sql-cli 1.72.0

SQL query tool for CSV/JSON with both interactive TUI and non-interactive CLI modes - perfect for exploration and automation
Documentation
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
use anyhow::{anyhow, Result};

use super::{ArgCount, FunctionCategory, FunctionSignature, SqlFunction};
use crate::data::datatable::DataValue;

/// Trait for method-style functions that operate on a column/value
/// These are called with dot notation: column.Method(args)
pub trait MethodFunction: SqlFunction {
    /// Check if this method function handles the given method name
    fn handles_method(&self, method_name: &str) -> bool;

    /// Get the method name this function handles
    fn method_name(&self) -> &'static str;

    /// Evaluate as a method (first arg is implicit 'self')
    fn evaluate_method(&self, receiver: &DataValue, args: &[DataValue]) -> Result<DataValue> {
        // Default implementation: prepend receiver to args and call evaluate
        let mut full_args = vec![receiver.clone()];
        full_args.extend_from_slice(args);
        self.evaluate(&full_args)
    }
}

/// `ToUpper` method function
pub struct ToUpperMethod;

impl SqlFunction for ToUpperMethod {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "TOUPPER",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(1),
            description: "Converts string to uppercase",
            returns: "STRING",
            examples: vec![
                "SELECT name.ToUpper() FROM users",
                "SELECT TOUPPER(name) FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        match &args[0] {
            DataValue::String(s) => Ok(DataValue::String(s.to_uppercase())),
            DataValue::InternedString(s) => Ok(DataValue::String(s.to_uppercase())),
            DataValue::Null => Ok(DataValue::Null),
            _ => Err(anyhow!("ToUpper expects a string argument")),
        }
    }
}

impl MethodFunction for ToUpperMethod {
    fn handles_method(&self, method_name: &str) -> bool {
        method_name.eq_ignore_ascii_case("ToUpper")
            || method_name.eq_ignore_ascii_case("ToUpperCase")
    }

    fn method_name(&self) -> &'static str {
        "ToUpper"
    }
}

/// `ToLower` method function
pub struct ToLowerMethod;

impl SqlFunction for ToLowerMethod {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "TOLOWER",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(1),
            description: "Converts string to lowercase",
            returns: "STRING",
            examples: vec![
                "SELECT name.ToLower() FROM users",
                "SELECT TOLOWER(name) FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        match &args[0] {
            DataValue::String(s) => Ok(DataValue::String(s.to_lowercase())),
            DataValue::InternedString(s) => Ok(DataValue::String(s.to_lowercase())),
            DataValue::Null => Ok(DataValue::Null),
            _ => Err(anyhow!("ToLower expects a string argument")),
        }
    }
}

impl MethodFunction for ToLowerMethod {
    fn handles_method(&self, method_name: &str) -> bool {
        method_name.eq_ignore_ascii_case("ToLower")
            || method_name.eq_ignore_ascii_case("ToLowerCase")
    }

    fn method_name(&self) -> &'static str {
        "ToLower"
    }
}

/// Trim method function
pub struct TrimMethod;

impl SqlFunction for TrimMethod {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "TRIM",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(1),
            description: "Removes leading and trailing whitespace",
            returns: "STRING",
            examples: vec![
                "SELECT name.Trim() FROM users",
                "SELECT TRIM(name) FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        match &args[0] {
            DataValue::String(s) => Ok(DataValue::String(s.trim().to_string())),
            DataValue::InternedString(s) => Ok(DataValue::String(s.trim().to_string())),
            DataValue::Null => Ok(DataValue::Null),
            _ => Err(anyhow!("Trim expects a string argument")),
        }
    }
}

impl MethodFunction for TrimMethod {
    fn handles_method(&self, method_name: &str) -> bool {
        method_name.eq_ignore_ascii_case("Trim")
    }

    fn method_name(&self) -> &'static str {
        "Trim"
    }
}

/// TrimStart method function
pub struct TrimStartMethod;

impl SqlFunction for TrimStartMethod {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "TRIMSTART",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(1),
            description: "Removes leading whitespace",
            returns: "STRING",
            examples: vec![
                "SELECT name.TrimStart() FROM users",
                "SELECT TRIMSTART(name) FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        match &args[0] {
            DataValue::String(s) => Ok(DataValue::String(s.trim_start().to_string())),
            DataValue::InternedString(s) => Ok(DataValue::String(s.trim_start().to_string())),
            DataValue::Null => Ok(DataValue::Null),
            _ => Err(anyhow!("TrimStart expects a string argument")),
        }
    }
}

impl MethodFunction for TrimStartMethod {
    fn handles_method(&self, method_name: &str) -> bool {
        method_name.eq_ignore_ascii_case("TrimStart")
    }

    fn method_name(&self) -> &'static str {
        "TrimStart"
    }
}

/// TrimEnd method function
pub struct TrimEndMethod;

impl SqlFunction for TrimEndMethod {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "TRIMEND",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(1),
            description: "Removes trailing whitespace",
            returns: "STRING",
            examples: vec![
                "SELECT name.TrimEnd() FROM users",
                "SELECT TRIMEND(name) FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        match &args[0] {
            DataValue::String(s) => Ok(DataValue::String(s.trim_end().to_string())),
            DataValue::InternedString(s) => Ok(DataValue::String(s.trim_end().to_string())),
            DataValue::Null => Ok(DataValue::Null),
            _ => Err(anyhow!("TrimEnd expects a string argument")),
        }
    }
}

