vibesql-executor 0.2.0

Query execution engine for vibesql SQL database
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
//! Logical operator implementations
//!
//! Handles: AND, OR
//! Implements: SQL three-valued logic (TRUE, FALSE, NULL)
//! Supports: SQLite truthiness (numeric values in boolean context)

use vibesql_types::SqlValue;

use crate::errors::ExecutorError;

/// Parse the leading numeric portion of a string, SQLite-style.
///
/// SQLite rules for string-to-numeric coercion:
/// - Leading whitespace is skipped
/// - Optional sign (+/-) is recognized
/// - Digits and decimal point are parsed
/// - Parsing stops at the first non-numeric character
/// - Returns 0.0 if no numeric prefix is found
///
/// Examples:
/// - "123" → 123.0
/// - "123abc" → 123.0
/// - "-45.6xyz" → -45.6
/// - "abc" → 0.0
/// - "" → 0.0
/// Check if a string is truthy in SQLite boolean context.
/// Parses leading numeric and returns true if non-zero.
pub fn is_truthy_string(s: &str) -> bool {
    parse_leading_numeric(s) != 0.0
}

/// Check if a SqlValue is truthy using SQLite truthiness rules.
///
/// SQLite rules:
/// - `Boolean(true)` → true
/// - `Boolean(false)` → false
/// - `Null` → false (NULL is not truthy for WHERE clause purposes)
/// - `0` and `0.0` → false
/// - Any other numeric value → true
/// - Strings → parse leading numeric, non-zero is true, 0 or non-numeric is false
///
/// Shared by row-selection paths (DELETE, UPDATE-on-view) so comparison
/// results that surface as `Integer(1)`/`Integer(0)` (SQLite-style) are
/// treated identically to `Boolean(true)`/`Boolean(false)`.
pub fn is_truthy(value: &SqlValue) -> bool {
    use SqlValue::*;
    match value {
        Boolean(b) => *b,
        Null => false, // NULL is not truthy for row selection
        // Integer types: 0 is false, non-zero is true
        Integer(n) => *n != 0,
        Smallint(n) => *n != 0,
        Bigint(n) => *n != 0,
        Unsigned(n) => *n != 0,
        // Floating point types: 0.0 is false, non-zero is true
        Float(f) => *f != 0.0,
        Real(f) => *f != 0.0,
        Double(f) => *f != 0.0,
        Numeric(f) => *f != 0.0,
        // String types: SQLite parses leading numeric portion
        Varchar(s) | Character(s) => is_truthy_string(s),
        // Other types are not truthy (conservative default)
        _ => false,
    }
}

fn parse_leading_numeric(s: &str) -> f64 {
    let s = s.trim_start();
    if s.is_empty() {
        return 0.0;
    }

    let mut chars = s.chars().peekable();
    let mut result = String::new();

    // Handle optional sign
    if let Some(&c) = chars.peek() {
        if c == '+' || c == '-' {
            result.push(c);
            chars.next();
        }
    }

    let mut has_digits = false;
    let mut has_dot = false;

    // Parse digits and decimal point
    while let Some(&c) = chars.peek() {
        if c.is_ascii_digit() {
            result.push(c);
            has_digits = true;
            chars.next();
        } else if c == '.' && !has_dot {
            result.push(c);
            has_dot = true;
            chars.next();
        } else {
            break;
        }
    }

    if !has_digits {
        return 0.0;
    }

    result.parse::<f64>().unwrap_or(0.0)
}

/// Convert a SqlValue to a boolean using SQLite truthiness rules.
///
/// SQLite rules:
/// - `0` and `0.0` → false
/// - Any other numeric value → true
/// - Boolean values → as-is
/// - NULL → None (three-valued logic)
/// - Strings → try to parse as number, non-numeric strings are treated as 0 (false)
/// - Other types → error
fn to_boolean(value: &SqlValue) -> Result<Option<bool>, ExecutorError> {
    use SqlValue::*;
    match value {
        Boolean(b) => Ok(Some(*b)),
        Null => Ok(None),
        // Integer types: 0 is false, non-zero is true
        Integer(n) => Ok(Some(*n != 0)),
        Smallint(n) => Ok(Some(*n != 0)),
        Bigint(n) => Ok(Some(*n != 0)),
        Unsigned(n) => Ok(Some(*n != 0)),
        // Floating point types: 0.0 is false, non-zero is true
        Float(f) => Ok(Some(*f != 0.0)),
        Real(f) => Ok(Some(*f != 0.0)),
        Double(f) => Ok(Some(*f != 0.0)),
        Numeric(f) => Ok(Some(*f != 0.0)),
        // String types: SQLite coerces strings to numeric for boolean context
        // SQLite parses the leading numeric portion of the string
        // e.g., '1x' → 1 (truthy), '0x' → 0 (falsy), 'abc' → 0 (falsy)
        Varchar(s) | Character(s) => {
            let trimmed = s.trim();
            // SQLite parses the leading numeric portion of a string
            // Use the parse_leading_numeric helper to match SQLite behavior
            let numeric_value = parse_leading_numeric(trimmed);
            Ok(Some(numeric_value != 0.0))
        }
        // Other types are not supported in boolean context
        _ => Err(ExecutorError::TypeMismatch {
            left: value.clone(),
            op: "boolean context".to_string(),
            right: SqlValue::Null,
        }),
    }
}

