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
// 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.

//! Conversion and Collation Functions
//!
//! This module provides type conversion and string collation functions:
//!
//! - [`CastFunction`] - CAST(value AS type) - Convert value to another type
//! - [`CollateFunction`] - COLLATE(string, collation) - Apply collation to string

use crate::common::SmartString;
use crate::core::{DataType, Error, Result, Value};
use crate::functions::{
    FunctionDataType, FunctionInfo, FunctionSignature, FunctionType, ScalarFunction,
};
use crate::validate_arg_count;

/// CAST function for type conversion
///
/// Converts a value from one type to another.
///
/// # Examples
/// - `CAST(123 AS TEXT)` → '123'
/// - `CAST('456' AS INTEGER)` → 456
/// - `CAST(1 AS BOOLEAN)` → true
#[derive(Default)]
pub struct CastFunction;

impl ScalarFunction for CastFunction {
    fn name(&self) -> &str {
        "CAST"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "CAST",
            FunctionType::Scalar,
            "Converts a value from one data type to another",
            FunctionSignature::new(
                FunctionDataType::Any,
                vec![FunctionDataType::Any, FunctionDataType::String],
                2,
                2,
            ),
        )
    }

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

        let value = &args[0];
        let target_type = match &args[1] {
            Value::Text(s) => s.to_uppercase(),
            _ => {
                return Err(Error::invalid_argument(
                    "Second argument to CAST must be a string type name",
                ))
            }
        };

        // Handle NULL values - SQL standard: CAST(NULL AS type) returns NULL
        if value.is_null() {
            return Ok(match target_type.as_str() {
                "INT" | "INTEGER" => Value::Null(DataType::Integer),
                "FLOAT" | "REAL" | "DOUBLE" => Value::Null(DataType::Float),
                "STRING" | "TEXT" | "VARCHAR" | "CHAR" => Value::Null(DataType::Text),
                "BOOLEAN" | "BOOL" => Value::Null(DataType::Boolean),
                "TIMESTAMP" | "DATETIME" | "DATE" | "TIME" => Value::Null(DataType::Timestamp),
                "JSON" => Value::Null(DataType::Json),
                _ => Value::null_unknown(),
            });
        }

        // Convert based on target type
        match target_type.as_str() {
            "INT" | "INTEGER" => cast_to_integer(value),
            "FLOAT" | "REAL" | "DOUBLE" => cast_to_float(value),
            "STRING" | "TEXT" | "VARCHAR" | "CHAR" => cast_to_string(value),
            "BOOLEAN" | "BOOL" => cast_to_boolean(value),
            "TIMESTAMP" | "DATETIME" | "DATE" | "TIME" => cast_to_timestamp(value),
            "JSON" => cast_to_json(value),
            _ => Err(Error::invalid_argument(format!(
                "Unsupported cast target type: {}",
                target_type
            ))),
        }
    }

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

/// Cast a value to INTEGER
fn cast_to_integer(value: &Value) -> Result<Value> {
    match value {
        Value::Integer(i) => Ok(Value::Integer(*i)),
        Value::Float(f) => {
            if !f.is_finite() {
                return Err(Error::invalid_argument(format!(
                    "Cannot cast {} to INTEGER",
                    f
                )));
            }
            if *f > i64::MAX as f64 || *f < i64::MIN as f64 {
                return Err(Error::invalid_argument(format!(
                    "Float value {} out of INTEGER range",
                    f
                )));
            }
            Ok(Value::Integer(*f as i64))
        }
        Value::Boolean(b) => Ok(Value::Integer(if *b { 1 } else { 0 })),
        Value::Text(s) => {
            if s.is_empty() {
                return Ok(Value::Integer(0));
            }
            // Try to parse as integer first
            if let Ok(i) = s.parse::<i64>() {
                return Ok(Value::Integer(i));
            }
            // If that fails, try as float and truncate
            if let Ok(f) = s.parse::<f64>() {
                if !f.is_finite() || f > i64::MAX as f64 || f < i64::MIN as f64 {
                    return Err(Error::invalid_argument(format!(
                        "Cannot convert '{}' to INTEGER",
                        s
                    )));
                }
                return Ok(Value::Integer(f as i64));
            }
            Err(Error::invalid_argument(format!(
                "Cannot convert '{}' to INTEGER",
                s
            )))
        }
        Value::Timestamp(t) => Ok(Value::Integer(t.timestamp())),
        Value::Extension(_) => Ok(Value::Integer(0)),
        Value::Null(dt) => Ok(Value::Null(*dt)),
    }
}