impl MethodFunction for TrimEndMethod {
    fn handles_method(&self, method_name: &str) -> bool {
        method_name.eq_ignore_ascii_case("TrimEnd")
    }

    fn method_name(&self) -> &'static str {
        "TrimEnd"
    }
}

/// Length method function (returns integer)
pub struct LengthMethod;

impl SqlFunction for LengthMethod {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "LENGTH",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(1),
            description: "Returns the length of a string",
            returns: "INTEGER",
            examples: vec![
                "SELECT name.Length() FROM users",
                "SELECT LENGTH(name) FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        match &args[0] {
            DataValue::String(s) => Ok(DataValue::Integer(s.len() as i64)),
            DataValue::InternedString(s) => Ok(DataValue::Integer(s.len() as i64)),
            DataValue::Null => Ok(DataValue::Null),
            _ => Err(anyhow!("Length expects a string argument")),
        }
    }
}

impl MethodFunction for LengthMethod {
    fn handles_method(&self, method_name: &str) -> bool {
        method_name.eq_ignore_ascii_case("Length") || method_name.eq_ignore_ascii_case("Len")
    }

    fn method_name(&self) -> &'static str {
        "Length"
    }
}

/// Contains method function (returns boolean)
pub struct ContainsMethod;

impl SqlFunction for ContainsMethod {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "CONTAINS",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(2),
            description: "Checks if string contains substring",
            returns: "BOOLEAN",
            examples: vec![
                "SELECT * FROM users WHERE name.Contains('john')",
                "SELECT CONTAINS(name, 'john') FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let haystack = match &args[0] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Boolean(false)),
            _ => return Err(anyhow!("Contains expects string arguments")),
        };

        let needle = match &args[1] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Boolean(false)),
            _ => return Err(anyhow!("Contains expects string arguments")),
        };

        Ok(DataValue::Boolean(haystack.contains(needle)))
    }
}

impl MethodFunction for ContainsMethod {
    fn handles_method(&self, method_name: &str) -> bool {
        method_name.eq_ignore_ascii_case("Contains")
    }

    fn method_name(&self) -> &'static str {
        "Contains"
    }
}

/// `StartsWith` method function
pub struct StartsWithMethod;

impl SqlFunction for StartsWithMethod {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "STARTSWITH",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(2),
            description: "Checks if string starts with prefix",
            returns: "BOOLEAN",
            examples: vec![
                "SELECT * FROM users WHERE name.StartsWith('John')",
                "SELECT STARTSWITH(name, 'John') FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let string = match &args[0] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Boolean(false)),
            _ => return Err(anyhow!("StartsWith expects string arguments")),
        };

        let prefix = match &args[1] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Boolean(false)),
            _ => return Err(anyhow!("StartsWith expects string arguments")),
        };

        Ok(DataValue::Boolean(string.starts_with(prefix)))
    }
}

impl MethodFunction for StartsWithMethod {
    fn handles_method(&self, method_name: &str) -> bool {
        method_name.eq_ignore_ascii_case("StartsWith")
    }

    fn method_name(&self) -> &'static str {
        "StartsWith"
    }
}

/// `EndsWith` method function
pub struct EndsWithMethod;

impl SqlFunction for EndsWithMethod {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "ENDSWITH",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(2),
            description: "Checks if string ends with suffix",
            returns: "BOOLEAN",
            examples: vec![
                "SELECT * FROM users WHERE email.EndsWith('.com')",
                "SELECT ENDSWITH(email, '.com') FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let string = match &args[0] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Boolean(false)),
            _ => return Err(anyhow!("EndsWith expects string arguments")),
        };

        let suffix = match &args[1] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Boolean(false)),
            _ => return Err(anyhow!("EndsWith expects string arguments")),
        };

        Ok(DataValue::Boolean(string.ends_with(suffix)))
    }
}

impl MethodFunction for EndsWithMethod {
    fn handles_method(&self, method_name: &str) -> bool {
        method_name.eq_ignore_ascii_case("EndsWith")
    }

    fn method_name(&self) -> &'static str {
        "EndsWith"
    }
}

/// Substring method function
pub struct SubstringMethod;

impl SqlFunction for SubstringMethod {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "SUBSTRING",
            category: FunctionCategory::String,
            arg_count: ArgCount::Range(2, 3),
            description: "Extracts substring from string",
            returns: "STRING",
            examples: vec![
                "SELECT name.Substring(0, 5) FROM users",
                "SELECT SUBSTRING(name, 0, 5) FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        if args.len() < 2 || args.len() > 3 {
            return Err(anyhow!("Substring expects 2 or 3 arguments"));
        }

        let string = match &args[0] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("Substring expects a string as first argument")),
        };

        let start = match &args[1] {
            DataValue::Integer(i) => *i as usize,
            _ => return Err(anyhow!("Substring expects integer start position")),
        };

        let result = if args.len() == 3 {
            let length = match &args[2] {
                DataValue::Integer(i) => *i as usize,
                _ => return Err(anyhow!("Substring expects integer length")),
            };

            let end = (start + length).min(string.len());
            string.chars().skip(start).take(end - start).collect()
        } else {
            string.chars().skip(start).collect()
        };

        Ok(DataValue::String(result))
    }
}

impl MethodFunction for SubstringMethod {
    fn handles_method(&self, method_name: &str) -> bool {
        method_name.eq_ignore_ascii_case("Substring") || method_name.eq_ignore_ascii_case("Substr")
    }