pub(crate) struct LogicalOps;

impl LogicalOps {
    /// AND operator - SQL three-valued logic with SQLite truthiness
    ///
    /// Truth table:
    /// - TRUE AND TRUE = TRUE
    /// - TRUE AND FALSE = FALSE
    /// - TRUE AND NULL = NULL
    /// - FALSE AND anything = FALSE
    /// - NULL AND TRUE = NULL
    /// - NULL AND FALSE = FALSE
    /// - NULL AND NULL = NULL
    ///
    /// SQLite truthiness:
    /// - Numeric 0/0.0 is treated as FALSE
    /// - Non-zero numeric values are treated as TRUE
    #[inline]
    pub fn and(left: &SqlValue, right: &SqlValue) -> Result<SqlValue, ExecutorError> {
        use SqlValue::*;

        // Convert both operands to boolean (None = NULL)
        let left_bool = to_boolean(left)?;
        let right_bool = to_boolean(right)?;

        match (left_bool, right_bool) {
            // Both have values
            (Some(a), Some(b)) => Ok(Boolean(a && b)),

            // FALSE AND anything = FALSE (even NULL)
            (Some(false), None) | (None, Some(false)) => Ok(Boolean(false)),

            // TRUE AND NULL = NULL
            (Some(true), None) | (None, Some(true)) => Ok(Null),

            // NULL AND NULL = NULL
            (None, None) => Ok(Null),
        }
    }

