graphitesql 0.0.5

A pure, safe, no_std Rust re-implementation of SQLite, compatible with the SQLite 3 file format.
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
//! Built-in scalar functions.
//!
//! Aggregate functions (`count`, `sum`, …) are handled by the executor, which
//! folds over rows; this module covers the per-row scalar functions. The set is
//! a useful core and grows toward SQLite's full library (`func.c`, `date.c`).

use super::eval::{self, EvalCtx};
use crate::error::{Error, Result};
use crate::sql::ast::Expr;
use crate::value::Value;
use alloc::string::String;
use alloc::vec::Vec;

/// Names that *can* be aggregates (used for catalog/name checks).
pub fn is_aggregate(name: &str) -> bool {
    matches!(
        name.to_ascii_lowercase().as_str(),
        "count" | "sum" | "total" | "avg" | "min" | "max" | "group_concat"
    )
}

/// Whether a *specific call* is an aggregate. `min`/`max` are scalar with 2+
/// arguments and aggregate with exactly one (or `*`), matching SQLite.
pub fn is_aggregate_call(name: &str, nargs: usize, star: bool) -> bool {
    match name.to_ascii_lowercase().as_str() {
        "count" | "sum" | "total" | "avg" | "group_concat" | "string_agg" => true,
        "json_group_array" => nargs == 1,
        "json_group_object" => nargs == 2,
        "min" | "max" => star || nargs == 1,
        _ => false,
    }
}

