stoolap 0.4.0

High-performance embedded SQL database with MVCC, time-travel queries, and full ACID compliance
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
// Copyright 2025 Stoolap Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Math scalar functions

use crate::core::{Error, Result, Value};
use crate::functions::{
    FunctionDataType, FunctionInfo, FunctionSignature, FunctionType, ScalarFunction,
};
use crate::validate_arg_count;
use rand::Rng;

use super::{value_to_f64, value_to_i64};

// ============================================================================
// ABS
// ============================================================================

/// ABS function - returns the absolute value of a number
#[derive(Default)]
pub struct AbsFunction;

impl ScalarFunction for AbsFunction {
    fn name(&self) -> &str {
        "ABS"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "ABS",
            FunctionType::Scalar,
            "Returns the absolute value of a number",
            FunctionSignature::new(FunctionDataType::Float, vec![FunctionDataType::Any], 1, 1),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "ABS", 1);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        // Try to preserve integer type if possible
        if let Some(i) = value_to_i64(&args[0]) {
            if matches!(args[0], Value::Integer(_)) {
                return match i.checked_abs() {
                    Some(abs) => Ok(Value::Integer(abs)),
                    None => Ok(Value::Null(crate::core::DataType::Integer)), // i64::MIN overflow
                };
            }
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("ABS argument must be a number"))?;

        Ok(Value::Float(num.abs()))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(AbsFunction)
    }
}

// ============================================================================
// ROUND
// ============================================================================

/// ROUND function - rounds a number to a specified number of decimal places
#[derive(Default)]
pub struct RoundFunction;

impl ScalarFunction for RoundFunction {
    fn name(&self) -> &str {
        "ROUND"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "ROUND",
            FunctionType::Scalar,
            "Rounds a number to a specified number of decimal places",
            FunctionSignature::new(
                FunctionDataType::Float,
                vec![FunctionDataType::Any, FunctionDataType::Integer],
                1,
                2,
            ),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "ROUND", 1, 2);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("ROUND first argument must be a number"))?;

        // Default to 0 decimal places if not specified
        let places = if args.len() == 2 && !args[1].is_null() {
            value_to_i64(&args[1])
                .ok_or_else(|| Error::invalid_argument("ROUND decimal places must be an integer"))?
                as i32
        } else {
            0
        };

        // Round to specified decimal places
        let shift = 10_f64.powi(places);
        let rounded = (num * shift).round() / shift;

        Ok(Value::Float(rounded))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(RoundFunction)
    }
}

// ============================================================================
// FLOOR
// ============================================================================

/// FLOOR function - returns the largest integer value not greater than the argument
#[derive(Default)]
pub struct FloorFunction;

impl ScalarFunction for FloorFunction {
    fn name(&self) -> &str {
        "FLOOR"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "FLOOR",
            FunctionType::Scalar,
            "Returns the largest integer value not greater than the argument",
            FunctionSignature::new(FunctionDataType::Float, vec![FunctionDataType::Any], 1, 1),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "FLOOR", 1);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("FLOOR argument must be a number"))?;

        Ok(Value::Float(num.floor()))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(FloorFunction)
    }
}

// ============================================================================
// CEILING
// ============================================================================

/// CEILING function - returns the smallest integer value not less than the argument
#[derive(Default)]
pub struct CeilingFunction;

impl ScalarFunction for CeilingFunction {
    fn name(&self) -> &str {
        "CEILING"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "CEILING",
            FunctionType::Scalar,
            "Returns the smallest integer value not less than the argument",
            FunctionSignature::new(FunctionDataType::Float, vec![FunctionDataType::Any], 1, 1),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "CEILING", 1);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("CEILING argument must be a number"))?;

        Ok(Value::Float(num.ceil()))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(CeilingFunction)
    }
}

// ============================================================================
// CEIL (alias for CEILING)
// ============================================================================

/// CEIL function - alias for CEILING, returns the smallest integer value not less than the argument
#[derive(Default)]
pub struct CeilFunction;