    /// OR operator - SQL three-valued logic with SQLite truthiness
    ///
    /// Truth table:
    /// - TRUE OR anything = TRUE
    /// - FALSE OR TRUE = TRUE
    /// - FALSE OR FALSE = FALSE
    /// - FALSE OR NULL = NULL
    /// - NULL OR TRUE = TRUE
    /// - NULL OR FALSE = NULL
    /// - NULL OR NULL = NULL
    ///
    /// SQLite truthiness:
    /// - Numeric 0/0.0 is treated as FALSE
    /// - Non-zero numeric values are treated as TRUE
    #[inline]
    pub fn or(left: &SqlValue, right: &SqlValue) -> Result<SqlValue, ExecutorError> {
        use SqlValue::*;

        // Convert both operands to boolean (None = NULL)
        let left_bool = to_boolean(left)?;
        let right_bool = to_boolean(right)?;

        match (left_bool, right_bool) {
            // Both have values
            (Some(a), Some(b)) => Ok(Boolean(a || b)),

            // TRUE OR anything = TRUE (even NULL)
            (Some(true), None) | (None, Some(true)) => Ok(Boolean(true)),

            // FALSE OR NULL = NULL
            (Some(false), None) | (None, Some(false)) => Ok(Null),

            // NULL OR NULL = NULL
            (None, None) => Ok(Null),
        }
    }
}

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

    #[test]
    fn test_and_operator() {
        assert_eq!(
            LogicalOps::and(&SqlValue::Boolean(true), &SqlValue::Boolean(true)).unwrap(),
            SqlValue::Boolean(true)
        );
        assert_eq!(
            LogicalOps::and(&SqlValue::Boolean(true), &SqlValue::Boolean(false)).unwrap(),
            SqlValue::Boolean(false)
        );
        assert_eq!(
            LogicalOps::and(&SqlValue::Boolean(false), &SqlValue::Boolean(false)).unwrap(),
            SqlValue::Boolean(false)
        );
    }

    #[test]
    fn test_or_operator() {
        assert_eq!(
            LogicalOps::or(&SqlValue::Boolean(true), &SqlValue::Boolean(true)).unwrap(),
            SqlValue::Boolean(true)
        );
        assert_eq!(
            LogicalOps::or(&SqlValue::Boolean(true), &SqlValue::Boolean(false)).unwrap(),
            SqlValue::Boolean(true)
        );
        assert_eq!(
            LogicalOps::or(&SqlValue::Boolean(false), &SqlValue::Boolean(false)).unwrap(),
            SqlValue::Boolean(false)
        );
    }

    #[test]
    fn test_strings_in_boolean_context() {
        // SQLite coerces strings to numeric for boolean context
        // Non-numeric strings like "hello" parse to 0.0, which is falsy
        let result = LogicalOps::and(
            &SqlValue::Varchar(arcstr::ArcStr::from("hello")),
            &SqlValue::Boolean(true),
        );
        // "hello" → 0 (falsy), so false AND true = false
        assert_eq!(result.unwrap(), SqlValue::Boolean(false));

        let result = LogicalOps::or(
            &SqlValue::Boolean(true),
            &SqlValue::Varchar(arcstr::ArcStr::from("world")),
        );
        // true OR "world" (falsy) = true
        assert_eq!(result.unwrap(), SqlValue::Boolean(true));

        // Numeric string prefix should work
        let result = LogicalOps::and(
            &SqlValue::Varchar(arcstr::ArcStr::from("1abc")),
            &SqlValue::Boolean(true),
        );
        // "1abc" → 1 (truthy), so true AND true = true
        assert_eq!(result.unwrap(), SqlValue::Boolean(true));

        let result = LogicalOps::and(
            &SqlValue::Varchar(arcstr::ArcStr::from("0")),
            &SqlValue::Boolean(true),
        );
        // "0" → 0 (falsy), so false AND true = false
        assert_eq!(result.unwrap(), SqlValue::Boolean(false));
    }

    #[test]
    fn test_and_with_integers() {
        // SQLite truthiness: 0 = false, non-zero = true
        // 1 AND 1 = true
        assert_eq!(
            LogicalOps::and(&SqlValue::Integer(1), &SqlValue::Integer(1)).unwrap(),
            SqlValue::Boolean(true)
        );
        // 1 AND 0 = false
        assert_eq!(
            LogicalOps::and(&SqlValue::Integer(1), &SqlValue::Integer(0)).unwrap(),
            SqlValue::Boolean(false)
        );
        // 0 AND 1 = false
        assert_eq!(
            LogicalOps::and(&SqlValue::Integer(0), &SqlValue::Integer(1)).unwrap(),
            SqlValue::Boolean(false)
        );
        // 0 AND 0 = false
        assert_eq!(
            LogicalOps::and(&SqlValue::Integer(0), &SqlValue::Integer(0)).unwrap(),
            SqlValue::Boolean(false)
        );
        // Non-zero values: 42 AND -7 = true
        assert_eq!(
            LogicalOps::and(&SqlValue::Integer(42), &SqlValue::Integer(-7)).unwrap(),
            SqlValue::Boolean(true)
        );
    }

    #[test]
    fn test_or_with_integers() {
        // SQLite truthiness: 0 = false, non-zero = true
        // 1 OR 0 = true
        assert_eq!(
            LogicalOps::or(&SqlValue::Integer(1), &SqlValue::Integer(0)).unwrap(),
            SqlValue::Boolean(true)
        );
        // 0 OR 1 = true
        assert_eq!(
            LogicalOps::or(&SqlValue::Integer(0), &SqlValue::Integer(1)).unwrap(),
            SqlValue::Boolean(true)
        );
        // 0 OR 0 = false
        assert_eq!(
            LogicalOps::or(&SqlValue::Integer(0), &SqlValue::Integer(0)).unwrap(),
            SqlValue::Boolean(false)
        );
        // 1 OR 1 = true
        assert_eq!(
            LogicalOps::or(&SqlValue::Integer(1), &SqlValue::Integer(1)).unwrap(),
            SqlValue::Boolean(true)
        );
    }

    #[test]
    fn test_and_with_floats() {
        // 1.5 AND 0.0 = false
        assert_eq!(
            LogicalOps::and(&SqlValue::Float(1.5), &SqlValue::Float(0.0)).unwrap(),
            SqlValue::Boolean(false)
        );
        // 1.5 AND 2.5 = true
        assert_eq!(
            LogicalOps::and(&SqlValue::Float(1.5), &SqlValue::Float(2.5)).unwrap(),
            SqlValue::Boolean(true)
        );
        // 0.0 AND 0.0 = false
        assert_eq!(
            LogicalOps::and(&SqlValue::Float(0.0), &SqlValue::Float(0.0)).unwrap(),
            SqlValue::Boolean(false)
        );
    }

    #[test]
    fn test_or_with_floats() {
        // 1.5 OR 0.0 = true
        assert_eq!(
            LogicalOps::or(&SqlValue::Float(1.5), &SqlValue::Float(0.0)).unwrap(),
            SqlValue::Boolean(true)
        );
        // 0.0 OR 0.0 = false
        assert_eq!(
            LogicalOps::or(&SqlValue::Float(0.0), &SqlValue::Float(0.0)).unwrap(),
            SqlValue::Boolean(false)
        );
    }

    #[test]
    fn test_and_with_numeric() {
        // Numeric type (f64)
        assert_eq!(
            LogicalOps::and(&SqlValue::Numeric(4.3), &SqlValue::Numeric(2.4)).unwrap(),
            SqlValue::Boolean(true)
        );
        assert_eq!(
            LogicalOps::and(&SqlValue::Numeric(0.0), &SqlValue::Numeric(2.4)).unwrap(),
            SqlValue::Boolean(false)
        );
    }

    #[test]
    fn test_or_with_numeric() {
        // Numeric type (f64)
        assert_eq!(
            LogicalOps::or(&SqlValue::Numeric(4.3), &SqlValue::Numeric(0.0)).unwrap(),
            SqlValue::Boolean(true)
        );
        assert_eq!(
            LogicalOps::or(&SqlValue::Numeric(0.0), &SqlValue::Numeric(0.0)).unwrap(),
            SqlValue::Boolean(false)
        );
    }

    #[test]
    fn test_mixed_numeric_and_boolean() {
        // Integer AND Boolean
        assert_eq!(
            LogicalOps::and(&SqlValue::Integer(1), &SqlValue::Boolean(true)).unwrap(),
            SqlValue::Boolean(true)
        );
        assert_eq!(
            LogicalOps::and(&SqlValue::Integer(0), &SqlValue::Boolean(true)).unwrap(),
            SqlValue::Boolean(false)
        );
        // Float OR Boolean
        assert_eq!(
            LogicalOps::or(&SqlValue::Float(0.0), &SqlValue::Boolean(false)).unwrap(),
            SqlValue::Boolean(false)
        );
        assert_eq!(
            LogicalOps::or(&SqlValue::Float(1.5), &SqlValue::Boolean(false)).unwrap(),
            SqlValue::Boolean(true)
        );
    }

    #[test]
    fn test_numeric_with_null() {
        // Integer with NULL
        // 0 AND NULL = FALSE (0 is false, false AND anything = false)
        assert_eq!(
            LogicalOps::and(&SqlValue::Integer(0), &SqlValue::Null).unwrap(),
            SqlValue::Boolean(false)
        );
        // 1 AND NULL = NULL (1 is true, true AND null = null)
        assert_eq!(
            LogicalOps::and(&SqlValue::Integer(1), &SqlValue::Null).unwrap(),
            SqlValue::Null
        );
        // 1 OR NULL = TRUE (1 is true, true OR anything = true)
        assert_eq!(
            LogicalOps::or(&SqlValue::Integer(1), &SqlValue::Null).unwrap(),
            SqlValue::Boolean(true)
        );
        // 0 OR NULL = NULL (0 is false, false OR null = null)
        assert_eq!(LogicalOps::or(&SqlValue::Integer(0), &SqlValue::Null).unwrap(), SqlValue::Null);
    }

    #[test]
    fn test_and_with_null() {
        // FALSE AND NULL = FALSE
        assert_eq!(
            LogicalOps::and(&SqlValue::Boolean(false), &SqlValue::Null).unwrap(),
            SqlValue::Boolean(false)
        );
        assert_eq!(
            LogicalOps::and(&SqlValue::Null, &SqlValue::Boolean(false)).unwrap(),
            SqlValue::Boolean(false)
        );

        // TRUE AND NULL = NULL
        assert_eq!(
            LogicalOps::and(&SqlValue::Boolean(true), &SqlValue::Null).unwrap(),
            SqlValue::Null
        );
        assert_eq!(
            LogicalOps::and(&SqlValue::Null, &SqlValue::Boolean(true)).unwrap(),
            SqlValue::Null
        );

        // NULL AND NULL = NULL
        assert_eq!(LogicalOps::and(&SqlValue::Null, &SqlValue::Null).unwrap(), SqlValue::Null);
    }

    #[test]
    fn test_or_with_null() {
        // TRUE OR NULL = TRUE
        assert_eq!(
            LogicalOps::or(&SqlValue::Boolean(true), &SqlValue::Null).unwrap(),
            SqlValue::Boolean(true)
        );
        assert_eq!(
            LogicalOps::or(&SqlValue::Null, &SqlValue::Boolean(true)).unwrap(),
            SqlValue::Boolean(true)
        );

        // FALSE OR NULL = NULL
        assert_eq!(
            LogicalOps::or(&SqlValue::Boolean(false), &SqlValue::Null).unwrap(),
            SqlValue::Null
        );
        assert_eq!(
            LogicalOps::or(&SqlValue::Null, &SqlValue::Boolean(false)).unwrap(),
            SqlValue::Null
        );

        // NULL OR NULL = NULL
        assert_eq!(LogicalOps::or(&SqlValue::Null, &SqlValue::Null).unwrap(), SqlValue::Null);
    }
}