/// Evaluate a scalar function call.
pub fn eval_scalar(name: &str, args: &[Expr], star: bool, ctx: &EvalCtx) -> Result<Value> {
    let lname = name.to_ascii_lowercase();
    if is_aggregate_call(&lname, args.len(), star) {
        return Err(Error::Error(alloc::format!(
            "aggregate function {name} used outside an aggregate context"
        )));
    }
    if star {
        return Err(Error::Error(alloc::format!(
            "{name}(*) is not a scalar call"
        )));
    }

    // Connection-state functions: read counters off the subquery handler.
    match lname.as_str() {
        "last_insert_rowid" | "changes" | "total_changes" => {
            arity(&lname, args, 0)?;
            let n = ctx.subqueries.map_or(0, |s| match lname.as_str() {
                "last_insert_rowid" => s.last_insert_rowid(),
                "changes" => s.changes(),
                _ => s.total_changes(),
            });
            return Ok(Value::Integer(n));
        }
        _ => {}
    }

    // Functions whose NULL-handling is special are done before arg evaluation.
    match lname.as_str() {
        "coalesce" => {
            for a in args {
                let v = eval::eval(a, ctx)?;
                if !matches!(v, Value::Null) {
                    return Ok(v);
                }
            }
            return Ok(Value::Null);
        }
        "ifnull" => {
            arity(&lname, args, 2)?;
            let a = eval::eval(&args[0], ctx)?;
            return if matches!(a, Value::Null) {
                eval::eval(&args[1], ctx)
            } else {
                Ok(a)
            };
        }
        _ => {}
    }

    let v: Vec<Value> = args
        .iter()
        .map(|a| eval::eval(a, ctx))
        .collect::<Result<_>>()?;

    Ok(match lname.as_str() {
        "abs" => {
            arity(&lname, args, 1)?;
            match &v[0] {
                Value::Null => Value::Null,
                // `abs(-9223372036854775808)` has no i64 result — SQLite errors.
                Value::Integer(i) => match i.checked_abs() {
                    Some(a) => Value::Integer(a),
                    None => return Err(Error::Error("integer overflow".into())),
                },
                Value::Real(r) => Value::Real(crate::util::float::abs(*r)),
                // A text/blob argument is coerced to a real (SQLite gives
                // `abs('5')` = 5.0, not 5).
                other => Value::Real(crate::util::float::abs(eval::to_f64(other))),
            }
        }
        "length" => {
            arity(&lname, args, 1)?;
            match &v[0] {
                Value::Null => Value::Null,
                Value::Blob(b) => Value::Integer(b.len() as i64),
                other => Value::Integer(eval::to_text(other).chars().count() as i64),
            }
        }
        "octet_length" => {
            arity(&lname, args, 1)?;
            // Number of bytes in the value's encoding: blobs as-is, everything
            // else as the UTF-8 length of its text representation.
            match &v[0] {
                Value::Null => Value::Null,
                Value::Blob(b) => Value::Integer(b.len() as i64),
                other => Value::Integer(eval::to_text(other).len() as i64),
            }
        }
        "glob" => {
            // glob(pattern, text) is the function form of `text GLOB pattern`.
            arity(&lname, args, 2)?;
            if v.iter().take(2).any(|x| matches!(x, Value::Null)) {
                Value::Null
            } else {
                let m = eval::glob_match(&eval::to_text(&v[0]), &eval::to_text(&v[1]));
                Value::Integer(m as i64)
            }
        }
        "lower" => {
            arity(&lname, args, 1)?;
            str_map(&v[0], |s| s.to_lowercase())
        }
        "upper" => {
            arity(&lname, args, 1)?;
            str_map(&v[0], |s| s.to_uppercase())
        }
        "trim" => trim_fn(&v, true, true),
        "ltrim" => trim_fn(&v, true, false),
        "rtrim" => trim_fn(&v, false, true),
        "typeof" => Value::Text(String::from(type_name(&v[0]))),
        "nullif" => {
            arity(&lname, args, 2)?;
            if eval::compare(&v[0], &v[1]) == core::cmp::Ordering::Equal {
                Value::Null
            } else {
                v[0].clone()
            }
        }
        "n/a" => unreachable!(),
        "substr" | "substring" => substr(&v)?,
        "instr" => instr(&v)?,
        "replace" => replace(&v)?,
        "round" => round(&v)?,
        "min" => scalar_min_max(&v, true),
        "max" => scalar_min_max(&v, false),
        "hex" => Value::Text(hex_encode(&v[0])),
        "char" => char_fn(&v),
        "unicode" => match &v[0] {
            Value::Null => Value::Null,
            other => eval::to_text(other)
                .chars()
                .next()
                .map(|c| Value::Integer(c as i64))
                .unwrap_or(Value::Null),
        },
        // `if` is SQLite's alias for `iif`. Both take 2 or 3 arguments: the
        // 2-argument form yields NULL when the condition is not true.
        "iif" | "if" => {
            if args.len() != 2 && args.len() != 3 {
                return Err(Error::Error(alloc::format!(
                    "wrong number of arguments to function {lname}() (want 2 or 3, got {})",
                    args.len()
                )));
            }
            if eval::truth(&v[0]) == Some(true) {
                v[1].clone()
            } else {
                v.get(2).cloned().unwrap_or(Value::Null)
            }
        }
        // The SQLite release graphitesql tracks and writes into new file headers
        // (`SQLITE_VERSION_NUMBER` 3_053_002 = 3.53.2).
        "sqlite_version" => {
            arity(&lname, args, 0)?;
            Value::Text(crate::TARGET_SQLITE_VERSION.into())
        }
        "zeroblob" => {
            arity(&lname, args, 1)?;
            match &v[0] {
                Value::Null => Value::Null,
                other => {
                    let n = eval::to_i64(other).max(0) as usize;
                    Value::Blob(alloc::vec![0u8; n])
                }
            }
        }
        "quote" => {
            arity(&lname, args, 1)?;
            Value::Text(quote_value(&v[0]))
        }
        "sign" => {
            arity(&lname, args, 1)?;
            // Numeric (or losslessly-numeric text) only; otherwise NULL.
            let num = match &v[0] {
                Value::Integer(i) => Some(*i as f64),
                Value::Real(r) => Some(*r),
                Value::Text(s) => eval::parse_decimal_f64(s.trim()),
                _ => None,
            };
            match num {
                Some(r) if r > 0.0 => Value::Integer(1),
                Some(r) if r < 0.0 => Value::Integer(-1),
                Some(_) => Value::Integer(0),
                None => Value::Null,
            }
        }
        "concat" => {
            // SQLite 3.44+: concatenate all args, treating NULL as empty.
            let mut s = String::new();
            for x in &v {
                if !matches!(x, Value::Null) {
                    s.push_str(&eval::to_text(x));
                }
            }
            Value::Text(s)
        }
        "concat_ws" => {
            if v.is_empty() {
                return Err(Error::Error("concat_ws() needs a separator".into()));
            }
            if matches!(v[0], Value::Null) {
                Value::Null
            } else {
                let sep = eval::to_text(&v[0]);
                let parts: alloc::vec::Vec<String> = v[1..]
                    .iter()
                    .filter(|x| !matches!(x, Value::Null))
                    .map(eval::to_text)
                    .collect();
                Value::Text(parts.join(&sep))
            }
        }
        "like" => {
            // like(pattern, text[, escape]) — the function form of `text LIKE
            // pattern`. NULL operand → NULL.
            if v.len() < 2 || v.len() > 3 {
                return Err(Error::Error("like() takes 2 or 3 arguments".into()));
            }
            if v.iter().take(2).any(|x| matches!(x, Value::Null)) {
                Value::Null
            } else {
                let escape = v.get(2).map(eval::to_text).and_then(|s| s.chars().next());
                let m =
                    eval::like_match_escape(&eval::to_text(&v[0]), &eval::to_text(&v[1]), escape);
                Value::Integer(m as i64)
            }
        }
        // Optimizer hints that are no-ops at the value level (return the operand).
        "likely" | "unlikely" => {
            arity(&lname, args, 1)?;
            v[0].clone()
        }
        "likelihood" => {
            arity(&lname, args, 2)?;
            v[0].clone()
        }
        "unhex" => {
            if v.is_empty() || v.len() > 2 {
                return Err(Error::Error("unhex() takes 1 or 2 arguments".into()));
            }
            // `unhex(X, Y)` first removes any characters of Y from X.
            let cleaned = match v.get(1) {
                Some(Value::Null) => return Ok(Value::Null),
                Some(ignore) => {
                    let set: alloc::vec::Vec<char> = eval::to_text(ignore).chars().collect();
                    Some(
                        eval::to_text(&v[0])
                            .chars()
                            .filter(|c| !set.contains(c))
                            .collect::<String>(),
                    )
                }
                None => None,
            };
            match &v[0] {
                Value::Null => Value::Null,
                other => {
                    let text = cleaned.unwrap_or_else(|| eval::to_text(other));
                    match unhex(&text) {
                        Some(b) => Value::Blob(b),
                        None => Value::Null,
                    }
                }
            }
        }
        // Math functions (SQLite's `-DSQLITE_ENABLE_MATH_FUNCTIONS` set; the CLI
        // ships with these enabled). Each coerces its argument(s) to a real and
        // returns NULL when an argument is NULL or the result is not finite,
        // matching SQLite.
        "pi" => {
            arity(&lname, args, 0)?;
            Value::Real(crate::util::float::PI)
        }
        "ceil" | "ceiling" => math1(&lname, &v, crate::util::float::ceil)?,
        "floor" => math1(&lname, &v, crate::util::float::floor)?,
        "trunc" => math1(&lname, &v, crate::util::float::trunc)?,
        "sqrt" => math1(&lname, &v, crate::util::float::sqrt)?,
        "exp" => math1(&lname, &v, crate::util::float::exp)?,
        "ln" => math1(&lname, &v, crate::util::float::ln)?,
        "log2" => math1(&lname, &v, crate::util::float::log2)?,
        "sin" => math1(&lname, &v, crate::util::float::sin)?,
        "cos" => math1(&lname, &v, crate::util::float::cos)?,
        "tan" => math1(&lname, &v, crate::util::float::tan)?,
        "asin" => math1(&lname, &v, crate::util::float::asin)?,
        "acos" => math1(&lname, &v, crate::util::float::acos)?,
        "atan" => math1(&lname, &v, crate::util::float::atan)?,
        "sinh" => math1(&lname, &v, crate::util::float::sinh)?,
        "cosh" => math1(&lname, &v, crate::util::float::cosh)?,
        "tanh" => math1(&lname, &v, crate::util::float::tanh)?,
        "asinh" => math1(&lname, &v, crate::util::float::asinh)?,
        "acosh" => math1(&lname, &v, crate::util::float::acosh)?,
        "atanh" => math1(&lname, &v, crate::util::float::atanh)?,
        "degrees" => math1(&lname, &v, crate::util::float::degrees)?,
        "radians" => math1(&lname, &v, crate::util::float::radians)?,
        // `log(X)` is base-10; `log(B, X)` is base B. `log10` is base-10.
        "log10" => math1(&lname, &v, crate::util::float::log10)?,
        "log" => {
            if v.len() == 1 {
                math_finite(real_arg(&v[0]).map(crate::util::float::log10))
            } else {
                arity(&lname, args, 2)?;
                match (real_arg(&v[0]), real_arg(&v[1])) {
                    (Some(b), Some(x)) => {
                        math_finite(Some(crate::util::float::ln(x) / crate::util::float::ln(b)))
                    }
                    _ => Value::Null,
                }
            }
        }
        "pow" | "power" => {
            arity(&lname, args, 2)?;
            match (real_arg(&v[0]), real_arg(&v[1])) {
                (Some(b), Some(e)) => math_finite(Some(crate::util::float::pow(b, e))),
                _ => Value::Null,
            }
        }
        "atan2" => {
            arity(&lname, args, 2)?;
            match (real_arg(&v[0]), real_arg(&v[1])) {
                (Some(y), Some(x)) => math_finite(Some(crate::util::float::atan2(y, x))),
                _ => Value::Null,
            }
        }
        "mod" => {
            arity(&lname, args, 2)?;
            match (real_arg(&v[0]), real_arg(&v[1])) {
                (Some(x), Some(y)) => math_finite(Some(crate::util::float::fmod(x, y))),
                _ => Value::Null,
            }
        }
        // JSON functions (see `super::json`).
        "json" => {
            arity(&lname, args, 1)?;
            match &v[0] {
                Value::Null => Value::Null,
                other => {
                    let text = eval::to_text(other);
                    match super::json::parse(&text) {
                        Some(j) => Value::Text(j.serialize()),
                        None => return Err(Error::Error("malformed JSON".into())),
                    }
                }
            }
        }
        "json_valid" => {
            arity(&lname, args, 1)?;
            match &v[0] {
                Value::Null => Value::Null,
                other => {
                    let ok = super::json::parse(&eval::to_text(other)).is_some();
                    Value::Integer(ok as i64)
                }
            }
        }
        // `json_error_position(X)` — the 1-based byte position of the first JSON
        // syntax error in X, or 0 when X is well-formed JSON. NULL yields NULL,
        // matching sqlite3.
        "json_error_position" => {
            arity(&lname, args, 1)?;
            match &v[0] {
                Value::Null => Value::Null,
                other => {
                    let pos = match super::json::parse_with_error_position(&eval::to_text(other)) {
                        Ok(_) => 0,
                        Err(off) => off as i64 + 1,
                    };
                    Value::Integer(pos)
                }
            }
        }
        // `json_pretty(X [, indent])` — reformat with indentation (default 4
        // spaces). Empty arrays/objects and scalars stay compact, like SQLite.
        "json_pretty" => {
            if v.is_empty() || v.len() > 2 {
                return Err(Error::Error("json_pretty() takes 1 or 2 arguments".into()));
            }
            match &v[0] {
                Value::Null => Value::Null,
                other => {
                    let indent = match v.get(1) {
                        Some(Value::Null) | None => alloc::string::String::from("    "),
                        Some(iv) => eval::to_text(iv),
                    };
                    match super::json::parse(&eval::to_text(other)) {
                        Some(j) => Value::Text(j.pretty(&indent)),
                        None => return Err(Error::Error("malformed JSON".into())),
                    }
                }
            }
        }
        "json_quote" => {
            arity(&lname, args, 1)?;
            Value::Text(super::json::value_to_json(&v[0]).serialize())
        }
        "json_type" => {
            if v.is_empty() || v.len() > 2 {
                return Err(Error::Error("json_type() takes 1 or 2 arguments".into()));
            }
            match json_root(&v[0])? {
                None => Value::Null,
                Some(root) => {
                    let target = if v.len() == 2 {
                        super::json::navigate(&root, &eval::to_text(&v[1]))
                    } else {
                        Some(&root)
                    };
                    match target {
                        Some(j) => Value::Text(String::from(j.type_name())),
                        None => Value::Null,
                    }
                }
            }
        }
        "json_array_length" => {
            if v.is_empty() || v.len() > 2 {
                return Err(Error::Error(
                    "json_array_length() takes 1 or 2 arguments".into(),
                ));
            }
            match json_root(&v[0])? {
                None => Value::Null,
                Some(root) => {
                    let target = if v.len() == 2 {
                        super::json::navigate(&root, &eval::to_text(&v[1]))
                    } else {
                        Some(&root)
                    };
                    match target {
                        Some(super::json::Json::Array(items)) => Value::Integer(items.len() as i64),
                        Some(_) => Value::Integer(0),
                        None => Value::Null,
                    }
                }
            }
        }
        "json_extract" => {
            if v.len() < 2 {
                return Err(Error::Error(
                    "json_extract() requires at least 2 arguments".into(),
                ));
            }
            match json_root(&v[0])? {
                None => Value::Null,
                Some(root) => json_extract(&root, &v[1..]),
            }
        }
        "json_array" => {
            let mut items = Vec::with_capacity(v.len());
            for (i, val) in v.iter().enumerate() {
                items.push(arg_to_json(val, args.get(i)));
            }
            Value::Text(super::json::Json::Array(items).serialize())
        }
        "json_object" => {
            if !v.len().is_multiple_of(2) {
                return Err(Error::Error(
                    "json_object() requires an even number of arguments".into(),
                ));
            }
            let mut members = Vec::with_capacity(v.len() / 2);
            for pair in v.chunks(2).enumerate() {
                let (i, kv) = pair;
                let key = eval::to_text(&kv[0]);
                let val = arg_to_json(&kv[1], args.get(2 * i + 1));
                members.push((key, val));
            }
            Value::Text(super::json::Json::Object(members).serialize())
        }
        "json_set" | "json_insert" | "json_replace" => {
            if v.len() < 3 || v.len().is_multiple_of(2) {
                return Err(Error::Error(alloc::format!(
                    "{lname}() requires a document and (path, value) pairs"
                )));
            }
            let mode = match lname.as_str() {
                "json_set" => super::json::SetMode::Set,
                "json_insert" => super::json::SetMode::Insert,
                _ => super::json::SetMode::Replace,
            };
            match json_root(&v[0])? {
                None => Value::Null,
                Some(mut root) => {
                    let mut i = 1;
                    while i + 1 < v.len() {
                        let path = eval::to_text(&v[i]);
                        let val = arg_to_json(&v[i + 1], args.get(i + 1));
                        super::json::set_path(&mut root, &path, val, mode);
                        i += 2;
                    }
                    Value::Text(root.serialize())
                }
            }
        }
        "json_remove" => {
            if v.is_empty() {
                return Err(Error::Error("json_remove() requires a document".into()));
            }
            match json_root(&v[0])? {
                None => Value::Null,
                Some(mut root) => {
                    for p in &v[1..] {
                        super::json::remove_path(&mut root, &eval::to_text(p));
                    }
                    Value::Text(root.serialize())
                }
            }
        }
        "json_patch" => {
            arity(&lname, args, 2)?;
            match (json_root(&v[0])?, json_root(&v[1])?) {
                (Some(mut root), Some(patch)) => {
                    super::json::merge_patch(&mut root, &patch);
                    Value::Text(root.serialize())
                }
                _ => Value::Null,
            }
        }
        // Date/time functions (see `super::datetime`).
        "date" => super::datetime::date(&v),
        "time" => super::datetime::time(&v),
        "datetime" => super::datetime::datetime(&v),
        "julianday" => super::datetime::julianday(&v),
        "unixepoch" => super::datetime::unixepoch(&v),
        "strftime" => super::datetime::strftime(&v),
        "timediff" => {
            arity(&lname, args, 2)?;
            super::datetime::timediff(&v[0], &v[1])
        }
        "printf" | "format" => super::datetime::printf(&v),
        _ => return Err(Error::Unsupported("unknown scalar function")),
    })
}