    fn method_name(&self) -> &'static str {
        "Substring"
    }
}

/// Replace method function
pub struct ReplaceMethod;

impl SqlFunction for ReplaceMethod {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "REPLACE",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(3),
            description: "Replaces all occurrences of a substring",
            returns: "STRING",
            examples: vec![
                "SELECT name.Replace('John', 'Jane') FROM users",
                "SELECT REPLACE(name, 'John', 'Jane') FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let string = match &args[0] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("Replace expects string arguments")),
        };

        let from = match &args[1] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            _ => return Err(anyhow!("Replace expects string arguments")),
        };

        let to = match &args[2] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            _ => return Err(anyhow!("Replace expects string arguments")),
        };

        Ok(DataValue::String(string.replace(from, to)))
    }
}

impl MethodFunction for ReplaceMethod {
    fn handles_method(&self, method_name: &str) -> bool {
        method_name.eq_ignore_ascii_case("Replace")
    }

    fn method_name(&self) -> &'static str {
        "Replace"
    }
}

/// MID function - Extract substring (SQL/Excel compatible, 1-based indexing)
pub struct MidFunction;

impl SqlFunction for MidFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "MID",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(3),
            description: "Extract substring from text (1-based indexing)",
            returns: "STRING",
            examples: vec![
                "SELECT MID('Hello', 1, 3)", // Returns 'Hel'
                "SELECT MID('World', 2, 3)", // Returns 'orl'
                "SELECT MID(name, 1, 5) FROM table",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        // Get the string
        let text = match &args[0] {
            DataValue::String(s) => s.clone(),
            DataValue::InternedString(s) => s.to_string(),
            DataValue::Integer(n) => n.to_string(),
            DataValue::Float(f) => f.to_string(),
            DataValue::Null => String::new(),
            _ => return Err(anyhow!("MID first argument must be convertible to text")),
        };

        // Get start position (1-based)
        let start_pos = match &args[1] {
            DataValue::Integer(n) => *n,
            DataValue::Float(f) => *f as i64,
            _ => return Err(anyhow!("MID start position must be a number")),
        };

        // Get length
        let length = match &args[2] {
            DataValue::Integer(n) => *n,
            DataValue::Float(f) => *f as i64,
            _ => return Err(anyhow!("MID length must be a number")),
        };

        // Validate arguments
        if start_pos < 1 {
            return Err(anyhow!("MID start position must be >= 1"));
        }
        if length < 0 {
            return Err(anyhow!("MID length must be >= 0"));
        }

        // Convert to 0-based index
        let start_idx = (start_pos - 1) as usize;
        let chars: Vec<char> = text.chars().collect();

        // If start position is beyond string length, return empty string
        if start_idx >= chars.len() {
            return Ok(DataValue::String(String::new()));
        }

        // Extract substring
        let end_idx = std::cmp::min(start_idx + length as usize, chars.len());
        let result: String = chars[start_idx..end_idx].iter().collect();

        Ok(DataValue::String(result))
    }
}

/// UPPER function - Convert string to uppercase
pub struct UpperFunction;

impl SqlFunction for UpperFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "UPPER",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(1),
            description: "Convert string to uppercase",
            returns: "STRING",
            examples: vec![
                "SELECT UPPER('hello')", // Returns 'HELLO'
                "SELECT UPPER(name) FROM table",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        match &args[0] {
            DataValue::String(s) => Ok(DataValue::String(s.to_uppercase())),
            DataValue::InternedString(s) => Ok(DataValue::String(s.to_uppercase())),
            DataValue::Null => Ok(DataValue::Null),
            _ => Err(anyhow!("UPPER expects a string argument")),
        }
    }
}

/// LOWER function - Convert string to lowercase
pub struct LowerFunction;

impl SqlFunction for LowerFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "LOWER",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(1),
            description: "Convert string to lowercase",
            returns: "STRING",
            examples: vec![
                "SELECT LOWER('HELLO')", // Returns 'hello'
                "SELECT LOWER(name) FROM table",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        match &args[0] {
            DataValue::String(s) => Ok(DataValue::String(s.to_lowercase())),
            DataValue::InternedString(s) => Ok(DataValue::String(s.to_lowercase())),
            DataValue::Null => Ok(DataValue::Null),
            _ => Err(anyhow!("LOWER expects a string argument")),
        }
    }
}

/// TRIM function - Remove leading and trailing whitespace
pub struct TrimFunction;

impl SqlFunction for TrimFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "TRIM",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(1),
            description: "Remove leading and trailing whitespace",
            returns: "STRING",
            examples: vec![
                "SELECT TRIM('  hello  ')", // Returns 'hello'
                "SELECT TRIM(description) FROM table",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        match &args[0] {
            DataValue::String(s) => Ok(DataValue::String(s.trim().to_string())),
            DataValue::InternedString(s) => Ok(DataValue::String(s.trim().to_string())),
            DataValue::Null => Ok(DataValue::Null),
            _ => Err(anyhow!("TRIM expects a string argument")),
        }
    }
}

/// TEXTJOIN function - Join multiple text values with a delimiter
pub struct TextJoinFunction;