impl ScalarFunction for CeilFunction {
    fn name(&self) -> &str {
        "CEIL"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "CEIL",
            FunctionType::Scalar,
            "Returns the smallest integer value not less than the argument (alias for CEILING)",
            FunctionSignature::new(FunctionDataType::Float, vec![FunctionDataType::Any], 1, 1),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "CEIL", 1);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("CEIL argument must be a number"))?;

        Ok(Value::Float(num.ceil()))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(CeilFunction)
    }
}

// ============================================================================
// MOD
// ============================================================================

/// MOD function - returns the remainder of a division
#[derive(Default)]
pub struct ModFunction;

impl ScalarFunction for ModFunction {
    fn name(&self) -> &str {
        "MOD"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "MOD",
            FunctionType::Scalar,
            "Returns the remainder of a division (modulo)",
            FunctionSignature::new(
                FunctionDataType::Integer,
                vec![FunctionDataType::Any, FunctionDataType::Any],
                2,
                2,
            ),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "MOD", 2);

        if args[0].is_null() || args[1].is_null() {
            return Ok(Value::null_unknown());
        }

        // Try integer modulo first
        if let (Some(a), Some(b)) = (value_to_i64(&args[0]), value_to_i64(&args[1])) {
            if b == 0 {
                return Err(Error::invalid_argument("MOD: division by zero"));
            }
            return Ok(Value::Integer(a % b));
        }

        // Fall back to float modulo
        let a = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("MOD first argument must be a number"))?;
        let b = value_to_f64(&args[1])
            .ok_or_else(|| Error::invalid_argument("MOD second argument must be a number"))?;

        if b == 0.0 {
            return Err(Error::invalid_argument("MOD: division by zero"));
        }

        Ok(Value::Float(a % b))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(ModFunction)
    }
}

// ============================================================================
// POWER / POW
// ============================================================================

/// POWER function - returns base raised to the power of exponent
#[derive(Default)]
pub struct PowerFunction;

impl ScalarFunction for PowerFunction {
    fn name(&self) -> &str {
        "POWER"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "POWER",
            FunctionType::Scalar,
            "Returns base raised to the power of exponent",
            FunctionSignature::new(
                FunctionDataType::Float,
                vec![FunctionDataType::Any, FunctionDataType::Any],
                2,
                2,
            ),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "POWER", 2);

        if args[0].is_null() || args[1].is_null() {
            return Ok(Value::null_unknown());
        }

        let base = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("POWER base must be a number"))?;
        let exp = value_to_f64(&args[1])
            .ok_or_else(|| Error::invalid_argument("POWER exponent must be a number"))?;

        Ok(Value::Float(base.powf(exp)))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(PowerFunction)
    }
}

/// POW function - alias for POWER
#[derive(Default)]
pub struct PowFunction;

impl ScalarFunction for PowFunction {
    fn name(&self) -> &str {
        "POW"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "POW",
            FunctionType::Scalar,
            "Returns base raised to the power of exponent (alias for POWER)",
            FunctionSignature::new(
                FunctionDataType::Float,
                vec![FunctionDataType::Any, FunctionDataType::Any],
                2,
                2,
            ),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        PowerFunction.evaluate(args)
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(PowFunction)
    }
}

// ============================================================================
// SQRT
// ============================================================================

/// SQRT function - returns the square root of a number
#[derive(Default)]
pub struct SqrtFunction;

impl ScalarFunction for SqrtFunction {
    fn name(&self) -> &str {
        "SQRT"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "SQRT",
            FunctionType::Scalar,
            "Returns the square root of a number",
            FunctionSignature::new(FunctionDataType::Float, vec![FunctionDataType::Any], 1, 1),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "SQRT", 1);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("SQRT argument must be a number"))?;

        if num < 0.0 {
            return Ok(Value::null_unknown()); // SQL standard returns NULL for negative input
        }

        Ok(Value::Float(num.sqrt()))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(SqrtFunction)
    }
}