/// Cast a value to FLOAT
fn cast_to_float(value: &Value) -> Result<Value> {
    match value {
        Value::Integer(i) => Ok(Value::Float(*i as f64)),
        Value::Float(f) => Ok(Value::Float(*f)),
        Value::Boolean(b) => Ok(Value::Float(if *b { 1.0 } else { 0.0 })),
        Value::Text(s) => {
            if s.is_empty() {
                return Ok(Value::Float(0.0));
            }
            match s.parse::<f64>() {
                Ok(f) => Ok(Value::Float(f)),
                Err(_) => Err(Error::invalid_argument(format!(
                    "Cannot convert '{}' to FLOAT",
                    s
                ))),
            }
        }
        Value::Timestamp(t) => Ok(Value::Float(t.timestamp() as f64)),
        Value::Extension(_) => Err(Error::invalid_argument("Cannot convert JSON to FLOAT")),
        Value::Null(dt) => Ok(Value::Null(*dt)),
    }
}

/// Cast a value to STRING/TEXT
fn cast_to_string(value: &Value) -> Result<Value> {
    match value {
        Value::Text(s) => Ok(Value::Text(s.clone())),
        Value::Integer(i) => Ok(Value::Text(SmartString::from_string(i.to_string()))),
        Value::Float(f) => {
            // Format with up to 6 decimal places
            Ok(Value::Text(SmartString::from_string(format!("{:.6}", f))))
        }
        Value::Boolean(b) => Ok(Value::Text(SmartString::from_string(b.to_string()))),
        Value::Timestamp(t) => Ok(Value::Text(SmartString::from_string(t.to_rfc3339()))),
        Value::Extension(data) if data.first() == Some(&(DataType::Json as u8)) => {
            let s = std::str::from_utf8(&data[1..]).unwrap_or("");
            Ok(Value::Text(SmartString::from(s)))
        }
        Value::Extension(_) => Ok(Value::Text(SmartString::from(""))),
        Value::Null(dt) => Ok(Value::Null(*dt)),
    }
}

/// Cast a value to BOOLEAN
fn cast_to_boolean(value: &Value) -> Result<Value> {
    match value {
        Value::Boolean(b) => Ok(Value::Boolean(*b)),
        Value::Integer(i) => Ok(Value::Boolean(*i != 0)),
        Value::Float(f) => Ok(Value::Boolean(*f != 0.0)),
        Value::Text(s) => {
            let lower = s.to_lowercase();
            let is_true = lower == "true"
                || lower == "yes"
                || lower == "1"
                || (!lower.is_empty() && lower != "0" && lower != "false" && lower != "no");
            Ok(Value::Boolean(is_true))
        }
        Value::Timestamp(_) => Err(Error::invalid_argument(
            "Cannot convert TIMESTAMP to BOOLEAN",
        )),
        Value::Extension(_) => Err(Error::invalid_argument("Cannot convert JSON to BOOLEAN")),
        Value::Null(dt) => Ok(Value::Null(*dt)),
    }
}

/// Cast a value to TIMESTAMP
fn cast_to_timestamp(value: &Value) -> Result<Value> {
    match value {
        Value::Timestamp(t) => Ok(Value::Timestamp(*t)),
        Value::Text(s) => {
            // Try to parse the timestamp using the core parse_timestamp function
            match crate::core::parse_timestamp(s) {
                Ok(t) => Ok(Value::Timestamp(t)),
                Err(_) => Err(Error::invalid_argument(format!(
                    "Cannot parse '{}' as TIMESTAMP",
                    s
                ))),
            }
        }
        Value::Integer(i) => {
            // Interpret as Unix timestamp
            use chrono::{TimeZone, Utc};
            match Utc.timestamp_opt(*i, 0) {
                chrono::LocalResult::Single(t) => Ok(Value::Timestamp(t)),
                _ => Err(Error::invalid_argument(format!(
                    "Invalid Unix timestamp: {}",
                    i
                ))),
            }
        }
        _ => Err(Error::invalid_argument(format!(
            "Cannot convert {:?} to TIMESTAMP",
            value.data_type()
        ))),
    }
}