impl SqlFunction for TextJoinFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "TEXTJOIN",
            category: FunctionCategory::String,
            arg_count: ArgCount::Variadic,
            description: "Join multiple text values with a delimiter",
            returns: "STRING",
            examples: vec![
                "SELECT TEXTJOIN(',', 1, 'a', 'b', 'c')", // Returns 'a,b,c'
                "SELECT TEXTJOIN(' - ', 1, name, city) FROM table",
                "SELECT TEXTJOIN('|', 0, col1, col2, col3) FROM table",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        if args.len() < 3 {
            return Err(anyhow!("TEXTJOIN requires at least 3 arguments: delimiter, ignore_empty, text1, [text2, ...]"));
        }

        // First argument: delimiter
        let delimiter = match &args[0] {
            DataValue::String(s) => s.clone(),
            DataValue::InternedString(s) => s.to_string(),
            DataValue::Integer(n) => n.to_string(),
            DataValue::Float(f) => f.to_string(),
            DataValue::Boolean(b) => b.to_string(),
            DataValue::Null => String::new(),
            _ => String::new(),
        };

        // Second argument: ignore_empty (treat as boolean - 0 is false, anything else is true)
        let ignore_empty = match &args[1] {
            DataValue::Integer(n) => *n != 0,
            DataValue::Float(f) => *f != 0.0,
            DataValue::Boolean(b) => *b,
            DataValue::String(s) => !s.is_empty() && s != "0" && s.to_lowercase() != "false",
            DataValue::InternedString(s) => {
                !s.is_empty() && s.as_str() != "0" && s.to_lowercase() != "false"
            }
            DataValue::Null => false,
            _ => true,
        };

        // Remaining arguments: values to join
        let mut values = Vec::new();
        for i in 2..args.len() {
            let string_value = match &args[i] {
                DataValue::String(s) => Some(s.clone()),
                DataValue::InternedString(s) => Some(s.to_string()),
                DataValue::Integer(n) => Some(n.to_string()),
                DataValue::Float(f) => Some(f.to_string()),
                DataValue::Boolean(b) => Some(b.to_string()),
                DataValue::DateTime(dt) => Some(dt.clone()),
                DataValue::Vector(v) => {
                    let components: Vec<String> = v.iter().map(|f| f.to_string()).collect();
                    Some(format!("[{}]", components.join(",")))
                }
                DataValue::Null => {
                    if ignore_empty {
                        None
                    } else {
                        Some(String::new())
                    }
                }
            };

            if let Some(s) = string_value {
                if !ignore_empty || !s.is_empty() {
                    values.push(s);
                }
            }
        }

        Ok(DataValue::String(values.join(&delimiter)))
    }
}

/// Edit distance (Levenshtein distance) function
pub struct EditDistanceFunction;

impl EditDistanceFunction {
    /// Calculate the Levenshtein distance between two strings
    #[must_use]
    pub fn calculate_edit_distance(s1: &str, s2: &str) -> usize {
        let len1 = s1.len();
        let len2 = s2.len();
        let mut matrix = vec![vec![0; len2 + 1]; len1 + 1];

        for i in 0..=len1 {
            matrix[i][0] = i;
        }
        for j in 0..=len2 {
            matrix[0][j] = j;
        }

        for (i, c1) in s1.chars().enumerate() {
            for (j, c2) in s2.chars().enumerate() {
                let cost = usize::from(c1 != c2);
                matrix[i + 1][j + 1] = std::cmp::min(
                    matrix[i][j + 1] + 1, // deletion
                    std::cmp::min(
                        matrix[i + 1][j] + 1, // insertion
                        matrix[i][j] + cost,  // substitution
                    ),
                );
            }
        }

        matrix[len1][len2]
    }
}

impl SqlFunction for EditDistanceFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "EDIT_DISTANCE",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(2),
            description: "Calculate the Levenshtein edit distance between two strings",
            returns: "INTEGER",
            examples: vec![
                "SELECT EDIT_DISTANCE('kitten', 'sitting')",
                "SELECT EDIT_DISTANCE(name, 'John') FROM users",
                "SELECT * FROM users WHERE EDIT_DISTANCE(name, 'Smith') <= 2",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let s1 = match &args[0] {
            DataValue::String(s) => s.clone(),
            DataValue::InternedString(s) => s.to_string(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("EDIT_DISTANCE expects string arguments")),
        };

        let s2 = match &args[1] {
            DataValue::String(s) => s.clone(),
            DataValue::InternedString(s) => s.to_string(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("EDIT_DISTANCE expects string arguments")),
        };

        let distance = Self::calculate_edit_distance(&s1, &s2);
        Ok(DataValue::Integer(distance as i64))
    }
}

/// FREQUENCY function - Count occurrences of a substring in a string
pub struct FrequencyFunction;

impl SqlFunction for FrequencyFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "FREQUENCY",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(2),
            description: "Count occurrences of a substring within a string",
            returns: "INTEGER",
            examples: vec![
                "SELECT FREQUENCY('hello world', 'o')",  // Returns 2
                "SELECT FREQUENCY('mississippi', 'ss')", // Returns 2
                "SELECT FREQUENCY(text_column, 'error') FROM logs",
                "SELECT name, FREQUENCY(name, 'a') as a_count FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        // Get the string to search in
        let text = match &args[0] {
            DataValue::String(s) => s.clone(),
            DataValue::InternedString(s) => s.to_string(),
            DataValue::Null => return Ok(DataValue::Integer(0)),
            _ => return Err(anyhow!("FREQUENCY expects string as first argument")),
        };

        // Get the substring to search for
        let search = match &args[1] {
            DataValue::String(s) => s.clone(),
            DataValue::InternedString(s) => s.to_string(),
            DataValue::Null => return Ok(DataValue::Integer(0)),
            _ => return Err(anyhow!("FREQUENCY expects string as second argument")),
        };

        // Empty search string returns 0
        if search.is_empty() {
            return Ok(DataValue::Integer(0));
        }

        // Count occurrences
        let count = text.matches(&search).count();
        Ok(DataValue::Integer(count as i64))
    }
}