// ============================================================================
// LOG (base 10)
// ============================================================================

/// LOG function - returns the base-10 logarithm of a number
#[derive(Default)]
pub struct LogFunction;

impl ScalarFunction for LogFunction {
    fn name(&self) -> &str {
        "LOG"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "LOG",
            FunctionType::Scalar,
            "Returns the base-10 logarithm of a number (or log with custom base)",
            FunctionSignature::new(
                FunctionDataType::Float,
                vec![FunctionDataType::Any, FunctionDataType::Any],
                1,
                2,
            ),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "LOG", 1, 2);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        if args.len() == 1 {
            // LOG(x) - base 10
            let num = value_to_f64(&args[0])
                .ok_or_else(|| Error::invalid_argument("LOG argument must be a number"))?;

            if num <= 0.0 {
                return Ok(Value::null_unknown());
            }

            Ok(Value::Float(num.log10()))
        } else {
            // LOG(base, x)
            if args[1].is_null() {
                return Ok(Value::null_unknown());
            }

            let base = value_to_f64(&args[0])
                .ok_or_else(|| Error::invalid_argument("LOG base must be a number"))?;
            let num = value_to_f64(&args[1])
                .ok_or_else(|| Error::invalid_argument("LOG argument must be a number"))?;

            if base <= 0.0 || base == 1.0 || num <= 0.0 {
                return Ok(Value::null_unknown());
            }

            Ok(Value::Float(num.log(base)))
        }
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(LogFunction)
    }
}

/// LOG10 function - returns the base-10 logarithm of a number
#[derive(Default)]
pub struct Log10Function;

impl ScalarFunction for Log10Function {
    fn name(&self) -> &str {
        "LOG10"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "LOG10",
            FunctionType::Scalar,
            "Returns the base-10 logarithm of a number",
            FunctionSignature::new(FunctionDataType::Float, vec![FunctionDataType::Any], 1, 1),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "LOG10", 1);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("LOG10 argument must be a number"))?;

        if num <= 0.0 {
            return Ok(Value::null_unknown());
        }

        Ok(Value::Float(num.log10()))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(Log10Function)
    }
}

/// LOG2 function - returns the base-2 logarithm of a number
#[derive(Default)]
pub struct Log2Function;

impl ScalarFunction for Log2Function {
    fn name(&self) -> &str {
        "LOG2"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "LOG2",
            FunctionType::Scalar,
            "Returns the base-2 logarithm of a number",
            FunctionSignature::new(FunctionDataType::Float, vec![FunctionDataType::Any], 1, 1),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "LOG2", 1);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("LOG2 argument must be a number"))?;

        if num <= 0.0 {
            return Ok(Value::null_unknown());
        }

        Ok(Value::Float(num.log2()))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(Log2Function)
    }
}

// ============================================================================
// LN (natural logarithm)
// ============================================================================

/// LN function - returns the natural logarithm of a number
#[derive(Default)]
pub struct LnFunction;

impl ScalarFunction for LnFunction {
    fn name(&self) -> &str {
        "LN"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "LN",
            FunctionType::Scalar,
            "Returns the natural logarithm (base e) of a number",
            FunctionSignature::new(FunctionDataType::Float, vec![FunctionDataType::Any], 1, 1),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "LN", 1);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("LN argument must be a number"))?;

        if num <= 0.0 {
            return Ok(Value::null_unknown());
        }

        Ok(Value::Float(num.ln()))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(LnFunction)
    }
}

// ============================================================================
// EXP
// ============================================================================

/// EXP function - returns e raised to the power of the argument
#[derive(Default)]
pub struct ExpFunction;

impl ScalarFunction for ExpFunction {
    fn name(&self) -> &str {
        "EXP"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "EXP",
            FunctionType::Scalar,
            "Returns e raised to the power of the argument",
            FunctionSignature::new(FunctionDataType::Float, vec![FunctionDataType::Any], 1, 1),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "EXP", 1);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("EXP argument must be a number"))?;

        Ok(Value::Float(num.exp()))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(ExpFunction)
    }
}