/// Render a value as a SQL literal, like SQLite's `quote()`.
fn quote_value(v: &Value) -> String {
    match v {
        Value::Null => String::from("NULL"),
        Value::Integer(i) => alloc::format!("{i}"),
        // `quote()` renders an infinity as `±9.0e+999` (unlike plain text output,
        // which prints `Inf`).
        Value::Real(r) if !r.is_finite() => {
            String::from(if *r < 0.0 { "-9.0e+999" } else { "9.0e+999" })
        }
        Value::Real(r) => eval::format_real(*r),
        Value::Text(s) => alloc::format!("'{}'", s.replace('\'', "''")),
        Value::Blob(b) => {
            // SQLite renders blob literals as `X'ABCD'` — uppercase `X` and
            // uppercase hex digits.
            let mut s = String::from("X'");
            for byte in b {
                s.push_str(&alloc::format!("{byte:02X}"));
            }
            s.push('\'');
            s
        }
    }
}

/// Decode a hex string to bytes (even length, all hex digits), else `None`.
fn unhex(s: &str) -> Option<alloc::vec::Vec<u8>> {
    let bytes = s.as_bytes();
    if !bytes.len().is_multiple_of(2) {
        return None;
    }
    let hexval = |c: u8| -> Option<u8> {
        match c {
            b'0'..=b'9' => Some(c - b'0'),
            b'a'..=b'f' => Some(c - b'a' + 10),
            b'A'..=b'F' => Some(c - b'A' + 10),
            _ => None,
        }
    };
    let mut out = alloc::vec::Vec::with_capacity(bytes.len() / 2);
    let mut i = 0;
    while i < bytes.len() {
        out.push((hexval(bytes[i])? << 4) | hexval(bytes[i + 1])?);
        i += 2;
    }
    Some(out)
}