/// IndexOf method function - finds the position of a substring
pub struct IndexOfMethod;

impl SqlFunction for IndexOfMethod {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "INDEXOF",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(2),
            description: "Returns the position of the first occurrence of a substring (0-based)",
            returns: "INTEGER",
            examples: vec![
                "SELECT email.IndexOf('@') FROM users",
                "SELECT INDEXOF(email, '@') FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let string = match &args[0] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("IndexOf expects string arguments")),
        };

        let substring = match &args[1] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("IndexOf expects string arguments")),
        };

        match string.find(substring) {
            Some(pos) => Ok(DataValue::Integer(pos as i64)),
            None => Ok(DataValue::Integer(-1)), // Return -1 if not found
        }
    }
}

impl MethodFunction for IndexOfMethod {
    fn handles_method(&self, method_name: &str) -> bool {
        method_name.eq_ignore_ascii_case("IndexOf")
    }

    fn method_name(&self) -> &'static str {
        "IndexOf"
    }
}

/// INSTR function - SQL standard function for finding substring position
/// Returns 1-based position for SQL compatibility
pub struct InstrFunction;

impl SqlFunction for InstrFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "INSTR",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(2),
            description: "Returns the position of the first occurrence of a substring (1-based, SQL standard)",
            returns: "INTEGER",
            examples: vec![
                "SELECT INSTR(email, '@') FROM users",
                "SELECT SUBSTRING(email, INSTR(email, '@') + 1) FROM users",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let string = match &args[0] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("INSTR expects string arguments")),
        };

        let substring = match &args[1] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("INSTR expects string arguments")),
        };

        match string.find(substring) {
            Some(pos) => Ok(DataValue::Integer((pos + 1) as i64)), // 1-based for SQL
            None => Ok(DataValue::Integer(0)), // Return 0 if not found (SQL standard)
        }
    }
}

/// LEFT function - extracts leftmost n characters or up to a delimiter
pub struct LeftFunction;

impl SqlFunction for LeftFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "LEFT",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(2),
            description: "Returns leftmost n characters from string",
            returns: "STRING",
            examples: vec![
                "SELECT LEFT(email, 5) FROM users",
                "SELECT LEFT('hello@world', INSTR('hello@world', '@') - 1)",
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let string = match &args[0] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("LEFT expects a string as first argument")),
        };

        let length = match &args[1] {
            DataValue::Integer(n) => *n as usize,
            DataValue::Float(f) => *f as usize,
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("LEFT expects a number as second argument")),
        };

        let result = if length >= string.len() {
            string.to_string()
        } else {
            string.chars().take(length).collect()
        };

        Ok(DataValue::String(result))
    }
}

/// RIGHT function - extracts rightmost n characters
pub struct RightFunction;

impl SqlFunction for RightFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "RIGHT",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(2),
            description: "Returns rightmost n characters from string",
            returns: "STRING",
            examples: vec![
                "SELECT RIGHT(filename, 4) FROM files", // Get file extension
                "SELECT RIGHT(email, LENGTH(email) - INSTR(email, '@'))", // Get domain
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let string = match &args[0] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("RIGHT expects a string as first argument")),
        };

        let length = match &args[1] {
            DataValue::Integer(n) => *n as usize,
            DataValue::Float(f) => *f as usize,
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("RIGHT expects a number as second argument")),
        };

        let chars: Vec<char> = string.chars().collect();
        let start = if length >= chars.len() {
            0
        } else {
            chars.len() - length
        };

        let result: String = chars[start..].iter().collect();
        Ok(DataValue::String(result))
    }
}

/// SUBSTRING_BEFORE - returns substring before first/nth occurrence of delimiter
pub struct SubstringBeforeFunction;

impl SqlFunction for SubstringBeforeFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "SUBSTRING_BEFORE",
            category: FunctionCategory::String,
            arg_count: ArgCount::Range(2, 3),
            description: "Returns substring before the first (or nth) occurrence of delimiter",
            returns: "STRING",
            examples: vec![
                "SELECT SUBSTRING_BEFORE(email, '@') FROM users", // Get username
                "SELECT SUBSTRING_BEFORE('a.b.c.d', '.', 2)",     // Get 'a.b' (before 2nd dot)
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        if args.len() < 2 || args.len() > 3 {
            return Err(anyhow!("SUBSTRING_BEFORE expects 2 or 3 arguments"));
        }

        let string = match &args[0] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => {
                return Err(anyhow!(
                    "SUBSTRING_BEFORE expects a string as first argument"
                ))
            }
        };

        let delimiter = match &args[1] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("SUBSTRING_BEFORE expects a string delimiter")),
        };

        let occurrence = if args.len() == 3 {
            match &args[2] {
                DataValue::Integer(n) => *n as usize,
                DataValue::Float(f) => *f as usize,
                DataValue::Null => 1,
                _ => return Err(anyhow!("SUBSTRING_BEFORE expects a number for occurrence")),
            }
        } else {
            1
        };

        if occurrence == 0 {
            return Ok(DataValue::String(String::new()));
        }

        // Find the nth occurrence
        let mut count = 0;
        for (i, _) in string.match_indices(delimiter) {
            count += 1;
            if count == occurrence {
                return Ok(DataValue::String(string[..i].to_string()));
            }
        }

        // If we didn't find enough occurrences, return empty string
        Ok(DataValue::String(String::new()))
    }
}