// ============================================================================
// SIGN
// ============================================================================

/// SIGN function - returns the sign of a number (-1, 0, or 1)
#[derive(Default)]
pub struct SignFunction;

impl ScalarFunction for SignFunction {
    fn name(&self) -> &str {
        "SIGN"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "SIGN",
            FunctionType::Scalar,
            "Returns the sign of a number (-1, 0, or 1)",
            FunctionSignature::new(FunctionDataType::Integer, vec![FunctionDataType::Any], 1, 1),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "SIGN", 1);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("SIGN argument must be a number"))?;

        let sign = if num > 0.0 {
            1
        } else if num < 0.0 {
            -1
        } else {
            0
        };

        Ok(Value::Integer(sign))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(SignFunction)
    }
}

// ============================================================================
// TRUNCATE / TRUNC
// ============================================================================

/// TRUNCATE function - truncates a number to a specified number of decimal places
#[derive(Default)]
pub struct TruncateFunction;

impl ScalarFunction for TruncateFunction {
    fn name(&self) -> &str {
        "TRUNCATE"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "TRUNCATE",
            FunctionType::Scalar,
            "Truncates a number to a specified number of decimal places",
            FunctionSignature::new(
                FunctionDataType::Float,
                vec![FunctionDataType::Any, FunctionDataType::Integer],
                1,
                2,
            ),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "TRUNCATE", 1, 2);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("TRUNCATE argument must be a number"))?;

        let places = if args.len() == 2 && !args[1].is_null() {
            value_to_i64(&args[1]).ok_or_else(|| {
                Error::invalid_argument("TRUNCATE decimal places must be an integer")
            })? as i32
        } else {
            0
        };

        let shift = 10_f64.powi(places);
        let truncated = (num * shift).trunc() / shift;

        Ok(Value::Float(truncated))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(TruncateFunction)
    }
}

/// TRUNC function - alias for TRUNCATE
#[derive(Default)]
pub struct TruncFunction;

impl ScalarFunction for TruncFunction {
    fn name(&self) -> &str {
        "TRUNC"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "TRUNC",
            FunctionType::Scalar,
            "Truncates a number to a specified number of decimal places (alias for TRUNCATE)",
            FunctionSignature::new(
                FunctionDataType::Float,
                vec![FunctionDataType::Any, FunctionDataType::Integer],
                1,
                2,
            ),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        TruncateFunction.evaluate(args)
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(TruncFunction)
    }
}

// ============================================================================
// PI
// ============================================================================

/// PI function - returns the value of pi
#[derive(Default)]
pub struct PiFunction;

impl ScalarFunction for PiFunction {
    fn name(&self) -> &str {
        "PI"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "PI",
            FunctionType::Scalar,
            "Returns the value of pi",
            FunctionSignature::new(FunctionDataType::Float, vec![], 0, 0),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        if !args.is_empty() {
            return Err(Error::invalid_argument(format!(
                "PI requires no arguments, got {}",
                args.len()
            )));
        }

        Ok(Value::Float(std::f64::consts::PI))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(PiFunction)
    }
}

// ============================================================================
// RANDOM / RAND
// ============================================================================

/// RANDOM function - returns a random float between 0 and 1
#[derive(Default)]
pub struct RandomFunction;

impl ScalarFunction for RandomFunction {
    fn name(&self) -> &str {
        "RANDOM"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "RANDOM",
            FunctionType::Scalar,
            "Returns a random float between 0 (inclusive) and 1 (exclusive)",
            FunctionSignature::new(FunctionDataType::Float, vec![], 0, 0),
        )
        .non_deterministic()
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        if !args.is_empty() {
            return Err(Error::invalid_argument(format!(
                "RANDOM requires no arguments, got {}",
                args.len()
            )));
        }