fn arity(name: &str, args: &[Expr], n: usize) -> Result<()> {
    if args.len() == n {
        Ok(())
    } else {
        Err(Error::Error(alloc::format!(
            "wrong number of arguments to function {name}() (want {n}, got {})",
            args.len()
        )))
    }
}

fn str_map(v: &Value, f: impl Fn(&str) -> String) -> Value {
    match v {
        Value::Null => Value::Null,
        other => Value::Text(f(&eval::to_text(other))),
    }
}

/// A numeric argument to a math function: `None` for SQL `NULL`, else the value
/// coerced to `f64` (SQLite applies REAL affinity to math-function arguments).
fn real_arg(v: &Value) -> Option<f64> {
    match v {
        Value::Null => None,
        other => Some(eval::to_f64(other)),
    }
}

/// Wrap a computed math result: `NULL` for a missing argument or a non-finite
/// result (domain error), else a `REAL`. Matches SQLite, where e.g. `ln(0)` and
/// `sqrt(-1)` yield `NULL`.
fn math_finite(r: Option<f64>) -> Value {
    match r {
        Some(x) if x.is_finite() => Value::Real(x),
        _ => Value::Null,
    }
}

/// A one-argument math function: arity-check, coerce, apply, finiteness-guard.
fn math1(name: &str, v: &[Value], f: impl Fn(f64) -> f64) -> Result<Value> {
    if v.len() != 1 {
        return Err(Error::Error(alloc::format!(
            "wrong number of arguments to function {name}()"
        )));
    }
    Ok(math_finite(real_arg(&v[0]).map(f)))
}