/// Cast a value to JSON
fn cast_to_json(value: &Value) -> Result<Value> {
    match value {
        Value::Extension(data) if data.first() == Some(&(DataType::Json as u8)) => {
            Ok(value.clone())
        }
        Value::Text(s) => Ok(Value::json(s.as_ref())),
        Value::Integer(i) => Ok(Value::json(i.to_string())),
        Value::Float(f) => Ok(Value::json(f.to_string())),
        Value::Boolean(b) => Ok(Value::json(b.to_string())),
        Value::Null(_) => Ok(Value::json("null")),
        Value::Timestamp(t) => Ok(Value::json(format!("\"{}\"", t.to_rfc3339()))),
        Value::Extension(_) => Ok(Value::json("null")),
    }
}

/// COLLATE function for string collation
///
/// Applies a collation to a string value for sorting and comparison.
///
/// # Supported Collations
/// - BINARY - Binary comparison (no change)
/// - NOCASE, CASE_INSENSITIVE - Case-insensitive comparison (converts to lowercase)
/// - NOACCENT, ACCENT_INSENSITIVE - Remove accents for comparison
/// - NUMERIC - For numeric-aware string comparison
#[derive(Default)]
pub struct CollateFunction;

impl ScalarFunction for CollateFunction {
    fn name(&self) -> &str {
        "COLLATE"
    }

    fn info(&self) -> FunctionInfo {
        FunctionInfo::new(
            "COLLATE",
            FunctionType::Scalar,
            "Applies a collation to a string value for sorting and comparison",
            FunctionSignature::new(
                FunctionDataType::String,
                vec![FunctionDataType::Any, FunctionDataType::String],
                2,
                2,
            ),
        )
    }

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

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

        // Convert first argument to string
        let s = match &args[0] {
            Value::Text(s) => s.to_string(),
            Value::Integer(i) => i.to_string(),
            Value::Float(f) => f.to_string(),
            Value::Boolean(b) => b.to_string(),
            Value::Timestamp(t) => t.to_rfc3339(),
            Value::Extension(data) if data.first() == Some(&(DataType::Json as u8)) => {
                std::str::from_utf8(&data[1..]).unwrap_or("").to_string()
            }
            Value::Extension(_) => String::new(),
            Value::Null(_) => return Ok(Value::null_unknown()),
        };

        // Get collation name
        let collation = match &args[1] {
            Value::Text(c) => c.to_uppercase(),
            _ => {
                return Err(Error::invalid_argument(
                    "COLLATE requires a string as the second argument",
                ))
            }
        };

        // Apply collation
        let result = apply_collation(&s, &collation)?;
        Ok(Value::Text(SmartString::from_string(result)))
    }

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

/// Apply a collation transformation to a string
fn apply_collation(s: &str, collation: &str) -> Result<String> {
    match collation {
        "BINARY" => Ok(s.to_string()),
        "NOCASE" | "CASE_INSENSITIVE" => Ok(s.to_lowercase()),
        "NOACCENT" | "ACCENT_INSENSITIVE" => Ok(remove_accents(s)),
        "NUMERIC" => Ok(s.to_string()), // No transformation, comparison handles it
        _ => Err(Error::invalid_argument(format!(
            "Unsupported collation: {}",
            collation
        ))),
    }
}

