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

//! Function expression for evaluating scalar functions in WHERE clauses
//!
//! This module provides `FunctionExpr` which wraps a scalar function call
//! and evaluates it as a boolean expression. This enables queries like:
//!
//! ```sql
//! SELECT * FROM users WHERE UPPER(name) = 'ALICE'
//! SELECT * FROM products WHERE LENGTH(description) > 100
//! ```

use std::any::Any;
use std::fmt::{self, Debug};

use rustc_hash::FxHashMap;
use std::sync::Arc;

use crate::core::{Operator, Result, Row, Schema, Value};
use crate::functions::ScalarFunction;

use super::{find_column_index, resolve_alias, Expression};

/// Expression that evaluates a scalar function and compares the result
///
/// This expression wraps a scalar function call with its arguments,
/// evaluates the function for each row, and compares the result to
/// a target value using a comparison operator.
///
/// # Example
///
/// For `UPPER(name) = 'ALICE'`:
/// - function: UPPER
/// - arguments: [ColumnArg("name")]
/// - operator: Eq
/// - compare_value: Text("ALICE")
pub struct FunctionExpr {
    /// The scalar function to call
    function: Arc<dyn ScalarFunction>,
    /// Arguments to pass to the function
    arguments: Vec<FunctionArg>,
    /// Comparison operator
    operator: Operator,
    /// Value to compare the function result against
    compare_value: Value,
    /// Pre-computed column indices for arguments
    arg_indices: Vec<Option<usize>>,
    /// Whether this expression has been prepared
    prepared: bool,
}

// Thread-local buffer for function arguments (avoids allocation per row)
thread_local! {
    static ARG_BUFFER: std::cell::RefCell<Vec<Value>> = std::cell::RefCell::new(Vec::with_capacity(4));
}

/// Argument to a function in a FunctionExpr
#[derive(Clone)]
pub enum FunctionArg {
    /// A column reference
    Column(String),
    /// A literal value
    Literal(Value),
    /// A nested function call (for function composition)
    Function {
        function: Arc<dyn ScalarFunction>,
        arguments: Vec<FunctionArg>,
    },
}

impl Debug for FunctionArg {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FunctionArg::Column(col) => f.debug_tuple("Column").field(col).finish(),
            FunctionArg::Literal(val) => f.debug_tuple("Literal").field(val).finish(),
            FunctionArg::Function {
                function,
                arguments,
            } => f
                .debug_struct("Function")
                .field("name", &function.name())
                .field("arguments", arguments)
                .finish(),
        }
    }
}

impl FunctionExpr {
    /// Create a new function expression
    ///
    /// # Arguments
    /// * `function` - The scalar function to call
    /// * `arguments` - Arguments to pass to the function
    /// * `operator` - Comparison operator
    /// * `compare_value` - Value to compare the function result against
    pub fn new(
        function: Arc<dyn ScalarFunction>,
        arguments: Vec<FunctionArg>,
        operator: Operator,
        compare_value: Value,
    ) -> Self {
        let arg_count = arguments.len();
        Self {
            function,
            arguments,
            operator,
            compare_value,
            arg_indices: vec![None; arg_count],
            prepared: false,
        }
    }

    /// Create a function expression for equality comparison
    pub fn eq(
        function: Arc<dyn ScalarFunction>,
        arguments: Vec<FunctionArg>,
        compare_value: Value,
    ) -> Self {
        Self::new(function, arguments, Operator::Eq, compare_value)
    }

    /// Create a function expression that evaluates to boolean (no comparison)
    ///
    /// This is for functions that return boolean directly, like custom predicates
    pub fn boolean(function: Arc<dyn ScalarFunction>, arguments: Vec<FunctionArg>) -> Self {
        Self::new(function, arguments, Operator::Eq, Value::Boolean(true))
    }

    /// Get the function name
    pub fn function_name(&self) -> &str {
        self.function.name()
    }

    /// Get the arguments
    pub fn get_arguments(&self) -> &[FunctionArg] {
        &self.arguments
    }

    /// Get the operator
    pub fn get_operator(&self) -> Operator {
        self.operator
    }

    /// Get the compare value
    pub fn get_compare_value(&self) -> &Value {
        &self.compare_value
    }

    /// Evaluate a function argument to get its value
    #[allow(clippy::only_used_in_recursion)]
    fn evaluate_arg(
        &self,
        arg: &FunctionArg,
        arg_index: Option<usize>,
        row: &Row,
    ) -> Result<Value> {
        match arg {
            FunctionArg::Column(col_name) => {
                if let Some(idx) = arg_index {
                    Ok(row.get(idx).cloned().unwrap_or_else(Value::null_unknown))
                } else {
                    // Fallback: try to find column by name (shouldn't happen if prepared)
                    Err(crate::core::Error::ColumnNotFound(col_name.to_string()))
                }
            }
            FunctionArg::Literal(value) => Ok(value.clone()),
            FunctionArg::Function {
                function,
                arguments,
            } => {
                // Recursively evaluate nested function
                let args: Result<Vec<Value>> = arguments
                    .iter()
                    .map(|a| self.evaluate_arg(a, None, row))
                    .collect();
                function.evaluate(&args?)
            }
        }
    }