/// Parse the first argument of a JSON function as a document: `NULL` → `None`;
/// malformed JSON is an error (matching SQLite).
fn json_root(v: &Value) -> Result<Option<super::json::Json>> {
    match v {
        Value::Null => Ok(None),
        other => match super::json::parse(&eval::to_text(other)) {
            Some(j) => Ok(Some(j)),
            None => Err(Error::Error("malformed JSON".into())),
        },
    }
}

/// `json_extract`: one path returns the SQL value at that path (objects/arrays as
/// minified JSON text); multiple paths return a JSON array of the extracted
/// elements (missing paths become JSON `null`).
fn json_extract(root: &super::json::Json, paths: &[Value]) -> Value {
    if paths.len() == 1 {
        return match super::json::navigate(root, &eval::to_text(&paths[0])) {
            Some(j) => j.to_sql(),
            None => Value::Null,
        };
    }
    let items = paths
        .iter()
        .map(|p| match super::json::navigate(root, &eval::to_text(p)) {
            Some(j) => j.clone(),
            None => super::json::Json::Null,
        })
        .collect();
    Value::Text(super::json::Json::Array(items).serialize())
}

/// Convert a constructor argument to JSON. If the source expression is itself a
/// JSON-producing call (`json`, `json_array`, `json_object`), its text value is
/// embedded as parsed JSON — mirroring SQLite's JSON subtype propagation — rather
/// than quoted as a string.
pub(crate) fn arg_to_json(val: &Value, expr: Option<&Expr>) -> super::json::Json {
    if let (Value::Text(s), Some(e)) = (val, expr) {
        if produces_json(e) {
            if let Some(j) = super::json::parse(s) {
                return j;
            }
        }
    }
    super::json::value_to_json(val)
}