        // Use thread-local RNG for proper randomness
        let random = rand::rng().random::<f64>();

        Ok(Value::Float(random))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(RandomFunction)
    }
}

// ============================================================================
// SIN
// ============================================================================

/// SIN function - returns the sine of an angle (in radians)
#[derive(Default)]
pub struct SinFunction;

impl ScalarFunction for SinFunction {
    fn name(&self) -> &str {
        "SIN"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "SIN",
            FunctionType::Scalar,
            "Returns the sine of an angle (in radians)",
            FunctionSignature::new(FunctionDataType::Float, vec![FunctionDataType::Any], 1, 1),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "SIN", 1);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("SIN argument must be a number"))?;

        Ok(Value::Float(num.sin()))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(SinFunction)
    }
}

// ============================================================================
// COS
// ============================================================================

/// COS function - returns the cosine of an angle (in radians)
#[derive(Default)]
pub struct CosFunction;

impl ScalarFunction for CosFunction {
    fn name(&self) -> &str {
        "COS"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "COS",
            FunctionType::Scalar,
            "Returns the cosine of an angle (in radians)",
            FunctionSignature::new(FunctionDataType::Float, vec![FunctionDataType::Any], 1, 1),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "COS", 1);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("COS argument must be a number"))?;

        Ok(Value::Float(num.cos()))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(CosFunction)
    }
}

// ============================================================================
// TAN
// ============================================================================

/// TAN function - returns the tangent of an angle (in radians)
#[derive(Default)]
pub struct TanFunction;