/// Remove accents from characters in a string
fn remove_accents(s: &str) -> String {
    s.chars()
        .filter_map(|c| {
            Some(match c {
                // Latin letters with accents -> base letter
                'À'..='Å' => 'A',
                'à'..='å' => 'a',
                'È'..='Ë' => 'E',
                'è'..='ë' => 'e',
                'Ì'..='Ï' => 'I',
                'ì'..='ï' => 'i',
                'Ò'..='Ö' => 'O',
                'ò'..='ö' => 'o',
                'Ù'..='Ü' => 'U',
                'ù'..='ü' => 'u',
                'Ç' => 'C',
                'ç' => 'c',
                'Ñ' => 'N',
                'ñ' => 'n',
                'Ÿ' => 'Y',
                'ÿ' => 'y',
                // Keep diacritical marks that are combining characters
                _ if c.is_ascii() || !is_combining_mark(c) => c,
                // Remove combining marks
                _ => return None,
            })
        })
        .collect()
}

/// Check if a character is a combining diacritical mark
fn is_combining_mark(c: char) -> bool {
    // Unicode combining diacritical marks range: U+0300 to U+036F
    matches!(c, '\u{0300}'..='\u{036F}')
}

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

    // CAST tests
    #[test]
    fn test_cast_to_integer() {
        let cast = CastFunction;

        // Integer passthrough
        assert_eq!(
            cast.evaluate(&[Value::Integer(42), Value::text("INTEGER")])
                .unwrap(),
            Value::Integer(42)
        );

        // Float to integer
        assert_eq!(
            cast.evaluate(&[Value::Float(3.7), Value::text("INT")])
                .unwrap(),
            Value::Integer(3)
        );

        // String to integer
        assert_eq!(
            cast.evaluate(&[Value::text("123"), Value::text("INTEGER")])
                .unwrap(),
            Value::Integer(123)
        );

        // Boolean to integer
        assert_eq!(
            cast.evaluate(&[Value::Boolean(true), Value::text("INT")])
                .unwrap(),
            Value::Integer(1)
        );
        assert_eq!(
            cast.evaluate(&[Value::Boolean(false), Value::text("INT")])
                .unwrap(),
            Value::Integer(0)
        );

        // Empty string to integer
        assert_eq!(
            cast.evaluate(&[Value::text(""), Value::text("INTEGER")])
                .unwrap(),
            Value::Integer(0)
        );
    }

    #[test]
    fn test_cast_text_to_integer_edge_cases() {
        let cast = CastFunction;

        // "inf" → should error, not silently saturate to i64::MAX
        assert!(cast
            .evaluate(&[Value::text("inf"), Value::text("INTEGER")])
            .is_err());
        assert!(cast
            .evaluate(&[Value::text("-inf"), Value::text("INTEGER")])
            .is_err());
        assert!(cast
            .evaluate(&[Value::text("NaN"), Value::text("INTEGER")])
            .is_err());
        // Out of i64 range
        assert!(cast
            .evaluate(&[Value::text("1e30"), Value::text("INTEGER")])
            .is_err());
        // Valid float string truncates to integer
        assert_eq!(
            cast.evaluate(&[Value::text("3.14"), Value::text("INTEGER")])
                .unwrap(),
            Value::Integer(3)
        );
    }

    #[test]
    fn test_cast_to_float() {
        let cast = CastFunction;

        // Integer to float
        assert_eq!(
            cast.evaluate(&[Value::Integer(42), Value::text("FLOAT")])
                .unwrap(),
            Value::Float(42.0)
        );

        // Float passthrough
        assert_eq!(
            cast.evaluate(&[Value::Float(3.5), Value::text("REAL")])
                .unwrap(),
            Value::Float(3.5)
        );

        // String to float
        assert_eq!(
            cast.evaluate(&[Value::text("2.5"), Value::text("DOUBLE")])
                .unwrap(),
            Value::Float(2.5)
        );
    }

    #[test]
    fn test_cast_to_string() {
        let cast = CastFunction;

        // Integer to string
        assert_eq!(
            cast.evaluate(&[Value::Integer(42), Value::text("TEXT")])
                .unwrap(),
            Value::text("42")
        );

        // Boolean to string
        assert_eq!(
            cast.evaluate(&[Value::Boolean(true), Value::text("STRING")])
                .unwrap(),
            Value::text("true")
        );

        // String passthrough
        assert_eq!(
            cast.evaluate(&[Value::text("hello"), Value::text("VARCHAR")])
                .unwrap(),
            Value::text("hello")
        );
    }

    #[test]
    fn test_cast_to_boolean() {
        let cast = CastFunction;

        // Integer to boolean
        assert_eq!(
            cast.evaluate(&[Value::Integer(1), Value::text("BOOL")])
                .unwrap(),
            Value::Boolean(true)
        );
        assert_eq!(
            cast.evaluate(&[Value::Integer(0), Value::text("BOOLEAN")])
                .unwrap(),
            Value::Boolean(false)
        );

        // String to boolean
        assert_eq!(
            cast.evaluate(&[Value::text("true"), Value::text("BOOL")])
                .unwrap(),
            Value::Boolean(true)
        );
        assert_eq!(
            cast.evaluate(&[Value::text("false"), Value::text("BOOL")])
                .unwrap(),
            Value::Boolean(false)
        );
        assert_eq!(
            cast.evaluate(&[Value::text("yes"), Value::text("BOOL")])
                .unwrap(),
            Value::Boolean(true)
        );
    }

    #[test]
    fn test_cast_null_handling() {
        let cast = CastFunction;

        // SQL standard: CAST(NULL AS type) returns NULL with the target type
        let result = cast
            .evaluate(&[Value::null_unknown(), Value::text("INTEGER")])
            .unwrap();
        assert!(result.is_null(), "CAST(NULL AS INTEGER) should return NULL");

        let result = cast
            .evaluate(&[Value::null_unknown(), Value::text("TEXT")])
            .unwrap();
        assert!(result.is_null(), "CAST(NULL AS TEXT) should return NULL");

        let result = cast
            .evaluate(&[Value::null_unknown(), Value::text("FLOAT")])
            .unwrap();
        assert!(result.is_null(), "CAST(NULL AS FLOAT) should return NULL");

        let result = cast
            .evaluate(&[Value::null_unknown(), Value::text("BOOLEAN")])
            .unwrap();
        assert!(result.is_null(), "CAST(NULL AS BOOLEAN) should return NULL");
    }

    // COLLATE tests
    #[test]
    fn test_collate_binary() {
        let collate = CollateFunction;

        assert_eq!(
            collate
                .evaluate(&[Value::text("Hello"), Value::text("BINARY")])
                .unwrap(),
            Value::text("Hello")
        );
    }

    #[test]
    fn test_collate_nocase() {
        let collate = CollateFunction;

        assert_eq!(
            collate
                .evaluate(&[Value::text("HELLO"), Value::text("NOCASE")])
                .unwrap(),
            Value::text("hello")
        );

        assert_eq!(
            collate
                .evaluate(&[Value::text("Hello World"), Value::text("CASE_INSENSITIVE")])
                .unwrap(),
            Value::text("hello world")
        );
    }

    #[test]
    fn test_collate_noaccent() {
        let collate = CollateFunction;

        assert_eq!(
            collate
                .evaluate(&[Value::text("Café"), Value::text("NOACCENT")])
                .unwrap(),
            Value::text("Cafe")
        );

        assert_eq!(
            collate
                .evaluate(&[Value::text("Naïve"), Value::text("ACCENT_INSENSITIVE")])
                .unwrap(),
            Value::text("Naive")
        );
    }

    #[test]
    fn test_collate_null_handling() {
        let collate = CollateFunction;

        let result = collate
            .evaluate(&[Value::null_unknown(), Value::text("NOCASE")])
            .unwrap();
        assert!(result.is_null());
    }

    #[test]
    fn test_collate_unsupported() {
        let collate = CollateFunction;

        let result = collate.evaluate(&[Value::text("test"), Value::text("INVALID")]);
        assert!(result.is_err());
    }

    #[test]
    fn test_remove_accents() {
        assert_eq!(remove_accents("Café"), "Cafe");
        assert_eq!(remove_accents("Naïve"), "Naive");
        assert_eq!(remove_accents("Résumé"), "Resume");
        assert_eq!(remove_accents("Élève"), "Eleve");
        assert_eq!(remove_accents("Über"), "Uber");
        assert_eq!(remove_accents("Español"), "Espanol");
    }
}