/// Whether an expression yields a value carrying SQLite's JSON subtype.
fn produces_json(e: &Expr) -> bool {
    match e {
        Expr::Function { name, .. } => matches!(
            name.to_ascii_lowercase().as_str(),
            "json"
                | "json_array"
                | "json_object"
                | "json_insert"
                | "json_replace"
                | "json_set"
                | "json_patch"
                | "json_remove"
        ),
        Expr::Paren(inner) => produces_json(inner),
        _ => false,
    }
}

fn type_name(v: &Value) -> &'static str {
    match v {
        Value::Null => "null",
        Value::Integer(_) => "integer",
        Value::Real(_) => "real",
        Value::Text(_) => "text",
        Value::Blob(_) => "blob",
    }
}

fn trim_fn(v: &[Value], left: bool, right: bool) -> Value {
    if v.is_empty() || matches!(v[0], Value::Null) {
        return Value::Null;
    }
    let s = eval::to_text(&v[0]);
    let trim_chars: Vec<char> = if v.len() >= 2 {
        eval::to_text(&v[1]).chars().collect()
    } else {
        alloc::vec![' ']
    };
    let is_trim = |c: char| trim_chars.contains(&c);
    let chars: Vec<char> = s.chars().collect();
    let mut start = 0;
    let mut end = chars.len();
    if left {
        while start < end && is_trim(chars[start]) {
            start += 1;
        }
    }
    if right {
        while end > start && is_trim(chars[end - 1]) {
            end -= 1;
        }
    }
    Value::Text(chars[start..end].iter().collect())
}