    /// Compare two values using the configured operator
    fn compare(&self, result: &Value, target: &Value) -> bool {
        match self.operator {
            Operator::Eq => result == target,
            Operator::Ne => result != target,
            Operator::Lt => result < target,
            Operator::Lte => result <= target,
            Operator::Gt => result > target,
            Operator::Gte => result >= target,
            // For other operators, fall back to equality check or false
            _ => false,
        }
    }
}

impl Debug for FunctionExpr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FunctionExpr")
            .field("function", &self.function.name())
            .field("arguments", &self.arguments)
            .field("operator", &self.operator)
            .field("compare_value", &self.compare_value)
            .field("prepared", &self.prepared)
            .finish()
    }
}

impl Expression for FunctionExpr {
    fn evaluate(&self, row: &Row) -> Result<bool> {
        // Fast path for single-argument column functions (most common case)
        // This avoids function call overhead and directly extracts from row
        if self.arguments.len() == 1 {
            if let FunctionArg::Column(_) = &self.arguments[0] {
                if let Some(idx) = self.arg_indices.first().copied().flatten() {
                    let value = row.get(idx).cloned().unwrap_or_else(Value::null_unknown);
                    let result = self.function.evaluate(std::slice::from_ref(&value))?;
                    return Ok(self.compare(&result, &self.compare_value));
                }
            }
        }

        // Use thread-local buffer for multi-arg functions
        ARG_BUFFER.with(|buf_cell| {
            let mut arg_values = buf_cell.borrow_mut();
            arg_values.clear();

            // Evaluate all arguments into the buffer
            for (i, arg) in self.arguments.iter().enumerate() {
                let value =
                    self.evaluate_arg(arg, self.arg_indices.get(i).copied().flatten(), row)?;
                arg_values.push(value);
            }

            // Call the function
            let result = self.function.evaluate(&arg_values)?;

            // Compare with target value
            Ok(self.compare(&result, &self.compare_value))
        })
    }

    fn evaluate_fast(&self, row: &Row) -> bool {
        self.evaluate(row).unwrap_or(false)
    }

    fn with_aliases(&self, aliases: &FxHashMap<String, String>) -> Box<dyn Expression> {
        let new_arguments: Vec<FunctionArg> = self
            .arguments
            .iter()
            .map(|arg| match arg {
                FunctionArg::Column(col) => {
                    FunctionArg::Column(resolve_alias(col, aliases).to_string())
                }
                FunctionArg::Literal(v) => FunctionArg::Literal(v.clone()),
                FunctionArg::Function {
                    function,
                    arguments,
                } => {
                    // Recursively resolve aliases in nested functions
                    FunctionArg::Function {
                        function: Arc::clone(function),
                        arguments: arguments
                            .iter()
                            .map(|a| match a {
                                FunctionArg::Column(c) => {
                                    FunctionArg::Column(resolve_alias(c, aliases).to_string())
                                }
                                other => other.clone(),
                            })
                            .collect(),
                    }
                }
            })
            .collect();

        Box::new(FunctionExpr {
            function: Arc::clone(&self.function),
            arguments: new_arguments,
            operator: self.operator,
            compare_value: self.compare_value.clone(),
            arg_indices: vec![None; self.arguments.len()],
            prepared: false,
        })
    }

    fn prepare_for_schema(&mut self, schema: &Schema) {
        self.arg_indices = self
            .arguments
            .iter()
            .map(|arg| match arg {
                FunctionArg::Column(col) => find_column_index(schema, col),
                _ => None,
            })
            .collect();
        self.prepared = true;
    }

    fn is_prepared(&self) -> bool {
        self.prepared
    }

    fn can_use_index(&self) -> bool {
        // Function expressions generally can't use indexes
        // unless we have function-based indexes (future optimization)
        false
    }

    fn clone_box(&self) -> Box<dyn Expression> {
        Box::new(FunctionExpr {
            function: Arc::clone(&self.function),
            arguments: self.arguments.clone(),
            operator: self.operator,
            compare_value: self.compare_value.clone(),
            arg_indices: self.arg_indices.clone(),
            prepared: self.prepared,
        })
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Expression that wraps a closure for dynamic evaluation
///
/// This is useful for testing or when you need a custom predicate
/// that doesn't fit the standard expression types.
pub struct EvalExpr {
    /// The evaluation function
    eval_fn: Box<dyn Fn(&Row) -> bool + Send + Sync>,
}

impl EvalExpr {
    /// Create a new eval expression from a closure
    pub fn new<F>(f: F) -> Self
    where
        F: Fn(&Row) -> bool + Send + Sync + 'static,
    {
        Self {
            eval_fn: Box::new(f),
        }
    }
}

impl Debug for EvalExpr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EvalExpr").finish()
    }
}

impl Expression for EvalExpr {
    fn evaluate(&self, row: &Row) -> Result<bool> {
        Ok((self.eval_fn)(row))
    }

    fn evaluate_fast(&self, row: &Row) -> bool {
        (self.eval_fn)(row)
    }