/// SUBSTRING_AFTER - returns substring after first/nth occurrence of delimiter
pub struct SubstringAfterFunction;

impl SqlFunction for SubstringAfterFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "SUBSTRING_AFTER",
            category: FunctionCategory::String,
            arg_count: ArgCount::Range(2, 3),
            description: "Returns substring after the first (or nth) occurrence of delimiter",
            returns: "STRING",
            examples: vec![
                "SELECT SUBSTRING_AFTER(email, '@') FROM users", // Get domain
                "SELECT SUBSTRING_AFTER('a.b.c.d', '.', 2)",     // Get 'c.d' (after 2nd dot)
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        if args.len() < 2 || args.len() > 3 {
            return Err(anyhow!("SUBSTRING_AFTER expects 2 or 3 arguments"));
        }

        let string = match &args[0] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => {
                return Err(anyhow!(
                    "SUBSTRING_AFTER expects a string as first argument"
                ))
            }
        };

        let delimiter = match &args[1] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("SUBSTRING_AFTER expects a string delimiter")),
        };

        let occurrence = if args.len() == 3 {
            match &args[2] {
                DataValue::Integer(n) => *n as usize,
                DataValue::Float(f) => *f as usize,
                DataValue::Null => 1,
                _ => return Err(anyhow!("SUBSTRING_AFTER expects a number for occurrence")),
            }
        } else {
            1
        };

        if occurrence == 0 {
            return Ok(DataValue::String(string.to_string()));
        }

        // Find the nth occurrence
        let mut count = 0;
        for (i, _) in string.match_indices(delimiter) {
            count += 1;
            if count == occurrence {
                let start = i + delimiter.len();
                if start < string.len() {
                    return Ok(DataValue::String(string[start..].to_string()));
                } else {
                    return Ok(DataValue::String(String::new()));
                }
            }
        }

        // If we didn't find enough occurrences, return empty string
        Ok(DataValue::String(String::new()))
    }
}

/// SPLIT_PART - returns the nth part of a string split by delimiter (1-based)
pub struct SplitPartFunction;

impl SqlFunction for SplitPartFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "SPLIT_PART",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(3),
            description: "Returns the nth part of a string split by delimiter (1-based index)",
            returns: "STRING",
            examples: vec![
                "SELECT SPLIT_PART('a.b.c.d', '.', 2)",        // Returns 'b'
                "SELECT SPLIT_PART(email, '@', 1) FROM users", // Get username
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let string = match &args[0] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("SPLIT_PART expects a string as first argument")),
        };

        let delimiter = match &args[1] {
            DataValue::String(s) => s.as_str(),
            DataValue::InternedString(s) => s.as_str(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("SPLIT_PART expects a string delimiter")),
        };

        let part_num = match &args[2] {
            DataValue::Integer(n) => *n as usize,
            DataValue::Float(f) => *f as usize,
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("SPLIT_PART expects a number for part index")),
        };

        if part_num == 0 {
            return Err(anyhow!("SPLIT_PART part index must be >= 1"));
        }

        let parts: Vec<&str> = string.split(delimiter).collect();

        if part_num <= parts.len() {
            Ok(DataValue::String(parts[part_num - 1].to_string()))
        } else {
            Ok(DataValue::String(String::new()))
        }
    }
}

/// CHR function - Convert ASCII code to character
pub struct ChrFunction;

impl SqlFunction for ChrFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "CHR",
            category: FunctionCategory::String,
            arg_count: ArgCount::Fixed(1),
            description: "Convert ASCII code to character",
            returns: "STRING",
            examples: vec![
                "SELECT CHR(65)", // Returns 'A'
                "SELECT CHR(97)", // Returns 'a'
                "SELECT CHR(48)", // Returns '0'
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        if args.len() != 1 {
            return Err(anyhow!("CHR expects exactly 1 argument"));
        }

        let ascii_code = match &args[0] {
            DataValue::Integer(n) => *n,
            DataValue::Float(f) => *f as i64,
            DataValue::String(s) => s
                .parse::<i64>()
                .map_err(|_| anyhow!("Invalid number for CHR: {}", s))?,
            DataValue::InternedString(s) => s
                .parse::<i64>()
                .map_err(|_| anyhow!("Invalid number for CHR: {}", s))?,
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("CHR expects a numeric argument")),
        };

        // ASCII printable range is 32-126, but we'll allow 0-255
        if ascii_code < 0 || ascii_code > 255 {
            return Err(anyhow!(
                "CHR argument must be between 0 and 255, got {}",
                ascii_code
            ));
        }

        let ch = ascii_code as u8 as char;
        Ok(DataValue::String(ch.to_string()))
    }
}

/// LOREM_IPSUM function - generates Lorem Ipsum placeholder text
pub struct LoremIpsumFunction;