fn substr(v: &[Value]) -> Result<Value> {
    if v.len() < 2 || v.len() > 3 {
        return Err(Error::Error("substr() takes 2 or 3 arguments".into()));
    }
    if matches!(v[0], Value::Null) {
        return Ok(Value::Null);
    }
    // `substr` of a blob slices bytes and returns a blob; otherwise it slices
    // characters of the text form and returns text.
    let blob = matches!(v[0], Value::Blob(_));
    let units: alloc::vec::Vec<char> = if blob {
        match &v[0] {
            Value::Blob(b) => b.iter().map(|&x| x as char).collect(),
            _ => unreachable!(),
        }
    } else {
        eval::to_text(&v[0]).chars().collect()
    };
    let len = units.len() as i64;
    // 1-based start; a negative start counts from the end. Unlike a naive clamp,
    // SQLite keeps the requested window and only the positions in 1..=len are
    // returned, so `substr('hello',0,3)` yields "he" (positions 0,1,2 → 1,2).
    let mut start = eval::to_i64(&v[1]);
    if start < 0 {
        start += len + 1;
    }
    let (wstart, wend) = if v.len() == 3 {
        let z = eval::to_i64(&v[2]);
        if z < 0 {
            (start + z, start)
        } else {
            (start, start + z)
        }
    } else {
        (start, len + 1)
    };
    let b = wstart.max(1);
    let e = wend.min(len + 1);
    let slice = if b >= e {
        &[][..]
    } else {
        &units[(b - 1) as usize..(e - 1) as usize]
    };
    if blob {
        Ok(Value::Blob(slice.iter().map(|&c| c as u8).collect()))
    } else {
        Ok(Value::Text(slice.iter().collect()))
    }
}

fn instr(v: &[Value]) -> Result<Value> {
    if v.len() != 2 {
        return Err(Error::Error("instr() takes 2 arguments".into()));
    }
    if matches!(v[0], Value::Null) || matches!(v[1], Value::Null) {
        return Ok(Value::Null);
    }
    let hay = eval::to_text(&v[0]);
    let needle = eval::to_text(&v[1]);
    // SQLite returns a 1-based character index, 0 if not found.
    match hay.find(&needle) {
        None => Ok(Value::Integer(0)),
        Some(byte_idx) => {
            let char_idx = hay[..byte_idx].chars().count();
            Ok(Value::Integer(char_idx as i64 + 1))
        }
    }
}

fn replace(v: &[Value]) -> Result<Value> {
    if v.len() != 3 {
        return Err(Error::Error("replace() takes 3 arguments".into()));
    }
    if v.iter().any(|x| matches!(x, Value::Null)) {
        return Ok(Value::Null);
    }
    let s = eval::to_text(&v[0]);
    let from = eval::to_text(&v[1]);
    let to = eval::to_text(&v[2]);
    if from.is_empty() {
        return Ok(Value::Text(s));
    }
    Ok(Value::Text(s.replace(&from, &to)))
}