    fn with_aliases(&self, _aliases: &FxHashMap<String, String>) -> Box<dyn Expression> {
        // Can't modify the closure, return a clone
        panic!("EvalExpr does not support alias resolution")
    }

    fn prepare_for_schema(&mut self, _schema: &Schema) {
        // Nothing to prepare for closures
    }

    fn is_prepared(&self) -> bool {
        true // Always "prepared"
    }

    fn clone_box(&self) -> Box<dyn Expression> {
        panic!("EvalExpr cannot be cloned")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{DataType, SchemaBuilder};
    use crate::functions::{
        FunctionDataType, FunctionInfo, FunctionSignature, FunctionType, UpperFunction,
    };

    fn test_schema() -> Schema {
        SchemaBuilder::new("test")
            .add_primary_key("id", DataType::Integer)
            .add("name", DataType::Text)
            .add("age", DataType::Integer)
            .build()
    }

    // Helper function for testing - LENGTH function
    struct TestLengthFn;

    impl ScalarFunction for TestLengthFn {
        fn name(&self) -> &str {
            "LENGTH"
        }

        fn info(&self) -> FunctionInfo {
            FunctionInfo::new(
                "LENGTH",
                FunctionType::Scalar,
                "Returns the length of a string",
                FunctionSignature::new(
                    FunctionDataType::Integer,
                    vec![FunctionDataType::String],
                    1,
                    1,
                ),
            )
        }

        fn evaluate(&self, args: &[Value]) -> Result<Value> {
            match args.first() {
                Some(Value::Text(s)) => Ok(Value::Integer(s.len() as i64)),
                Some(Value::Null(_)) => Ok(Value::null_unknown()),
                _ => Ok(Value::Integer(0)),
            }
        }

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

    #[test]
    fn test_function_expr_upper() {
        let schema = test_schema();
        let upper_fn = Arc::new(UpperFunction);

        let mut expr = FunctionExpr::eq(
            upper_fn,
            vec![FunctionArg::Column("name".to_string())],
            Value::text("ALICE"),
        );
        expr.prepare_for_schema(&schema);

        // Row with name = "alice" should match UPPER(name) = 'ALICE'
        let row1 = Row::from_values(vec![
            Value::Integer(1),
            Value::text("alice"),
            Value::Integer(30),
        ]);
        assert!(expr.evaluate(&row1).unwrap());

        // Row with name = "Alice" should also match
        let row2 = Row::from_values(vec![
            Value::Integer(2),
            Value::text("Alice"),
            Value::Integer(25),
        ]);
        assert!(expr.evaluate(&row2).unwrap());

        // Row with name = "bob" should not match
        let row3 = Row::from_values(vec![
            Value::Integer(3),
            Value::text("bob"),
            Value::Integer(35),
        ]);
        assert!(!expr.evaluate(&row3).unwrap());
    }

    #[test]
    fn test_function_expr_with_literal() {
        let schema = test_schema();
        let upper_fn = Arc::new(UpperFunction);

        let mut expr = FunctionExpr::eq(
            upper_fn,
            vec![FunctionArg::Literal(Value::text("hello"))],
            Value::text("HELLO"),
        );
        expr.prepare_for_schema(&schema);

        // Should always match since it's comparing literals
        let row = Row::from_values(vec![
            Value::Integer(1),
            Value::text("anything"),
            Value::Integer(30),
        ]);
        assert!(expr.evaluate(&row).unwrap());
    }

    #[test]
    fn test_function_expr_operators() {
        let schema = test_schema();

        let length_fn = Arc::new(TestLengthFn);

        // Test LENGTH(name) > 3
        let mut expr = FunctionExpr::new(
            length_fn,
            vec![FunctionArg::Column("name".to_string())],
            Operator::Gt,
            Value::Integer(3),
        );
        expr.prepare_for_schema(&schema);

        // "alice" has length 5 > 3
        let row1 = Row::from_values(vec![
            Value::Integer(1),
            Value::text("alice"),
            Value::Integer(30),
        ]);
        assert!(expr.evaluate(&row1).unwrap());

        // "bob" has length 3, not > 3
        let row2 = Row::from_values(vec![
            Value::Integer(2),
            Value::text("bob"),
            Value::Integer(25),
        ]);
        assert!(!expr.evaluate(&row2).unwrap());
    }

    #[test]
    fn test_eval_expr() {
        let expr = EvalExpr::new(|row| {
            // Return true if first column is Integer > 5
            match row.get(0) {
                Some(Value::Integer(n)) => *n > 5,
                _ => false,
            }
        });

        let row1 = Row::from_values(vec![Value::Integer(10)]);
        assert!(expr.evaluate(&row1).unwrap());

        let row2 = Row::from_values(vec![Value::Integer(3)]);
        assert!(!expr.evaluate(&row2).unwrap());
    }

    #[test]
    fn test_function_expr_clone() {
        let upper_fn = Arc::new(UpperFunction);

        let expr = FunctionExpr::eq(
            upper_fn,
            vec![FunctionArg::Column("name".to_string())],
            Value::text("ALICE"),
        );

        let cloned = expr.clone_box();
        assert!(format!("{:?}", cloned).contains("FunctionExpr"));
    }
}