impl SqlFunction for LoremIpsumFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "LOREM_IPSUM",
            category: FunctionCategory::String,
            arg_count: ArgCount::Range(1, 3),
            description: "Generate Lorem Ipsum placeholder text with specified number of words",
            returns: "STRING",
            examples: vec![
                "SELECT LOREM_IPSUM(10)",        // 10 random Lorem Ipsum words
                "SELECT LOREM_IPSUM(50)",        // 50 words
                "SELECT LOREM_IPSUM(20, 1)",     // 20 words, starting with 'Lorem ipsum...'
                "SELECT LOREM_IPSUM(15, 0, id)", // 15 words, use id as seed for variation
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let num_words = match &args[0] {
            DataValue::Integer(n) if *n > 0 => *n as usize,
            DataValue::Float(f) if *f > 0.0 => *f as usize,
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("LOREM_IPSUM requires a positive number of words")),
        };

        // Check if we should start with traditional "Lorem ipsum..." opening
        let start_traditional = if args.len() > 1 {
            match &args[1] {
                DataValue::Integer(n) => *n != 0,
                DataValue::Boolean(b) => *b,
                _ => false,
            }
        } else {
            false
        };

        // Get optional seed for reproducible but varied results
        let seed_value = if args.len() > 2 {
            match &args[2] {
                DataValue::Integer(n) => *n as u64,
                DataValue::Float(f) => *f as u64,
                DataValue::String(s) => {
                    // Hash the string to get a numeric seed
                    let mut hash = 0u64;
                    for byte in s.bytes() {
                        hash = hash.wrapping_mul(31).wrapping_add(byte as u64);
                    }
                    hash
                }
                DataValue::Null => 0,
                _ => 0,
            }
        } else {
            0
        };

        // Lorem Ipsum word bank - traditional Latin placeholder text words
        const LOREM_WORDS: &[&str] = &[
            "lorem",
            "ipsum",
            "dolor",
            "sit",
            "amet",
            "consectetur",
            "adipiscing",
            "elit",
            "sed",
            "do",
            "eiusmod",
            "tempor",
            "incididunt",
            "ut",
            "labore",
            "et",
            "dolore",
            "magna",
            "aliqua",
            "enim",
            "ad",
            "minim",
            "veniam",
            "quis",
            "nostrud",
            "exercitation",
            "ullamco",
            "laboris",
            "nisi",
            "aliquip",
            "ex",
            "ea",
            "commodo",
            "consequat",
            "duis",
            "aute",
            "irure",
            "in",
            "reprehenderit",
            "voluptate",
            "velit",
            "esse",
            "cillum",
            "fugiat",
            "nulla",
            "pariatur",
            "excepteur",
            "sint",
            "occaecat",
            "cupidatat",
            "non",
            "proident",
            "sunt",
            "culpa",
            "qui",
            "officia",
            "deserunt",
            "mollit",
            "anim",
            "id",
            "est",
            "laborum",
            "perspiciatis",
            "unde",
            "omnis",
            "iste",
            "natus",
            "error",
            "voluptatem",
            "accusantium",
            "doloremque",
            "laudantium",
            "totam",
            "rem",
            "aperiam",
            "eaque",
            "ipsa",
            "quae",
            "ab",
            "illo",
            "inventore",
            "veritatis",
            "quasi",
            "architecto",
            "beatae",
            "vitae",
            "dicta",
            "explicabo",
            "nemo",
            "enim",
            "ipsam",
            "quia",
            "voluptas",
            "aspernatur",
            "aut",
            "odit",
            "fugit",
            "consequuntur",
            "magni",
            "dolores",
            "eos",
            "ratione",
            "sequi",
            "nesciunt",
            "neque",
            "porro",
            "quisquam",
            "dolorem",
            "adipisci",
            "numquam",
            "eius",
            "modi",
            "tempora",
            "incidunt",
            "magnam",
            "quaerat",
            "etiam",
            "minus",
            "soluta",
            "nobis",
            "eligendi",
            "optio",
            "cumque",
            "nihil",
            "impedit",
            "quo",
            "possimus",
            "suscipit",
            "laboriosam",
            "aliquid",
            "fuga",
            "distinctio",
            "libero",
            "tempore",
            "cum",
            "assumenda",
            "est",
            "omnis",
            "dolor",
            "repellendus",
            "temporibus",
            "autem",
            "quibusdam",
            "officiis",
            "debitis",
            "rerum",
            "necessitatibus",
            "saepe",
            "eveniet",
            "voluptates",
            "repudiandae",
            "molestiae",
            "recusandae",
            "itaque",
            "earum",
            "hic",
            "tenetur",
            "sapiente",
            "delectus",
            "reiciendis",
            "voluptatibus",
            "maiores",
            "alias",
            "consequatur",
            "perferendis",
            "doloribus",
            "asperiores",
            "repellat",
            "iusto",
            "odio",
            "dignissimos",
            "ducimus",
            "blanditiis",
            "praesentium",
            "voluptatum",
            "deleniti",
            "atque",
            "corrupti",
            "quos",
            "quas",
            "molestias",
            "excepturi",
            "occaecati",
            "provident",
            "similique",
            "mollitia",
            "animi",
            "illum",
            "dolorum",
            "fuga",
            "harum",
            "quidem",
            "rerum",
            "facilis",
            "expedita",
            "distinctio",
            "nam",
            "libero",
            "tempore",
            "cum",
            "soluta",
            "nobis",
            "eligendi",
            "optio",
            "cumque",
            "nihil",
            "impedit",
            "minus",
            "quod",
            "maxime",
            "placeat",
            "facere",
            "possimus",
            "omnis",
            "voluptas",
            "assumenda",
        ];

        let mut result = Vec::with_capacity(num_words);

        if start_traditional && num_words > 0 {
            // Start with traditional "Lorem ipsum dolor sit amet..."
            let traditional_start = ["lorem", "ipsum", "dolor", "sit", "amet"];
            let take_count = num_words.min(traditional_start.len());
            for i in 0..take_count {
                result.push(traditional_start[i]);
            }

            // Fill remaining with random words
            let seed = if seed_value != 0 {
                seed_value
            } else {
                use std::time::{SystemTime, UNIX_EPOCH};
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_nanos() as u64
            };

            let mut rng = seed.wrapping_mul(num_words as u64); // Combine seed with word count
            for i in take_count..num_words {
                // Simple pseudo-random selection
                rng = (rng.wrapping_mul(1664525).wrapping_add(1013904223)) ^ (i as u64);
                let idx = (rng as usize) % LOREM_WORDS.len();
                result.push(LOREM_WORDS[idx]);
            }
        } else {
            // Generate random Lorem words
            let seed = if seed_value != 0 {
                seed_value
            } else {
                use std::time::{SystemTime, UNIX_EPOCH};
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_nanos() as u64
            };

            let mut rng = seed.wrapping_mul(num_words as u64).wrapping_add(12345); // Combine seed with word count
            for i in 0..num_words {
                // Simple pseudo-random selection with better entropy
                rng = (rng.wrapping_mul(1664525).wrapping_add(1013904223)) ^ (i as u64);
                let idx = (rng as usize) % LOREM_WORDS.len();
                result.push(LOREM_WORDS[idx]);
            }
        }

        // Capitalize first word and add periods for readability
        let mut text = String::new();
        for (i, word) in result.iter().enumerate() {
            if i == 0 {
                // Capitalize first word
                text.push_str(&word.chars().next().unwrap().to_uppercase().to_string());
                text.push_str(&word[1..]);
            } else {
                text.push(' ');
                // Occasionally start a new sentence (roughly every 10-15 words)
                if i > 0 && ((i * 7) % 13 == 0) && i < num_words - 1 {
                    text.pop(); // Remove the space
                    text.push_str(". ");
                    // Capitalize next word
                    text.push_str(&word.chars().next().unwrap().to_uppercase().to_string());
                    text.push_str(&word[1..]);
                } else {
                    text.push_str(word);
                }
            }
        }

        // Add final period if we generated text
        if !text.is_empty() {
            text.push('.');
        }

        Ok(DataValue::String(text))
    }
}