fn round(v: &[Value]) -> Result<Value> {
    if v.is_empty() || v.len() > 2 {
        return Err(Error::Error("round() takes 1 or 2 arguments".into()));
    }
    if matches!(v[0], Value::Null) {
        return Ok(Value::Null);
    }
    let x = eval::to_f64(&v[0]);
    let digits = if v.len() == 2 {
        eval::to_i64(&v[1]).clamp(0, 30) as u32
    } else {
        0
    };
    Ok(Value::Real(round_half_away(x, digits)))
}

/// Round `x` to `n` decimal places, half away from zero, matching SQLite. Instead
/// of `round(x * 10^n) / 10^n` — which loses precision (e.g. `2.675 * 100` rounds
/// *up* to exactly `267.5` in f64, giving 2.68 where SQLite gives 2.67) — this
/// formats `x` to high fixed precision (exposing the true decimal digits) and
/// rounds the digit string, so it sees that `2.675` is really `2.67499…`.
pub(crate) fn round_half_away(x: f64, n: u32) -> f64 {
    if !x.is_finite() || x == 0.0 {
        return x;
    }
    // Values at or beyond 2^52 have no fractional part in f64; return unchanged
    // (this also bounds the formatted string length).
    if crate::util::float::abs(x) >= 4_503_599_627_370_496.0 {
        return x;
    }
    let neg = x < 0.0;
    let ax = crate::util::float::abs(x);
    let prec = n as usize + 25;
    let s = alloc::format!("{ax:.prec$}");
    let dot = s.find('.').unwrap_or(s.len());
    let frac = if dot < s.len() { &s[dot + 1..] } else { "" };
    // Round up when the first dropped digit (position `n`) is >= 5.
    let round_up = frac.as_bytes().get(n as usize).is_some_and(|&d| d >= b'5');
    // Kept digits: the integer part followed by the first `n` fractional digits.
    let mut digits: alloc::vec::Vec<u8> = alloc::vec::Vec::new();
    digits.extend_from_slice(&s.as_bytes()[..dot]);
    if n > 0 {
        let take = (n as usize).min(frac.len());
        digits.extend_from_slice(&frac.as_bytes()[..take]);
        // Pad with zeros if the formatting produced fewer than n fraction digits.
        digits.resize(dot + n as usize, b'0');
    }
    if round_up {
        let mut i = digits.len();
        loop {
            if i == 0 {
                digits.insert(0, b'1');
                break;
            }
            i -= 1;
            if digits[i] == b'9' {
                digits[i] = b'0';
            } else {
                digits[i] += 1;
                break;
            }
        }
    }
    // Reassemble with the decimal point `n` digits from the right and parse back.
    let nn = n as usize;
    let s2 = if nn == 0 {
        alloc::string::String::from_utf8(digits).unwrap_or_default()
    } else {
        let point = digits.len() - nn;
        let mut out = alloc::string::String::new();
        out.push_str(core::str::from_utf8(&digits[..point]).unwrap_or("0"));
        out.push('.');
        out.push_str(core::str::from_utf8(&digits[point..]).unwrap_or("0"));
        out
    };
    let mag: f64 = s2.parse().unwrap_or(ax);
    if neg {
        -mag
    } else {
        mag
    }
}

fn scalar_min_max(v: &[Value], want_min: bool) -> Value {
    // Scalar min()/max() with 2+ args; NULL if any arg is NULL.
    if v.iter().any(|x| matches!(x, Value::Null)) {
        return Value::Null;
    }
    let mut best = v[0].clone();
    for x in &v[1..] {
        let ord = eval::compare(x, &best);
        let take = if want_min {
            ord == core::cmp::Ordering::Less
        } else {
            ord == core::cmp::Ordering::Greater
        };
        if take {
            best = x.clone();
        }
    }
    best
}

fn hex_encode(v: &Value) -> String {
    let bytes = match v {
        Value::Blob(b) => b.clone(),
        other => eval::to_text(other).into_bytes(),
    };
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push(nibble(b >> 4));
        s.push(nibble(b & 0xf));
    }
    s
}

fn nibble(n: u8) -> char {
    match n {
        0..=9 => (b'0' + n) as char,
        _ => (b'A' + n - 10) as char,
    }
}

fn char_fn(v: &[Value]) -> Value {
    let mut s = String::new();
    for x in v {
        if let Some(c) = char::from_u32(eval::to_i64(x) as u32) {
            s.push(c);
        }
    }
    Value::Text(s)
}