impl ScalarFunction for TanFunction {
    fn name(&self) -> &str {
        "TAN"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "TAN",
            FunctionType::Scalar,
            "Returns the tangent of an angle (in radians)",
            FunctionSignature::new(FunctionDataType::Float, vec![FunctionDataType::Any], 1, 1),
        )
    }

    fn evaluate(&self, args: &[Value]) -> Result<Value> {
        validate_arg_count!(args, "TAN", 1);

        if args[0].is_null() {
            return Ok(Value::null_unknown());
        }

        let num = value_to_f64(&args[0])
            .ok_or_else(|| Error::invalid_argument("TAN argument must be a number"))?;

        Ok(Value::Float(num.tan()))
    }

    fn clone_box(&self) -> Box<dyn ScalarFunction> {
        Box::new(TanFunction)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_abs_positive() {
        let f = AbsFunction;
        assert_eq!(
            f.evaluate(&[Value::Integer(42)]).unwrap(),
            Value::Integer(42)
        );
        assert_eq!(f.evaluate(&[Value::Float(3.5)]).unwrap(), Value::Float(3.5));
    }

    #[test]
    fn test_abs_negative() {
        let f = AbsFunction;
        assert_eq!(
            f.evaluate(&[Value::Integer(-42)]).unwrap(),
            Value::Integer(42)
        );
        assert_eq!(
            f.evaluate(&[Value::Float(-3.5)]).unwrap(),
            Value::Float(3.5)
        );
    }

    #[test]
    fn test_abs_null() {
        let f = AbsFunction;
        assert!(f.evaluate(&[Value::null_unknown()]).unwrap().is_null());
    }

    #[test]
    fn test_abs_zero() {
        let f = AbsFunction;
        assert_eq!(f.evaluate(&[Value::Integer(0)]).unwrap(), Value::Integer(0));
        assert_eq!(f.evaluate(&[Value::Float(0.0)]).unwrap(), Value::Float(0.0));
    }

    #[test]
    fn test_round_default() {
        let f = RoundFunction;
        assert_eq!(f.evaluate(&[Value::Float(3.7)]).unwrap(), Value::Float(4.0));
        assert_eq!(f.evaluate(&[Value::Float(3.2)]).unwrap(), Value::Float(3.0));
        assert_eq!(f.evaluate(&[Value::Float(3.5)]).unwrap(), Value::Float(4.0));
    }

    #[test]
    fn test_round_with_places() {
        let f = RoundFunction;
        assert_eq!(
            f.evaluate(&[Value::Float(3.54159), Value::Integer(2)])
                .unwrap(),
            Value::Float(3.54)
        );
        assert_eq!(
            f.evaluate(&[Value::Float(3.54159), Value::Integer(4)])
                .unwrap(),
            Value::Float(3.5416)
        );
        assert_eq!(
            f.evaluate(&[Value::Float(1234.5678), Value::Integer(0)])
                .unwrap(),
            Value::Float(1235.0)
        );
    }

    #[test]
    fn test_round_negative_places() {
        let f = RoundFunction;
        // Round to tens
        assert_eq!(
            f.evaluate(&[Value::Float(1234.5), Value::Integer(-1)])
                .unwrap(),
            Value::Float(1230.0)
        );
        // Round to hundreds
        assert_eq!(
            f.evaluate(&[Value::Float(1234.5), Value::Integer(-2)])
                .unwrap(),
            Value::Float(1200.0)
        );
    }

    #[test]
    fn test_round_null() {
        let f = RoundFunction;
        assert!(f.evaluate(&[Value::null_unknown()]).unwrap().is_null());
        assert_eq!(
            f.evaluate(&[Value::Float(3.5), Value::null_unknown()])
                .unwrap(),
            Value::Float(4.0)
        );
    }

    #[test]
    fn test_floor() {
        let f = FloorFunction;
        assert_eq!(f.evaluate(&[Value::Float(3.7)]).unwrap(), Value::Float(3.0));
        assert_eq!(f.evaluate(&[Value::Float(3.2)]).unwrap(), Value::Float(3.0));
        assert_eq!(
            f.evaluate(&[Value::Float(-3.2)]).unwrap(),
            Value::Float(-4.0)
        );
        assert_eq!(f.evaluate(&[Value::Integer(5)]).unwrap(), Value::Float(5.0));
    }

    #[test]
    fn test_floor_null() {
        let f = FloorFunction;
        assert!(f.evaluate(&[Value::null_unknown()]).unwrap().is_null());
    }

    #[test]
    fn test_ceiling() {
        let f = CeilingFunction;
        assert_eq!(f.evaluate(&[Value::Float(3.7)]).unwrap(), Value::Float(4.0));
        assert_eq!(f.evaluate(&[Value::Float(3.2)]).unwrap(), Value::Float(4.0));
        assert_eq!(
            f.evaluate(&[Value::Float(-3.2)]).unwrap(),
            Value::Float(-3.0)
        );
        assert_eq!(f.evaluate(&[Value::Integer(5)]).unwrap(), Value::Float(5.0));
    }

    #[test]
    fn test_ceiling_null() {
        let f = CeilingFunction;
        assert!(f.evaluate(&[Value::null_unknown()]).unwrap().is_null());
    }

    #[test]
    fn test_abs_string_number() {
        let f = AbsFunction;
        assert_eq!(
            f.evaluate(&[Value::text("-42.5")]).unwrap(),
            Value::Float(42.5)
        );
    }

    #[test]
    fn test_abs_invalid_arg_count() {
        let f = AbsFunction;
        assert!(f.evaluate(&[]).is_err());
        assert!(f.evaluate(&[Value::Integer(1), Value::Integer(2)]).is_err());
    }

    #[test]
    fn test_sin() {
        let f = SinFunction;
        // sin(0) = 0
        let result = f.evaluate(&[Value::Float(0.0)]).unwrap();
        if let Value::Float(v) = result {
            assert!((v - 0.0).abs() < 1e-10);
        } else {
            panic!("Expected Float");
        }
        // sin(π/2) = 1
        let result = f
            .evaluate(&[Value::Float(std::f64::consts::FRAC_PI_2)])
            .unwrap();
        if let Value::Float(v) = result {
            assert!((v - 1.0).abs() < 1e-10);
        } else {
            panic!("Expected Float");
        }
        // sin(π) ≈ 0
        let result = f.evaluate(&[Value::Float(std::f64::consts::PI)]).unwrap();
        if let Value::Float(v) = result {
            assert!(v.abs() < 1e-10);
        } else {
            panic!("Expected Float");
        }
    }

    #[test]
    fn test_sin_null() {
        let f = SinFunction;
        assert!(f.evaluate(&[Value::null_unknown()]).unwrap().is_null());
    }

    #[test]
    fn test_cos() {
        let f = CosFunction;
        // cos(0) = 1
        let result = f.evaluate(&[Value::Float(0.0)]).unwrap();
        if let Value::Float(v) = result {
            assert!((v - 1.0).abs() < 1e-10);
        } else {
            panic!("Expected Float");
        }
        // cos(π/2) ≈ 0
        let result = f
            .evaluate(&[Value::Float(std::f64::consts::FRAC_PI_2)])
            .unwrap();
        if let Value::Float(v) = result {
            assert!(v.abs() < 1e-10);
        } else {
            panic!("Expected Float");
        }
        // cos(π) = -1
        let result = f.evaluate(&[Value::Float(std::f64::consts::PI)]).unwrap();
        if let Value::Float(v) = result {
            assert!((v - (-1.0)).abs() < 1e-10);
        } else {
            panic!("Expected Float");
        }
    }

    #[test]
    fn test_cos_null() {
        let f = CosFunction;
        assert!(f.evaluate(&[Value::null_unknown()]).unwrap().is_null());
    }

    #[test]
    fn test_tan() {
        let f = TanFunction;
        // tan(0) = 0
        let result = f.evaluate(&[Value::Float(0.0)]).unwrap();
        if let Value::Float(v) = result {
            assert!((v - 0.0).abs() < 1e-10);
        } else {
            panic!("Expected Float");
        }
        // tan(π/4) = 1
        let result = f
            .evaluate(&[Value::Float(std::f64::consts::FRAC_PI_4)])
            .unwrap();
        if let Value::Float(v) = result {
            assert!((v - 1.0).abs() < 1e-10);
        } else {
            panic!("Expected Float");
        }
        // tan(π) ≈ 0
        let result = f.evaluate(&[Value::Float(std::f64::consts::PI)]).unwrap();
        if let Value::Float(v) = result {
            assert!(v.abs() < 1e-10);
        } else {
            panic!("Expected Float");
        }
    }

    #[test]
    fn test_tan_null() {
        let f = TanFunction;
        assert!(f.evaluate(&[Value::null_unknown()]).unwrap().is_null());
    }

    #[test]
    fn test_trig_with_integers() {
        // Test that integer inputs work correctly
        let sin_f = SinFunction;
        let cos_f = CosFunction;
        let tan_f = TanFunction;

        // sin(0) = 0
        assert!(sin_f.evaluate(&[Value::Integer(0)]).is_ok());
        // cos(0) = 1
        let result = cos_f.evaluate(&[Value::Integer(0)]).unwrap();
        if let Value::Float(v) = result {
            assert!((v - 1.0).abs() < 1e-10);
        }
        // tan(0) = 0
        assert!(tan_f.evaluate(&[Value::Integer(0)]).is_ok());
    }

    #[test]
    fn test_trig_invalid_args() {
        let sin_f = SinFunction;
        let cos_f = CosFunction;
        let tan_f = TanFunction;

        assert!(sin_f.evaluate(&[]).is_err());
        assert!(cos_f.evaluate(&[]).is_err());
        assert!(tan_f.evaluate(&[]).is_err());

        assert!(sin_f
            .evaluate(&[Value::Integer(1), Value::Integer(2)])
            .is_err());
        assert!(cos_f
            .evaluate(&[Value::Integer(1), Value::Integer(2)])
            .is_err());
        assert!(tan_f
            .evaluate(&[Value::Integer(1), Value::Integer(2)])
            .is_err());
    }
}