/// Register all string method functions
pub fn register_string_methods(registry: &mut super::FunctionRegistry) {
    use std::sync::Arc;

    // Register new string functions (non-method versions)
    registry.register(Box::new(MidFunction));
    registry.register(Box::new(UpperFunction));
    registry.register(Box::new(LowerFunction));
    registry.register(Box::new(TrimFunction));
    registry.register(Box::new(TextJoinFunction));
    registry.register(Box::new(EditDistanceFunction));
    registry.register(Box::new(FrequencyFunction));

    // Register new convenient string extraction functions
    registry.register(Box::new(LeftFunction));
    registry.register(Box::new(RightFunction));
    registry.register(Box::new(SubstringBeforeFunction));
    registry.register(Box::new(SubstringAfterFunction));
    registry.register(Box::new(SplitPartFunction));

    // Register ToUpper
    let to_upper = Arc::new(ToUpperMethod);
    registry.register(Box::new(ToUpperMethod));
    registry.register_method(to_upper);

    // Register ToLower
    let to_lower = Arc::new(ToLowerMethod);
    registry.register(Box::new(ToLowerMethod));
    registry.register_method(to_lower);

    // Register Trim
    let trim = Arc::new(TrimMethod);
    registry.register(Box::new(TrimMethod));
    registry.register_method(trim);

    // Register TrimStart
    let trim_start = Arc::new(TrimStartMethod);
    registry.register(Box::new(TrimStartMethod));
    registry.register_method(trim_start);

    // Register TrimEnd
    let trim_end = Arc::new(TrimEndMethod);
    registry.register(Box::new(TrimEndMethod));
    registry.register_method(trim_end);

    // Register Length
    let length = Arc::new(LengthMethod);
    registry.register(Box::new(LengthMethod));
    registry.register_method(length);

    // Register Contains
    let contains = Arc::new(ContainsMethod);
    registry.register(Box::new(ContainsMethod));
    registry.register_method(contains);

    // Register StartsWith
    let starts_with = Arc::new(StartsWithMethod);
    registry.register(Box::new(StartsWithMethod));
    registry.register_method(starts_with);

    // Register EndsWith
    let ends_with = Arc::new(EndsWithMethod);
    registry.register(Box::new(EndsWithMethod));
    registry.register_method(ends_with);

    // Register Substring
    let substring = Arc::new(SubstringMethod);
    registry.register(Box::new(SubstringMethod));
    registry.register_method(substring);

    // Register Replace
    let replace = Arc::new(ReplaceMethod);
    registry.register(Box::new(ReplaceMethod));
    registry.register_method(replace);

    // Register IndexOf/INSTR
    let indexof = Arc::new(IndexOfMethod);
    registry.register(Box::new(IndexOfMethod));
    registry.register_method(indexof.clone());
    // Also register as INSTR for SQL compatibility
    registry.register(Box::new(InstrFunction));

    // Register CHR function
    registry.register(Box::new(ChrFunction));

    // Register LOREM_IPSUM function
    registry.register(Box::new(LoremIpsumFunction));
}