Skip to main content

sql_cli/data/
arithmetic_evaluator.rs

1use crate::config::global::get_date_notation;
2use crate::data::data_view::DataView;
3use crate::data::datatable::{DataTable, DataValue};
4use crate::data::value_comparisons::compare_with_op;
5use crate::sql::aggregate_functions::AggregateFunctionRegistry; // New registry
6use crate::sql::aggregates::AggregateRegistry; // Old registry (for migration)
7use crate::sql::functions::FunctionRegistry;
8use crate::sql::parser::ast::{ColumnRef, WindowSpec};
9use crate::sql::recursive_parser::SqlExpression;
10use crate::sql::window_context::WindowContext;
11use crate::sql::window_functions::{ExpressionEvaluator, WindowFunctionRegistry};
12use anyhow::{anyhow, Result};
13use std::collections::{HashMap, HashSet};
14use std::sync::Arc;
15use std::time::Instant;
16use tracing::{debug, info};
17
18/// Evaluates SQL expressions to compute `DataValues` (for SELECT clauses)
19/// This is different from `RecursiveWhereEvaluator` which returns boolean
20pub struct ArithmeticEvaluator<'a> {
21    table: &'a DataTable,
22    _date_notation: String,
23    function_registry: Arc<FunctionRegistry>,
24    aggregate_registry: Arc<AggregateRegistry>, // Old registry (being phased out)
25    new_aggregate_registry: Arc<AggregateFunctionRegistry>, // New registry
26    window_function_registry: Arc<WindowFunctionRegistry>,
27    visible_rows: Option<Vec<usize>>, // For aggregate functions on filtered views
28    window_contexts: HashMap<u64, Arc<WindowContext>>, // Cache window contexts by hash
29    table_aliases: HashMap<String, String>, // Map alias -> table name for qualified columns
30}
31
32impl<'a> ArithmeticEvaluator<'a> {
33    #[must_use]
34    pub fn new(table: &'a DataTable) -> Self {
35        Self {
36            table,
37            _date_notation: get_date_notation(),
38            function_registry: Arc::new(FunctionRegistry::new()),
39            aggregate_registry: Arc::new(AggregateRegistry::new()),
40            new_aggregate_registry: Arc::new(AggregateFunctionRegistry::new()),
41            window_function_registry: Arc::new(WindowFunctionRegistry::new()),
42            visible_rows: None,
43            window_contexts: HashMap::new(),
44            table_aliases: HashMap::new(),
45        }
46    }
47
48    #[must_use]
49    pub fn with_date_notation(table: &'a DataTable, date_notation: String) -> Self {
50        Self {
51            table,
52            _date_notation: date_notation,
53            function_registry: Arc::new(FunctionRegistry::new()),
54            aggregate_registry: Arc::new(AggregateRegistry::new()),
55            new_aggregate_registry: Arc::new(AggregateFunctionRegistry::new()),
56            window_function_registry: Arc::new(WindowFunctionRegistry::new()),
57            visible_rows: None,
58            window_contexts: HashMap::new(),
59            table_aliases: HashMap::new(),
60        }
61    }
62
63    /// Set visible rows for aggregate functions (for filtered views)
64    #[must_use]
65    pub fn with_visible_rows(mut self, rows: Vec<usize>) -> Self {
66        self.visible_rows = Some(rows);
67        self
68    }
69
70    /// Set table aliases for qualified column resolution
71    #[must_use]
72    pub fn with_table_aliases(mut self, aliases: HashMap<String, String>) -> Self {
73        self.table_aliases = aliases;
74        self
75    }
76
77    #[must_use]
78    pub fn with_date_notation_and_registry(
79        table: &'a DataTable,
80        date_notation: String,
81        function_registry: Arc<FunctionRegistry>,
82    ) -> Self {
83        Self {
84            table,
85            _date_notation: date_notation,
86            function_registry,
87            aggregate_registry: Arc::new(AggregateRegistry::new()),
88            new_aggregate_registry: Arc::new(AggregateFunctionRegistry::new()),
89            window_function_registry: Arc::new(WindowFunctionRegistry::new()),
90            visible_rows: None,
91            window_contexts: HashMap::new(),
92            table_aliases: HashMap::new(),
93        }
94    }
95
96    /// Find a column name similar to the given name using edit distance
97    fn find_similar_column(&self, name: &str) -> Option<String> {
98        let columns = self.table.column_names();
99        let mut best_match: Option<(String, usize)> = None;
100
101        for col in columns {
102            let distance = self.edit_distance(&col.to_lowercase(), &name.to_lowercase());
103            // Only suggest if distance is small (likely a typo)
104            // Allow up to 3 edits for longer names
105            let max_distance = if name.len() > 10 { 3 } else { 2 };
106            if distance <= max_distance {
107                match &best_match {
108                    None => best_match = Some((col, distance)),
109                    Some((_, best_dist)) if distance < *best_dist => {
110                        best_match = Some((col, distance));
111                    }
112                    _ => {}
113                }
114            }
115        }
116
117        best_match.map(|(name, _)| name)
118    }
119
120    /// Calculate Levenshtein edit distance between two strings
121    fn edit_distance(&self, s1: &str, s2: &str) -> usize {
122        // Use the shared implementation from string_methods
123        crate::sql::functions::string_methods::EditDistanceFunction::calculate_edit_distance(s1, s2)
124    }
125
126    /// Evaluate an SQL expression to produce a `DataValue`
127    pub fn evaluate(&mut self, expr: &SqlExpression, row_index: usize) -> Result<DataValue> {
128        debug!(
129            "ArithmeticEvaluator: evaluating {:?} for row {}",
130            expr, row_index
131        );
132
133        match expr {
134            SqlExpression::Column(column_ref) => self.evaluate_column_ref(column_ref, row_index),
135            SqlExpression::StringLiteral(s) => Ok(DataValue::String(s.clone())),
136            SqlExpression::BooleanLiteral(b) => Ok(DataValue::Boolean(*b)),
137            SqlExpression::NumberLiteral(n) => self.evaluate_number_literal(n),
138            SqlExpression::Null => Ok(DataValue::Null),
139            SqlExpression::BinaryOp { left, op, right } => {
140                self.evaluate_binary_op(left, op, right, row_index)
141            }
142            SqlExpression::FunctionCall {
143                name,
144                args,
145                distinct,
146            } => self.evaluate_function_with_distinct(name, args, *distinct, row_index),
147            SqlExpression::WindowFunction {
148                name,
149                args,
150                window_spec,
151            } => self.evaluate_window_function(name, args, window_spec, row_index),
152            SqlExpression::MethodCall {
153                object,
154                method,
155                args,
156            } => self.evaluate_method_call(object, method, args, row_index),
157            SqlExpression::ChainedMethodCall { base, method, args } => {
158                // Evaluate the base expression first, then apply the method
159                let base_value = self.evaluate(base, row_index)?;
160                self.evaluate_method_on_value(&base_value, method, args, row_index)
161            }
162            SqlExpression::Between { expr, lower, upper } => {
163                let val = self.evaluate(expr, row_index)?;
164                let lo = self.evaluate(lower, row_index)?;
165                let hi = self.evaluate(upper, row_index)?;
166                let ge = compare_with_op(&val, &lo, ">=", false);
167                let le = compare_with_op(&val, &hi, "<=", false);
168                Ok(DataValue::Boolean(ge && le))
169            }
170            // Logical negation as a value-producing expression. Reached, e.g., by
171            // a post-aggregation `HAVING NOT (COUNT(*) > 2)` predicate (P10).
172            // Three-valued logic: NOT NULL is NULL; otherwise negate the boolean.
173            SqlExpression::Not { expr } => {
174                let inner = self.evaluate(expr, row_index)?;
175                match inner {
176                    DataValue::Null => Ok(DataValue::Null),
177                    other => Ok(DataValue::Boolean(!self.to_bool(&other)?)),
178                }
179            }
180            // IN / NOT IN as a value-producing expression — needed when they
181            // appear inside CASE branches or other arithmetic contexts. The
182            // WHERE path has its own evaluator; this mirrors its equality
183            // semantics via compare_with_op. After subquery rewriting, an
184            // `x IN (SELECT ...)` arrives here as an InList of literals.
185            SqlExpression::InList { expr, values } => {
186                let val = self.evaluate(expr, row_index)?;
187                for v in values {
188                    let item = self.evaluate(v, row_index)?;
189                    if compare_with_op(&val, &item, "=", false) {
190                        return Ok(DataValue::Boolean(true));
191                    }
192                }
193                Ok(DataValue::Boolean(false))
194            }
195            SqlExpression::NotInList { expr, values } => {
196                let val = self.evaluate(expr, row_index)?;
197                for v in values {
198                    let item = self.evaluate(v, row_index)?;
199                    if compare_with_op(&val, &item, "=", false) {
200                        return Ok(DataValue::Boolean(false));
201                    }
202                }
203                Ok(DataValue::Boolean(true))
204            }
205            SqlExpression::CaseExpression {
206                when_branches,
207                else_branch,
208            } => self.evaluate_case_expression(when_branches, else_branch, row_index),
209            SqlExpression::SimpleCaseExpression {
210                expr,
211                when_branches,
212                else_branch,
213            } => self.evaluate_simple_case_expression(expr, when_branches, else_branch, row_index),
214            SqlExpression::DateTimeConstructor {
215                year,
216                month,
217                day,
218                hour,
219                minute,
220                second,
221            } => self.evaluate_datetime_constructor(*year, *month, *day, *hour, *minute, *second),
222            SqlExpression::DateTimeToday {
223                hour,
224                minute,
225                second,
226            } => self.evaluate_datetime_today(*hour, *minute, *second),
227            _ => Err(anyhow!(
228                "Unsupported expression type for arithmetic evaluation: {:?}",
229                expr
230            )),
231        }
232    }
233
234    /// Evaluate a column reference with proper table scoping
235    fn evaluate_column_ref(&self, column_ref: &ColumnRef, row_index: usize) -> Result<DataValue> {
236        if let Some(table_prefix) = &column_ref.table_prefix {
237            // Resolve alias if it exists in table_aliases map
238            let actual_table = self
239                .table_aliases
240                .get(table_prefix)
241                .map(|s| s.as_str())
242                .unwrap_or(table_prefix);
243
244            // Try qualified lookup with resolved table name
245            let qualified_name = format!("{}.{}", actual_table, column_ref.name);
246
247            if let Some(col_idx) = self.table.find_column_by_qualified_name(&qualified_name) {
248                debug!(
249                    "Resolved {}.{} -> '{}' at index {}",
250                    table_prefix, column_ref.name, qualified_name, col_idx
251                );
252                return self
253                    .table
254                    .get_value(row_index, col_idx)
255                    .ok_or_else(|| anyhow!("Row {} out of bounds", row_index))
256                    .map(|v| v.clone());
257            }
258
259            // Fallback: try unqualified lookup
260            if let Some(col_idx) = self.table.get_column_index(&column_ref.name) {
261                debug!(
262                    "Resolved {}.{} -> unqualified '{}' at index {}",
263                    table_prefix, column_ref.name, column_ref.name, col_idx
264                );
265                return self
266                    .table
267                    .get_value(row_index, col_idx)
268                    .ok_or_else(|| anyhow!("Row {} out of bounds", row_index))
269                    .map(|v| v.clone());
270            }
271
272            // If not found, return error
273            Err(anyhow!(
274                "Column '{}' not found. Table '{}' may not support qualified column names",
275                qualified_name,
276                actual_table
277            ))
278        } else {
279            // Simple column name lookup
280            self.evaluate_column(&column_ref.name, row_index)
281        }
282    }
283
284    /// Evaluate a column reference
285    fn evaluate_column(&self, column_name: &str, row_index: usize) -> Result<DataValue> {
286        // First try to resolve qualified column names (table.column or alias.column)
287        let resolved_column = if column_name.contains('.') {
288            // Split on last dot to handle cases like "schema.table.column"
289            if let Some(dot_pos) = column_name.rfind('.') {
290                let _table_or_alias = &column_name[..dot_pos];
291                let col_name = &column_name[dot_pos + 1..];
292
293                // For now, just use the column name part
294                // In the future, we could validate the table/alias part
295                debug!(
296                    "Resolving qualified column: {} -> {}",
297                    column_name, col_name
298                );
299                col_name.to_string()
300            } else {
301                column_name.to_string()
302            }
303        } else {
304            column_name.to_string()
305        };
306
307        let col_index = if let Some(idx) = self.table.get_column_index(&resolved_column) {
308            idx
309        } else if resolved_column != column_name {
310            // If not found, try the original name
311            if let Some(idx) = self.table.get_column_index(column_name) {
312                idx
313            } else {
314                let suggestion = self.find_similar_column(&resolved_column);
315                return Err(match suggestion {
316                    Some(similar) => anyhow!(
317                        "Column '{}' not found. Did you mean '{}'?",
318                        column_name,
319                        similar
320                    ),
321                    None => anyhow!("Column '{}' not found", column_name),
322                });
323            }
324        } else {
325            let suggestion = self.find_similar_column(&resolved_column);
326            return Err(match suggestion {
327                Some(similar) => anyhow!(
328                    "Column '{}' not found. Did you mean '{}'?",
329                    column_name,
330                    similar
331                ),
332                None => anyhow!("Column '{}' not found", column_name),
333            });
334        };
335
336        if row_index >= self.table.row_count() {
337            return Err(anyhow!("Row index {} out of bounds", row_index));
338        }
339
340        let row = self
341            .table
342            .get_row(row_index)
343            .ok_or_else(|| anyhow!("Row {} not found", row_index))?;
344
345        let value = row
346            .get(col_index)
347            .ok_or_else(|| anyhow!("Column index {} out of bounds for row", col_index))?;
348
349        Ok(value.clone())
350    }
351
352    /// Evaluate a number literal (handles both integers and floats)
353    fn evaluate_number_literal(&self, number_str: &str) -> Result<DataValue> {
354        // Try to parse as integer first
355        if let Ok(int_val) = number_str.parse::<i64>() {
356            return Ok(DataValue::Integer(int_val));
357        }
358
359        // If that fails, try as float
360        if let Ok(float_val) = number_str.parse::<f64>() {
361            return Ok(DataValue::Float(float_val));
362        }
363
364        Err(anyhow!("Invalid number literal: {}", number_str))
365    }
366
367    /// Evaluate a binary operation (arithmetic)
368    fn evaluate_binary_op(
369        &mut self,
370        left: &SqlExpression,
371        op: &str,
372        right: &SqlExpression,
373        row_index: usize,
374    ) -> Result<DataValue> {
375        let left_val = self.evaluate(left, row_index)?;
376        let right_val = self.evaluate(right, row_index)?;
377
378        debug!(
379            "ArithmeticEvaluator: {} {} {}",
380            self.format_value(&left_val),
381            op,
382            self.format_value(&right_val)
383        );
384
385        match op {
386            "+" => self.add_values(&left_val, &right_val),
387            "-" => self.subtract_values(&left_val, &right_val),
388            "*" => self.multiply_values(&left_val, &right_val),
389            "/" => self.divide_values(&left_val, &right_val),
390            "%" => {
391                // Modulo operator - call MOD function
392                let args = vec![left.clone(), right.clone()];
393                self.evaluate_function("MOD", &args, row_index)
394            }
395            // Comparison operators (return boolean results)
396            // Use centralized comparison logic for consistency
397            ">" | "<" | ">=" | "<=" | "=" | "!=" | "<>" => {
398                let result = compare_with_op(&left_val, &right_val, op, false);
399                Ok(DataValue::Boolean(result))
400            }
401            // IS NULL / IS NOT NULL operators
402            "IS NULL" => Ok(DataValue::Boolean(matches!(left_val, DataValue::Null))),
403            "IS NOT NULL" => Ok(DataValue::Boolean(!matches!(left_val, DataValue::Null))),
404            // Logical operators
405            "AND" => {
406                let left_bool = self.to_bool(&left_val)?;
407                let right_bool = self.to_bool(&right_val)?;
408                Ok(DataValue::Boolean(left_bool && right_bool))
409            }
410            "OR" => {
411                let left_bool = self.to_bool(&left_val)?;
412                let right_bool = self.to_bool(&right_val)?;
413                Ok(DataValue::Boolean(left_bool || right_bool))
414            }
415            // LIKE operator - SQL pattern matching
416            "LIKE" => {
417                let text = self.value_to_string(&left_val);
418                let pattern = self.value_to_string(&right_val);
419                let matches = self.sql_like_match(&text, &pattern);
420                Ok(DataValue::Boolean(matches))
421            }
422            _ => Err(anyhow!("Unsupported arithmetic operator: {}", op)),
423        }
424    }
425
426    /// Add two `DataValues` with type coercion
427    fn add_values(&self, left: &DataValue, right: &DataValue) -> Result<DataValue> {
428        // NULL handling - any operation with NULL returns NULL
429        if matches!(left, DataValue::Null) || matches!(right, DataValue::Null) {
430            return Ok(DataValue::Null);
431        }
432
433        match (left, right) {
434            (DataValue::Integer(a), DataValue::Integer(b)) => Ok(DataValue::Integer(a + b)),
435            (DataValue::Integer(a), DataValue::Float(b)) => Ok(DataValue::Float(*a as f64 + b)),
436            (DataValue::Float(a), DataValue::Integer(b)) => Ok(DataValue::Float(a + *b as f64)),
437            (DataValue::Float(a), DataValue::Float(b)) => Ok(DataValue::Float(a + b)),
438            _ => Err(anyhow!("Cannot add {:?} and {:?}", left, right)),
439        }
440    }
441
442    /// Subtract two `DataValues` with type coercion
443    fn subtract_values(&self, left: &DataValue, right: &DataValue) -> Result<DataValue> {
444        // NULL handling - any operation with NULL returns NULL
445        if matches!(left, DataValue::Null) || matches!(right, DataValue::Null) {
446            return Ok(DataValue::Null);
447        }
448
449        match (left, right) {
450            (DataValue::Integer(a), DataValue::Integer(b)) => Ok(DataValue::Integer(a - b)),
451            (DataValue::Integer(a), DataValue::Float(b)) => Ok(DataValue::Float(*a as f64 - b)),
452            (DataValue::Float(a), DataValue::Integer(b)) => Ok(DataValue::Float(a - *b as f64)),
453            (DataValue::Float(a), DataValue::Float(b)) => Ok(DataValue::Float(a - b)),
454            _ => Err(anyhow!("Cannot subtract {:?} and {:?}", left, right)),
455        }
456    }
457
458    /// Multiply two `DataValues` with type coercion
459    fn multiply_values(&self, left: &DataValue, right: &DataValue) -> Result<DataValue> {
460        // NULL handling - any operation with NULL returns NULL
461        if matches!(left, DataValue::Null) || matches!(right, DataValue::Null) {
462            return Ok(DataValue::Null);
463        }
464
465        match (left, right) {
466            (DataValue::Integer(a), DataValue::Integer(b)) => Ok(DataValue::Integer(a * b)),
467            (DataValue::Integer(a), DataValue::Float(b)) => Ok(DataValue::Float(*a as f64 * b)),
468            (DataValue::Float(a), DataValue::Integer(b)) => Ok(DataValue::Float(a * *b as f64)),
469            (DataValue::Float(a), DataValue::Float(b)) => Ok(DataValue::Float(a * b)),
470            _ => Err(anyhow!("Cannot multiply {:?} and {:?}", left, right)),
471        }
472    }
473
474    /// Divide two `DataValues` with type coercion
475    fn divide_values(&self, left: &DataValue, right: &DataValue) -> Result<DataValue> {
476        // NULL handling - any operation with NULL returns NULL
477        if matches!(left, DataValue::Null) || matches!(right, DataValue::Null) {
478            return Ok(DataValue::Null);
479        }
480
481        // Check for division by zero first
482        let is_zero = match right {
483            DataValue::Integer(0) => true,
484            DataValue::Float(f) if *f == 0.0 => true, // Only check for exact zero, not epsilon
485            _ => false,
486        };
487
488        if is_zero {
489            return Err(anyhow!("Division by zero"));
490        }
491
492        match (left, right) {
493            (DataValue::Integer(a), DataValue::Integer(b)) => {
494                // Integer division - if result is exact, keep as int, otherwise promote to float
495                if a % b == 0 {
496                    Ok(DataValue::Integer(a / b))
497                } else {
498                    Ok(DataValue::Float(*a as f64 / *b as f64))
499                }
500            }
501            (DataValue::Integer(a), DataValue::Float(b)) => Ok(DataValue::Float(*a as f64 / b)),
502            (DataValue::Float(a), DataValue::Integer(b)) => Ok(DataValue::Float(a / *b as f64)),
503            (DataValue::Float(a), DataValue::Float(b)) => Ok(DataValue::Float(a / b)),
504            _ => Err(anyhow!("Cannot divide {:?} and {:?}", left, right)),
505        }
506    }
507
508    /// Format a `DataValue` for debug output
509    fn format_value(&self, value: &DataValue) -> String {
510        match value {
511            DataValue::Integer(i) => i.to_string(),
512            DataValue::Float(f) => f.to_string(),
513            DataValue::String(s) => format!("'{s}'"),
514            _ => format!("{value:?}"),
515        }
516    }
517
518    /// Convert a DataValue to boolean for logical operations
519    fn to_bool(&self, value: &DataValue) -> Result<bool> {
520        match value {
521            DataValue::Boolean(b) => Ok(*b),
522            DataValue::Integer(i) => Ok(*i != 0),
523            DataValue::Float(f) => Ok(*f != 0.0),
524            DataValue::Null => Ok(false),
525            _ => Err(anyhow!("Cannot convert {:?} to boolean", value)),
526        }
527    }
528
529    /// Convert DataValue to string for pattern matching
530    fn value_to_string(&self, value: &DataValue) -> String {
531        match value {
532            DataValue::String(s) => s.clone(),
533            DataValue::InternedString(s) => s.to_string(),
534            DataValue::Integer(i) => i.to_string(),
535            DataValue::Float(f) => f.to_string(),
536            DataValue::Boolean(b) => b.to_string(),
537            DataValue::DateTime(dt) => dt.to_string(),
538            DataValue::Vector(v) => {
539                // Format as "[x,y,z]"
540                let components: Vec<String> = v.iter().map(|f| f.to_string()).collect();
541                format!("[{}]", components.join(","))
542            }
543            DataValue::Null => String::new(),
544        }
545    }
546
547    /// SQL LIKE pattern matching
548    /// Supports % (any chars) and _ (single char)
549    fn sql_like_match(&self, text: &str, pattern: &str) -> bool {
550        let pattern_chars: Vec<char> = pattern.chars().collect();
551        let text_chars: Vec<char> = text.chars().collect();
552
553        self.like_match_recursive(&text_chars, 0, &pattern_chars, 0)
554    }
555
556    /// Recursive helper for LIKE matching
557    fn like_match_recursive(
558        &self,
559        text: &[char],
560        text_pos: usize,
561        pattern: &[char],
562        pattern_pos: usize,
563    ) -> bool {
564        // If we've consumed both text and pattern, it's a match
565        if pattern_pos >= pattern.len() {
566            return text_pos >= text.len();
567        }
568
569        // Handle % wildcard (matches zero or more characters)
570        if pattern[pattern_pos] == '%' {
571            // Try matching zero characters (skip the %)
572            if self.like_match_recursive(text, text_pos, pattern, pattern_pos + 1) {
573                return true;
574            }
575            // Try matching one or more characters
576            if text_pos < text.len() {
577                return self.like_match_recursive(text, text_pos + 1, pattern, pattern_pos);
578            }
579            return false;
580        }
581
582        // If text is consumed but pattern isn't, no match
583        if text_pos >= text.len() {
584            return false;
585        }
586
587        // Handle _ wildcard (matches exactly one character)
588        if pattern[pattern_pos] == '_' {
589            return self.like_match_recursive(text, text_pos + 1, pattern, pattern_pos + 1);
590        }
591
592        // Handle literal character match
593        if text[text_pos] == pattern[pattern_pos] {
594            return self.like_match_recursive(text, text_pos + 1, pattern, pattern_pos + 1);
595        }
596
597        false
598    }
599
600    /// Evaluate a function call
601    fn evaluate_function_with_distinct(
602        &mut self,
603        name: &str,
604        args: &[SqlExpression],
605        distinct: bool,
606        row_index: usize,
607    ) -> Result<DataValue> {
608        // If DISTINCT is specified, handle it specially for aggregate functions
609        if distinct {
610            let name_upper = name.to_uppercase();
611
612            // Check if it's an aggregate function in either registry
613            if self.aggregate_registry.is_aggregate(&name_upper)
614                || self.new_aggregate_registry.contains(&name_upper)
615            {
616                return self.evaluate_aggregate_with_distinct(&name_upper, args, row_index);
617            } else {
618                return Err(anyhow!(
619                    "DISTINCT can only be used with aggregate functions"
620                ));
621            }
622        }
623
624        // Otherwise, use the regular evaluation
625        self.evaluate_function(name, args, row_index)
626    }
627
628    fn evaluate_aggregate_with_distinct(
629        &mut self,
630        name: &str,
631        args: &[SqlExpression],
632        _row_index: usize,
633    ) -> Result<DataValue> {
634        let name_upper = name.to_uppercase();
635
636        // Check new aggregate registry first for migrated functions
637        if self.new_aggregate_registry.get(&name_upper).is_some() {
638            let rows_to_process: Vec<usize> = if let Some(ref visible) = self.visible_rows {
639                visible.clone()
640            } else {
641                (0..self.table.rows.len()).collect()
642            };
643
644            // Collect and deduplicate values for DISTINCT
645            let mut vals = Vec::new();
646            for &row_idx in &rows_to_process {
647                if !args.is_empty() {
648                    let value = self.evaluate(&args[0], row_idx)?;
649                    vals.push(value);
650                }
651            }
652
653            // Deduplicate values
654            let mut seen = HashSet::new();
655            let unique_values: Vec<_> = vals
656                .into_iter()
657                .filter(|v| {
658                    let key = format!("{:?}", v);
659                    seen.insert(key)
660                })
661                .collect();
662
663            // Get the aggregate function from the new registry
664            let agg_func = self.new_aggregate_registry.get(&name_upper).unwrap();
665            let mut state = agg_func.create_state();
666
667            // Use unique values
668            for value in &unique_values {
669                state.accumulate(value)?;
670            }
671
672            return Ok(state.finalize());
673        }
674
675        // Check old aggregate registry (DISTINCT handling)
676        if self.aggregate_registry.get(&name_upper).is_some() {
677            // Determine which rows to process first
678            let rows_to_process: Vec<usize> = if let Some(ref visible) = self.visible_rows {
679                visible.clone()
680            } else {
681                (0..self.table.rows.len()).collect()
682            };
683
684            // Special handling for STRING_AGG with separator parameter
685            if name_upper == "STRING_AGG" && args.len() >= 2 {
686                // STRING_AGG(DISTINCT column, separator)
687                let mut state = crate::sql::aggregates::AggregateState::StringAgg(
688                    // Evaluate the separator (second argument) once
689                    if args.len() >= 2 {
690                        let separator = self.evaluate(&args[1], 0)?; // Separator doesn't depend on row
691                        match separator {
692                            DataValue::String(s) => crate::sql::aggregates::StringAggState::new(&s),
693                            DataValue::InternedString(s) => {
694                                crate::sql::aggregates::StringAggState::new(&s)
695                            }
696                            _ => crate::sql::aggregates::StringAggState::new(","), // Default separator
697                        }
698                    } else {
699                        crate::sql::aggregates::StringAggState::new(",")
700                    },
701                );
702
703                // Evaluate the first argument (column) for each row and accumulate
704                // Handle DISTINCT - use a HashSet to track seen values
705                let mut seen_values = HashSet::new();
706
707                for &row_idx in &rows_to_process {
708                    let value = self.evaluate(&args[0], row_idx)?;
709
710                    // Skip if we've seen this value
711                    if !seen_values.insert(value.clone()) {
712                        continue; // Skip duplicate values
713                    }
714
715                    // Now get the aggregate function and accumulate
716                    let agg_func = self.aggregate_registry.get(&name_upper).unwrap();
717                    agg_func.accumulate(&mut state, &value)?;
718                }
719
720                // Finalize the aggregate
721                let agg_func = self.aggregate_registry.get(&name_upper).unwrap();
722                return Ok(agg_func.finalize(state));
723            }
724
725            // For other aggregates with DISTINCT
726            // Evaluate the argument expression for each row
727            let mut vals = Vec::new();
728            for &row_idx in &rows_to_process {
729                if !args.is_empty() {
730                    let value = self.evaluate(&args[0], row_idx)?;
731                    vals.push(value);
732                }
733            }
734
735            // Deduplicate values for DISTINCT
736            let mut seen = HashSet::new();
737            let mut unique_values = Vec::new();
738            for value in vals {
739                if seen.insert(value.clone()) {
740                    unique_values.push(value);
741                }
742            }
743
744            // Now get the aggregate function and process
745            let agg_func = self.aggregate_registry.get(&name_upper).unwrap();
746            let mut state = agg_func.init();
747
748            // Use unique values
749            for value in &unique_values {
750                agg_func.accumulate(&mut state, value)?;
751            }
752
753            return Ok(agg_func.finalize(state));
754        }
755
756        Err(anyhow!("Unknown aggregate function: {}", name))
757    }
758
759    fn evaluate_function(
760        &mut self,
761        name: &str,
762        args: &[SqlExpression],
763        row_index: usize,
764    ) -> Result<DataValue> {
765        // Check if this is an aggregate function
766        let name_upper = name.to_uppercase();
767
768        // Check new aggregate registry first (for migrated functions)
769        if self.new_aggregate_registry.get(&name_upper).is_some() {
770            // Use new registry for SUM
771            let rows_to_process: Vec<usize> = if let Some(ref visible) = self.visible_rows {
772                visible.clone()
773            } else {
774                (0..self.table.rows.len()).collect()
775            };
776
777            // Get the aggregate function from the new registry
778            let agg_func = self.new_aggregate_registry.get(&name_upper).unwrap();
779            let mut state = agg_func.create_state();
780
781            // Special handling for COUNT(*)
782            if name_upper == "COUNT" || name_upper == "COUNT_STAR" {
783                if args.is_empty()
784                    || (args.len() == 1
785                        && matches!(&args[0], SqlExpression::Column(col) if col.name == "*"))
786                    || (args.len() == 1
787                        && matches!(&args[0], SqlExpression::StringLiteral(s) if s == "*"))
788                {
789                    // COUNT(*) or COUNT_STAR - count all rows
790                    for _ in &rows_to_process {
791                        state.accumulate(&DataValue::Integer(1))?;
792                    }
793                } else {
794                    // COUNT(column) - count non-null values
795                    for &row_idx in &rows_to_process {
796                        let value = self.evaluate(&args[0], row_idx)?;
797                        state.accumulate(&value)?;
798                    }
799                }
800            } else {
801                // Other aggregates - evaluate arguments and accumulate
802                if !args.is_empty() {
803                    for &row_idx in &rows_to_process {
804                        let value = self.evaluate(&args[0], row_idx)?;
805                        state.accumulate(&value)?;
806                    }
807                }
808            }
809
810            return Ok(state.finalize());
811        }
812
813        // Check old aggregate registry (for non-migrated functions)
814        if self.aggregate_registry.get(&name_upper).is_some() {
815            // Determine which rows to process first
816            let rows_to_process: Vec<usize> = if let Some(ref visible) = self.visible_rows {
817                visible.clone()
818            } else {
819                (0..self.table.rows.len()).collect()
820            };
821
822            // Special handling for STRING_AGG with separator parameter
823            if name_upper == "STRING_AGG" && args.len() >= 2 {
824                // STRING_AGG(column, separator) - without DISTINCT (handled separately)
825                let mut state = crate::sql::aggregates::AggregateState::StringAgg(
826                    // Evaluate the separator (second argument) once
827                    if args.len() >= 2 {
828                        let separator = self.evaluate(&args[1], 0)?; // Separator doesn't depend on row
829                        match separator {
830                            DataValue::String(s) => crate::sql::aggregates::StringAggState::new(&s),
831                            DataValue::InternedString(s) => {
832                                crate::sql::aggregates::StringAggState::new(&s)
833                            }
834                            _ => crate::sql::aggregates::StringAggState::new(","), // Default separator
835                        }
836                    } else {
837                        crate::sql::aggregates::StringAggState::new(",")
838                    },
839                );
840
841                // Evaluate the first argument (column) for each row and accumulate
842                for &row_idx in &rows_to_process {
843                    let value = self.evaluate(&args[0], row_idx)?;
844                    // Now get the aggregate function and accumulate
845                    let agg_func = self.aggregate_registry.get(&name_upper).unwrap();
846                    agg_func.accumulate(&mut state, &value)?;
847                }
848
849                // Finalize the aggregate
850                let agg_func = self.aggregate_registry.get(&name_upper).unwrap();
851                return Ok(agg_func.finalize(state));
852            }
853
854            // Evaluate arguments first if needed (to avoid borrow issues)
855            let values = if !args.is_empty()
856                && !(args.len() == 1
857                    && matches!(&args[0], SqlExpression::Column(c) if c.name == "*"))
858            {
859                // Evaluate the argument expression for each row
860                let mut vals = Vec::new();
861                for &row_idx in &rows_to_process {
862                    let value = self.evaluate(&args[0], row_idx)?;
863                    vals.push(value);
864                }
865                Some(vals)
866            } else {
867                None
868            };
869
870            // Now get the aggregate function and process
871            let agg_func = self.aggregate_registry.get(&name_upper).unwrap();
872            let mut state = agg_func.init();
873
874            if let Some(values) = values {
875                // Use evaluated values (DISTINCT is handled in evaluate_aggregate_with_distinct)
876                for value in &values {
877                    agg_func.accumulate(&mut state, value)?;
878                }
879            } else {
880                // COUNT(*) case
881                for _ in &rows_to_process {
882                    agg_func.accumulate(&mut state, &DataValue::Integer(1))?;
883                }
884            }
885
886            return Ok(agg_func.finalize(state));
887        }
888
889        // First check if this function exists in the registry
890        if self.function_registry.get(name).is_some() {
891            // Evaluate all arguments first to avoid borrow issues
892            let mut evaluated_args = Vec::new();
893            for arg in args {
894                evaluated_args.push(self.evaluate(arg, row_index)?);
895            }
896
897            // Get the function and call it
898            let func = self.function_registry.get(name).unwrap();
899            return func.evaluate(&evaluated_args);
900        }
901
902        // If not in registry, return error for unknown function
903        Err(anyhow!("Unknown function: {}", name))
904    }
905
906    /// Get or create a WindowContext for the given specification
907    /// Public to allow pre-creation of contexts in query engine (optimization)
908    pub fn get_or_create_window_context(
909        &mut self,
910        spec: &WindowSpec,
911    ) -> Result<Arc<WindowContext>> {
912        let overall_start = Instant::now();
913
914        // Create a hash-based key for fast caching (much faster than format!("{:?}", spec))
915        let key = spec.compute_hash();
916
917        if let Some(context) = self.window_contexts.get(&key) {
918            info!(
919                "WindowContext cache hit for spec (lookup: {:.2}μs)",
920                overall_start.elapsed().as_micros()
921            );
922            return Ok(Arc::clone(context));
923        }
924
925        info!("WindowContext cache miss - creating new context");
926        let dataview_start = Instant::now();
927
928        // Create a DataView from the table (with visible rows if filtered)
929        let data_view = if let Some(ref _visible_rows) = self.visible_rows {
930            // Create a filtered view
931            let view = DataView::new(Arc::new(self.table.clone()));
932            // Apply filtering based on visible rows
933            // Note: This is a simplified approach - in production we'd need proper filtering
934            view
935        } else {
936            DataView::new(Arc::new(self.table.clone()))
937        };
938
939        info!(
940            "DataView creation took {:.2}μs",
941            dataview_start.elapsed().as_micros()
942        );
943        let context_start = Instant::now();
944
945        // Create the WindowContext with the full spec (including frame)
946        let context = WindowContext::new_with_spec(Arc::new(data_view), spec.clone())?;
947
948        info!(
949            "WindowContext::new_with_spec took {:.2}ms (rows: {})",
950            context_start.elapsed().as_secs_f64() * 1000.0,
951            self.table.row_count()
952        );
953
954        let context = Arc::new(context);
955        self.window_contexts.insert(key, Arc::clone(&context));
956
957        info!(
958            "Total WindowContext creation (cache miss) took {:.2}ms",
959            overall_start.elapsed().as_secs_f64() * 1000.0
960        );
961
962        Ok(context)
963    }
964
965    /// Evaluate a window function
966    fn evaluate_window_function(
967        &mut self,
968        name: &str,
969        args: &[SqlExpression],
970        spec: &WindowSpec,
971        row_index: usize,
972    ) -> Result<DataValue> {
973        let func_start = Instant::now();
974        let name_upper = name.to_uppercase();
975
976        // First check if this is a syntactic sugar function in the registry
977        debug!("Looking for window function {} in registry", name_upper);
978        if let Some(window_fn_arc) = self.window_function_registry.get(&name_upper) {
979            debug!("Found window function {} in registry", name_upper);
980
981            // Dereference to get the actual window function
982            let window_fn = window_fn_arc.as_ref();
983
984            // Validate arguments
985            window_fn.validate_args(args)?;
986
987            // Transform the window spec based on the function's requirements
988            let transformed_spec = window_fn.transform_window_spec(spec, args)?;
989
990            // Get or create the window context with the transformed spec
991            let context = self.get_or_create_window_context(&transformed_spec)?;
992
993            // Create an expression evaluator adapter
994            struct EvaluatorAdapter<'a, 'b> {
995                evaluator: &'a mut ArithmeticEvaluator<'b>,
996                row_index: usize,
997            }
998
999            impl<'a, 'b> ExpressionEvaluator for EvaluatorAdapter<'a, 'b> {
1000                fn evaluate(
1001                    &mut self,
1002                    expr: &SqlExpression,
1003                    row_index: usize,
1004                ) -> Result<DataValue> {
1005                    self.evaluator.evaluate(expr, row_index)
1006                }
1007            }
1008
1009            let mut adapter = EvaluatorAdapter {
1010                evaluator: self,
1011                row_index,
1012            };
1013
1014            let compute_start = Instant::now();
1015            // Call the window function's compute method
1016            let result = window_fn.compute(&context, row_index, args, &mut adapter);
1017
1018            info!(
1019                "{} (registry) evaluation: total={:.2}μs, compute={:.2}μs",
1020                name_upper,
1021                func_start.elapsed().as_micros(),
1022                compute_start.elapsed().as_micros()
1023            );
1024
1025            return result;
1026        }
1027
1028        // Fall back to built-in window functions
1029        let context_start = Instant::now();
1030        let context = self.get_or_create_window_context(spec)?;
1031        let context_time = context_start.elapsed();
1032
1033        let eval_start = Instant::now();
1034
1035        let result = match name_upper.as_str() {
1036            "LAG" => {
1037                // LAG(column, offset, default)
1038                if args.is_empty() {
1039                    return Err(anyhow!("LAG requires at least 1 argument"));
1040                }
1041
1042                // Get column name
1043                let column = match &args[0] {
1044                    SqlExpression::Column(col) => col.clone(),
1045                    _ => return Err(anyhow!("LAG first argument must be a column")),
1046                };
1047
1048                // Get offset (default 1)
1049                let offset = if args.len() > 1 {
1050                    match self.evaluate(&args[1], row_index)? {
1051                        DataValue::Integer(i) => i as i32,
1052                        _ => return Err(anyhow!("LAG offset must be an integer")),
1053                    }
1054                } else {
1055                    1
1056                };
1057
1058                let offset_start = Instant::now();
1059                // Get value at offset
1060                let value = context
1061                    .get_offset_value(row_index, -offset, &column.name)
1062                    .unwrap_or(DataValue::Null);
1063
1064                debug!(
1065                    "LAG offset access took {:.2}μs (offset={})",
1066                    offset_start.elapsed().as_micros(),
1067                    offset
1068                );
1069
1070                Ok(value)
1071            }
1072            "LEAD" => {
1073                // LEAD(column, offset, default)
1074                if args.is_empty() {
1075                    return Err(anyhow!("LEAD requires at least 1 argument"));
1076                }
1077
1078                // Get column name
1079                let column = match &args[0] {
1080                    SqlExpression::Column(col) => col.clone(),
1081                    _ => return Err(anyhow!("LEAD first argument must be a column")),
1082                };
1083
1084                // Get offset (default 1)
1085                let offset = if args.len() > 1 {
1086                    match self.evaluate(&args[1], row_index)? {
1087                        DataValue::Integer(i) => i as i32,
1088                        _ => return Err(anyhow!("LEAD offset must be an integer")),
1089                    }
1090                } else {
1091                    1
1092                };
1093
1094                let offset_start = Instant::now();
1095                // Get value at offset
1096                let value = context
1097                    .get_offset_value(row_index, offset, &column.name)
1098                    .unwrap_or(DataValue::Null);
1099
1100                debug!(
1101                    "LEAD offset access took {:.2}μs (offset={})",
1102                    offset_start.elapsed().as_micros(),
1103                    offset
1104                );
1105
1106                Ok(value)
1107            }
1108            "ROW_NUMBER" => {
1109                // ROW_NUMBER() - no arguments
1110                Ok(DataValue::Integer(context.get_row_number(row_index) as i64))
1111            }
1112            "RANK" => {
1113                // RANK() - no arguments
1114                Ok(DataValue::Integer(context.get_rank(row_index)))
1115            }
1116            "DENSE_RANK" => {
1117                // DENSE_RANK() - no arguments
1118                Ok(DataValue::Integer(context.get_dense_rank(row_index)))
1119            }
1120            "FIRST_VALUE" => {
1121                // FIRST_VALUE(column) OVER (... ROWS ...)
1122                if args.is_empty() {
1123                    return Err(anyhow!("FIRST_VALUE requires 1 argument"));
1124                }
1125
1126                let column = match &args[0] {
1127                    SqlExpression::Column(col) => col.clone(),
1128                    _ => return Err(anyhow!("FIRST_VALUE argument must be a column")),
1129                };
1130
1131                // Use frame-aware version if frame is specified
1132                if context.has_frame() {
1133                    Ok(context
1134                        .get_frame_first_value(row_index, &column.name)
1135                        .unwrap_or(DataValue::Null))
1136                } else {
1137                    Ok(context
1138                        .get_first_value(row_index, &column.name)
1139                        .unwrap_or(DataValue::Null))
1140                }
1141            }
1142            "LAST_VALUE" => {
1143                // LAST_VALUE(column) OVER (... ROWS ...)
1144                if args.is_empty() {
1145                    return Err(anyhow!("LAST_VALUE requires 1 argument"));
1146                }
1147
1148                let column = match &args[0] {
1149                    SqlExpression::Column(col) => col.clone(),
1150                    _ => return Err(anyhow!("LAST_VALUE argument must be a column")),
1151                };
1152
1153                // Use frame-aware version if frame is specified
1154                if context.has_frame() {
1155                    Ok(context
1156                        .get_frame_last_value(row_index, &column.name)
1157                        .unwrap_or(DataValue::Null))
1158                } else {
1159                    Ok(context
1160                        .get_last_value(row_index, &column.name)
1161                        .unwrap_or(DataValue::Null))
1162                }
1163            }
1164            "SUM" => {
1165                // SUM(column) OVER (PARTITION BY ... ROWS n PRECEDING)
1166                if args.is_empty() {
1167                    return Err(anyhow!("SUM requires 1 argument"));
1168                }
1169
1170                let column = match &args[0] {
1171                    SqlExpression::Column(col) => col.clone(),
1172                    _ => return Err(anyhow!("SUM argument must be a column")),
1173                };
1174
1175                // Use frame-aware sum if frame is specified, otherwise use partition sum
1176                if context.has_frame() {
1177                    Ok(context
1178                        .get_frame_sum(row_index, &column.name)
1179                        .unwrap_or(DataValue::Null))
1180                } else {
1181                    Ok(context
1182                        .get_partition_sum(row_index, &column.name)
1183                        .unwrap_or(DataValue::Null))
1184                }
1185            }
1186            "AVG" => {
1187                // AVG(column) OVER (PARTITION BY ... ROWS n PRECEDING)
1188                if args.is_empty() {
1189                    return Err(anyhow!("AVG requires 1 argument"));
1190                }
1191
1192                let column = match &args[0] {
1193                    SqlExpression::Column(col) => col.clone(),
1194                    _ => return Err(anyhow!("AVG argument must be a column")),
1195                };
1196
1197                // Use frame-aware avg if frame is specified, otherwise use partition avg
1198                if context.has_frame() {
1199                    Ok(context
1200                        .get_frame_avg(row_index, &column.name)
1201                        .unwrap_or(DataValue::Null))
1202                } else {
1203                    Ok(context
1204                        .get_partition_avg(row_index, &column.name)
1205                        .unwrap_or(DataValue::Null))
1206                }
1207            }
1208            "STDDEV" | "STDEV" => {
1209                // STDDEV(column) OVER (PARTITION BY ... ROWS n PRECEDING)
1210                if args.is_empty() {
1211                    return Err(anyhow!("STDDEV requires 1 argument"));
1212                }
1213
1214                let column = match &args[0] {
1215                    SqlExpression::Column(col) => col.clone(),
1216                    _ => return Err(anyhow!("STDDEV argument must be a column")),
1217                };
1218
1219                Ok(context
1220                    .get_frame_stddev(row_index, &column.name)
1221                    .unwrap_or(DataValue::Null))
1222            }
1223            "VARIANCE" | "VAR" => {
1224                // VARIANCE(column) OVER (PARTITION BY ... ROWS n PRECEDING)
1225                if args.is_empty() {
1226                    return Err(anyhow!("VARIANCE requires 1 argument"));
1227                }
1228
1229                let column = match &args[0] {
1230                    SqlExpression::Column(col) => col.clone(),
1231                    _ => return Err(anyhow!("VARIANCE argument must be a column")),
1232                };
1233
1234                Ok(context
1235                    .get_frame_variance(row_index, &column.name)
1236                    .unwrap_or(DataValue::Null))
1237            }
1238            "MIN" => {
1239                // MIN(column) OVER (PARTITION BY ... ROWS n PRECEDING)
1240                if args.is_empty() {
1241                    return Err(anyhow!("MIN requires 1 argument"));
1242                }
1243
1244                let column = match &args[0] {
1245                    SqlExpression::Column(col) => col.clone(),
1246                    _ => return Err(anyhow!("MIN argument must be a column")),
1247                };
1248
1249                let frame_rows = context.get_frame_rows(row_index);
1250                if frame_rows.is_empty() {
1251                    return Ok(DataValue::Null);
1252                }
1253
1254                let source_table = context.source();
1255                let col_idx = source_table
1256                    .get_column_index(&column.name)
1257                    .ok_or_else(|| anyhow!("Column '{}' not found", column.name))?;
1258
1259                let mut min_value: Option<DataValue> = None;
1260                for &row_idx in &frame_rows {
1261                    if let Some(value) = source_table.get_value(row_idx, col_idx) {
1262                        if !matches!(value, DataValue::Null) {
1263                            match &min_value {
1264                                None => min_value = Some(value.clone()),
1265                                Some(current_min) => {
1266                                    if value < current_min {
1267                                        min_value = Some(value.clone());
1268                                    }
1269                                }
1270                            }
1271                        }
1272                    }
1273                }
1274
1275                Ok(min_value.unwrap_or(DataValue::Null))
1276            }
1277            "MAX" => {
1278                // MAX(column) OVER (PARTITION BY ... ROWS n PRECEDING)
1279                if args.is_empty() {
1280                    return Err(anyhow!("MAX requires 1 argument"));
1281                }
1282
1283                let column = match &args[0] {
1284                    SqlExpression::Column(col) => col.clone(),
1285                    _ => return Err(anyhow!("MAX argument must be a column")),
1286                };
1287
1288                let frame_rows = context.get_frame_rows(row_index);
1289                if frame_rows.is_empty() {
1290                    return Ok(DataValue::Null);
1291                }
1292
1293                let source_table = context.source();
1294                let col_idx = source_table
1295                    .get_column_index(&column.name)
1296                    .ok_or_else(|| anyhow!("Column '{}' not found", column.name))?;
1297
1298                let mut max_value: Option<DataValue> = None;
1299                for &row_idx in &frame_rows {
1300                    if let Some(value) = source_table.get_value(row_idx, col_idx) {
1301                        if !matches!(value, DataValue::Null) {
1302                            match &max_value {
1303                                None => max_value = Some(value.clone()),
1304                                Some(current_max) => {
1305                                    if value > current_max {
1306                                        max_value = Some(value.clone());
1307                                    }
1308                                }
1309                            }
1310                        }
1311                    }
1312                }
1313
1314                Ok(max_value.unwrap_or(DataValue::Null))
1315            }
1316            "COUNT" => {
1317                // COUNT(*) or COUNT(column) OVER (PARTITION BY ... ROWS n PRECEDING)
1318                // Use frame-aware count if frame is specified, otherwise use partition count
1319
1320                if args.is_empty() {
1321                    // COUNT(*) OVER (...)
1322                    if context.has_frame() {
1323                        Ok(context
1324                            .get_frame_count(row_index, None)
1325                            .unwrap_or(DataValue::Null))
1326                    } else {
1327                        Ok(context
1328                            .get_partition_count(row_index, None)
1329                            .unwrap_or(DataValue::Null))
1330                    }
1331                } else {
1332                    // Check for COUNT(*)
1333                    let column = match &args[0] {
1334                        SqlExpression::Column(col) => {
1335                            if col.name == "*" {
1336                                // COUNT(*) - count all rows
1337                                if context.has_frame() {
1338                                    return Ok(context
1339                                        .get_frame_count(row_index, None)
1340                                        .unwrap_or(DataValue::Null));
1341                                } else {
1342                                    return Ok(context
1343                                        .get_partition_count(row_index, None)
1344                                        .unwrap_or(DataValue::Null));
1345                                }
1346                            }
1347                            col.clone()
1348                        }
1349                        SqlExpression::StringLiteral(s) if s == "*" => {
1350                            // COUNT(*) as StringLiteral
1351                            if context.has_frame() {
1352                                return Ok(context
1353                                    .get_frame_count(row_index, None)
1354                                    .unwrap_or(DataValue::Null));
1355                            } else {
1356                                return Ok(context
1357                                    .get_partition_count(row_index, None)
1358                                    .unwrap_or(DataValue::Null));
1359                            }
1360                        }
1361                        _ => return Err(anyhow!("COUNT argument must be a column or *")),
1362                    };
1363
1364                    // COUNT(column) - count non-null values
1365                    if context.has_frame() {
1366                        Ok(context
1367                            .get_frame_count(row_index, Some(&column.name))
1368                            .unwrap_or(DataValue::Null))
1369                    } else {
1370                        Ok(context
1371                            .get_partition_count(row_index, Some(&column.name))
1372                            .unwrap_or(DataValue::Null))
1373                    }
1374                }
1375            }
1376            _ => Err(anyhow!("Unknown window function: {}", name)),
1377        };
1378
1379        let eval_time = eval_start.elapsed();
1380
1381        info!(
1382            "{} (built-in) evaluation: total={:.2}μs, context={:.2}μs, eval={:.2}μs",
1383            name_upper,
1384            func_start.elapsed().as_micros(),
1385            context_time.as_micros(),
1386            eval_time.as_micros()
1387        );
1388
1389        result
1390    }
1391
1392    /// Evaluate a method call on a column (e.g., `column.Trim()`)
1393    fn evaluate_method_call(
1394        &mut self,
1395        object: &str,
1396        method: &str,
1397        args: &[SqlExpression],
1398        row_index: usize,
1399    ) -> Result<DataValue> {
1400        // Get column value
1401        let col_index = self.table.get_column_index(object).ok_or_else(|| {
1402            let suggestion = self.find_similar_column(object);
1403            match suggestion {
1404                Some(similar) => {
1405                    anyhow!("Column '{}' not found. Did you mean '{}'?", object, similar)
1406                }
1407                None => anyhow!("Column '{}' not found", object),
1408            }
1409        })?;
1410
1411        let cell_value = self.table.get_value(row_index, col_index).cloned();
1412
1413        self.evaluate_method_on_value(
1414            &cell_value.unwrap_or(DataValue::Null),
1415            method,
1416            args,
1417            row_index,
1418        )
1419    }
1420
1421    /// Evaluate a method on a value
1422    fn evaluate_method_on_value(
1423        &mut self,
1424        value: &DataValue,
1425        method: &str,
1426        args: &[SqlExpression],
1427        row_index: usize,
1428    ) -> Result<DataValue> {
1429        // Method-call syntax (`x.Method(...)`) dispatches through the method
1430        // registry first, so a function can give its C#-style method form
1431        // different semantics from its SQL function form (e.g. SUBSTRING is
1432        // 1-based as a function but `.Substring()` is 0-based like .NET).
1433        // The default `evaluate_method` just prepends the receiver and calls
1434        // `evaluate`, so this is behavior-preserving for every other method.
1435        if let Some(method_fn) = self.function_registry.get_method(method) {
1436            let mut method_args = Vec::with_capacity(args.len());
1437            for arg in args {
1438                method_args.push(self.evaluate(arg, row_index)?);
1439            }
1440            return method_fn.evaluate_method(value, &method_args);
1441        }
1442
1443        // Otherwise, proxy the method through the function registry.
1444        // Many string methods have corresponding functions (TRIM, LENGTH, CONTAINS, etc.)
1445
1446        // Map method names to function names (case-insensitive matching)
1447        let function_name = match method.to_lowercase().as_str() {
1448            "trim" => "TRIM",
1449            "trimstart" | "trimbegin" => "TRIMSTART",
1450            "trimend" => "TRIMEND",
1451            "length" | "len" => "LENGTH",
1452            "contains" => "CONTAINS",
1453            "startswith" => "STARTSWITH",
1454            "endswith" => "ENDSWITH",
1455            "indexof" => "INDEXOF",
1456            _ => method, // Try the method name as-is
1457        };
1458
1459        // Check if we have this function in the registry
1460        if self.function_registry.get(function_name).is_some() {
1461            debug!(
1462                "Proxying method '{}' through function registry as '{}'",
1463                method, function_name
1464            );
1465
1466            // Prepare arguments: receiver is the first argument, followed by method args
1467            let mut func_args = vec![value.clone()];
1468
1469            // Evaluate method arguments and add them
1470            for arg in args {
1471                func_args.push(self.evaluate(arg, row_index)?);
1472            }
1473
1474            // Get the function and call it
1475            let func = self.function_registry.get(function_name).unwrap();
1476            return func.evaluate(&func_args);
1477        }
1478
1479        // If not in registry, the method is not supported
1480        // All methods should be registered in the function registry
1481        Err(anyhow!(
1482            "Method '{}' not found. It should be registered in the function registry.",
1483            method
1484        ))
1485    }
1486
1487    /// Evaluate a CASE expression
1488    fn evaluate_case_expression(
1489        &mut self,
1490        when_branches: &[crate::sql::recursive_parser::WhenBranch],
1491        else_branch: &Option<Box<SqlExpression>>,
1492        row_index: usize,
1493    ) -> Result<DataValue> {
1494        debug!(
1495            "ArithmeticEvaluator: evaluating CASE expression for row {}",
1496            row_index
1497        );
1498
1499        // Evaluate each WHEN condition in order
1500        for branch in when_branches {
1501            // Evaluate the condition as a boolean
1502            let condition_result = self.evaluate_condition_as_bool(&branch.condition, row_index)?;
1503
1504            if condition_result {
1505                debug!("CASE: WHEN condition matched, evaluating result expression");
1506                return self.evaluate(&branch.result, row_index);
1507            }
1508        }
1509
1510        // If no WHEN condition matched, evaluate ELSE clause (or return NULL)
1511        if let Some(else_expr) = else_branch {
1512            debug!("CASE: No WHEN matched, evaluating ELSE expression");
1513            self.evaluate(else_expr, row_index)
1514        } else {
1515            debug!("CASE: No WHEN matched and no ELSE, returning NULL");
1516            Ok(DataValue::Null)
1517        }
1518    }
1519
1520    /// Evaluate a simple CASE expression
1521    fn evaluate_simple_case_expression(
1522        &mut self,
1523        expr: &Box<SqlExpression>,
1524        when_branches: &[crate::sql::parser::ast::SimpleWhenBranch],
1525        else_branch: &Option<Box<SqlExpression>>,
1526        row_index: usize,
1527    ) -> Result<DataValue> {
1528        debug!(
1529            "ArithmeticEvaluator: evaluating simple CASE expression for row {}",
1530            row_index
1531        );
1532
1533        // Evaluate the main expression once
1534        let case_value = self.evaluate(expr, row_index)?;
1535        debug!("Simple CASE: evaluated expression to {:?}", case_value);
1536
1537        // Compare against each WHEN value in order
1538        for branch in when_branches {
1539            // Evaluate the WHEN value
1540            let when_value = self.evaluate(&branch.value, row_index)?;
1541
1542            // Check for equality
1543            if self.values_equal(&case_value, &when_value)? {
1544                debug!("Simple CASE: WHEN value matched, evaluating result expression");
1545                return self.evaluate(&branch.result, row_index);
1546            }
1547        }
1548
1549        // If no WHEN value matched, evaluate ELSE clause (or return NULL)
1550        if let Some(else_expr) = else_branch {
1551            debug!("Simple CASE: No WHEN matched, evaluating ELSE expression");
1552            self.evaluate(else_expr, row_index)
1553        } else {
1554            debug!("Simple CASE: No WHEN matched and no ELSE, returning NULL");
1555            Ok(DataValue::Null)
1556        }
1557    }
1558
1559    /// Check if two DataValues are equal
1560    fn values_equal(&self, left: &DataValue, right: &DataValue) -> Result<bool> {
1561        match (left, right) {
1562            (DataValue::Null, DataValue::Null) => Ok(true),
1563            (DataValue::Null, _) | (_, DataValue::Null) => Ok(false),
1564            (DataValue::Integer(a), DataValue::Integer(b)) => Ok(a == b),
1565            (DataValue::Float(a), DataValue::Float(b)) => Ok((a - b).abs() < f64::EPSILON),
1566            (DataValue::String(a), DataValue::String(b)) => Ok(a == b),
1567            (DataValue::Boolean(a), DataValue::Boolean(b)) => Ok(a == b),
1568            (DataValue::DateTime(a), DataValue::DateTime(b)) => Ok(a == b),
1569            // Type coercion for numeric comparisons
1570            (DataValue::Integer(a), DataValue::Float(b)) => {
1571                Ok((*a as f64 - b).abs() < f64::EPSILON)
1572            }
1573            (DataValue::Float(a), DataValue::Integer(b)) => {
1574                Ok((a - *b as f64).abs() < f64::EPSILON)
1575            }
1576            _ => Ok(false),
1577        }
1578    }
1579
1580    /// Helper method to evaluate an expression as a boolean (for CASE WHEN conditions)
1581    fn evaluate_condition_as_bool(
1582        &mut self,
1583        expr: &SqlExpression,
1584        row_index: usize,
1585    ) -> Result<bool> {
1586        let value = self.evaluate(expr, row_index)?;
1587
1588        match value {
1589            DataValue::Boolean(b) => Ok(b),
1590            DataValue::Integer(i) => Ok(i != 0),
1591            DataValue::Float(f) => Ok(f != 0.0),
1592            DataValue::Null => Ok(false),
1593            DataValue::String(s) => Ok(!s.is_empty()),
1594            DataValue::InternedString(s) => Ok(!s.is_empty()),
1595            _ => Ok(true), // Other types are considered truthy
1596        }
1597    }
1598
1599    /// Evaluate a DATETIME constructor expression
1600    fn evaluate_datetime_constructor(
1601        &self,
1602        year: i32,
1603        month: u32,
1604        day: u32,
1605        hour: Option<u32>,
1606        minute: Option<u32>,
1607        second: Option<u32>,
1608    ) -> Result<DataValue> {
1609        use chrono::{NaiveDate, TimeZone, Utc};
1610
1611        // Create a NaiveDate
1612        let date = NaiveDate::from_ymd_opt(year, month, day)
1613            .ok_or_else(|| anyhow!("Invalid date: {}-{}-{}", year, month, day))?;
1614
1615        // Create datetime with provided time components or defaults
1616        let hour = hour.unwrap_or(0);
1617        let minute = minute.unwrap_or(0);
1618        let second = second.unwrap_or(0);
1619
1620        let naive_datetime = date
1621            .and_hms_opt(hour, minute, second)
1622            .ok_or_else(|| anyhow!("Invalid time: {}:{}:{}", hour, minute, second))?;
1623
1624        // Convert to UTC DateTime
1625        let datetime = Utc.from_utc_datetime(&naive_datetime);
1626
1627        // Format as string with milliseconds
1628        let datetime_str = datetime.format("%Y-%m-%d %H:%M:%S%.3f").to_string();
1629        Ok(DataValue::String(datetime_str))
1630    }
1631
1632    /// Evaluate a DATETIME.TODAY constructor expression
1633    fn evaluate_datetime_today(
1634        &self,
1635        hour: Option<u32>,
1636        minute: Option<u32>,
1637        second: Option<u32>,
1638    ) -> Result<DataValue> {
1639        use chrono::{TimeZone, Utc};
1640
1641        // Get today's date in UTC
1642        let today = Utc::now().date_naive();
1643
1644        // Create datetime with provided time components or defaults
1645        let hour = hour.unwrap_or(0);
1646        let minute = minute.unwrap_or(0);
1647        let second = second.unwrap_or(0);
1648
1649        let naive_datetime = today
1650            .and_hms_opt(hour, minute, second)
1651            .ok_or_else(|| anyhow!("Invalid time: {}:{}:{}", hour, minute, second))?;
1652
1653        // Convert to UTC DateTime
1654        let datetime = Utc.from_utc_datetime(&naive_datetime);
1655
1656        // Format as string with milliseconds
1657        let datetime_str = datetime.format("%Y-%m-%d %H:%M:%S%.3f").to_string();
1658        Ok(DataValue::String(datetime_str))
1659    }
1660}
1661
1662#[cfg(test)]
1663mod tests {
1664    use super::*;
1665    use crate::data::datatable::{DataColumn, DataRow};
1666
1667    fn create_test_table() -> DataTable {
1668        let mut table = DataTable::new("test");
1669        table.add_column(DataColumn::new("a"));
1670        table.add_column(DataColumn::new("b"));
1671        table.add_column(DataColumn::new("c"));
1672
1673        table
1674            .add_row(DataRow::new(vec![
1675                DataValue::Integer(10),
1676                DataValue::Float(2.5),
1677                DataValue::Integer(4),
1678            ]))
1679            .unwrap();
1680
1681        table
1682    }
1683
1684    #[test]
1685    fn test_evaluate_column() {
1686        let table = create_test_table();
1687        let mut evaluator = ArithmeticEvaluator::new(&table);
1688
1689        let expr = SqlExpression::Column(ColumnRef::unquoted("a".to_string()));
1690        let result = evaluator.evaluate(&expr, 0).unwrap();
1691        assert_eq!(result, DataValue::Integer(10));
1692    }
1693
1694    #[test]
1695    fn test_evaluate_between_column_in_range() {
1696        let table = create_test_table();
1697        let mut evaluator = ArithmeticEvaluator::new(&table);
1698
1699        // column 'a' is 10 — 5 <= 10 <= 20 is true
1700        let expr = SqlExpression::Between {
1701            expr: Box::new(SqlExpression::Column(ColumnRef::unquoted("a".to_string()))),
1702            lower: Box::new(SqlExpression::NumberLiteral("5".to_string())),
1703            upper: Box::new(SqlExpression::NumberLiteral("20".to_string())),
1704        };
1705        assert_eq!(
1706            evaluator.evaluate(&expr, 0).unwrap(),
1707            DataValue::Boolean(true)
1708        );
1709    }
1710
1711    #[test]
1712    fn test_evaluate_between_column_out_of_range() {
1713        let table = create_test_table();
1714        let mut evaluator = ArithmeticEvaluator::new(&table);
1715
1716        // column 'a' is 10 — 11 <= 10 <= 20 is false
1717        let expr = SqlExpression::Between {
1718            expr: Box::new(SqlExpression::Column(ColumnRef::unquoted("a".to_string()))),
1719            lower: Box::new(SqlExpression::NumberLiteral("11".to_string())),
1720            upper: Box::new(SqlExpression::NumberLiteral("20".to_string())),
1721        };
1722        assert_eq!(
1723            evaluator.evaluate(&expr, 0).unwrap(),
1724            DataValue::Boolean(false)
1725        );
1726    }
1727
1728    #[test]
1729    fn test_evaluate_between_endpoints_inclusive() {
1730        let table = create_test_table();
1731        let mut evaluator = ArithmeticEvaluator::new(&table);
1732
1733        // column 'a' is 10 — 10 <= 10 <= 10 is true (both endpoints inclusive)
1734        let expr = SqlExpression::Between {
1735            expr: Box::new(SqlExpression::Column(ColumnRef::unquoted("a".to_string()))),
1736            lower: Box::new(SqlExpression::NumberLiteral("10".to_string())),
1737            upper: Box::new(SqlExpression::NumberLiteral("10".to_string())),
1738        };
1739        assert_eq!(
1740            evaluator.evaluate(&expr, 0).unwrap(),
1741            DataValue::Boolean(true)
1742        );
1743    }
1744
1745    #[test]
1746    fn test_evaluate_number_literal() {
1747        let table = create_test_table();
1748        let mut evaluator = ArithmeticEvaluator::new(&table);
1749
1750        let expr = SqlExpression::NumberLiteral("42".to_string());
1751        let result = evaluator.evaluate(&expr, 0).unwrap();
1752        assert_eq!(result, DataValue::Integer(42));
1753
1754        let expr = SqlExpression::NumberLiteral("3.14".to_string());
1755        let result = evaluator.evaluate(&expr, 0).unwrap();
1756        assert_eq!(result, DataValue::Float(3.14));
1757    }
1758
1759    #[test]
1760    fn test_add_values() {
1761        let table = create_test_table();
1762        let mut evaluator = ArithmeticEvaluator::new(&table);
1763
1764        // Integer + Integer
1765        let result = evaluator
1766            .add_values(&DataValue::Integer(5), &DataValue::Integer(3))
1767            .unwrap();
1768        assert_eq!(result, DataValue::Integer(8));
1769
1770        // Integer + Float
1771        let result = evaluator
1772            .add_values(&DataValue::Integer(5), &DataValue::Float(2.5))
1773            .unwrap();
1774        assert_eq!(result, DataValue::Float(7.5));
1775    }
1776
1777    #[test]
1778    fn test_multiply_values() {
1779        let table = create_test_table();
1780        let mut evaluator = ArithmeticEvaluator::new(&table);
1781
1782        // Integer * Float
1783        let result = evaluator
1784            .multiply_values(&DataValue::Integer(4), &DataValue::Float(2.5))
1785            .unwrap();
1786        assert_eq!(result, DataValue::Float(10.0));
1787    }
1788
1789    #[test]
1790    fn test_divide_values() {
1791        let table = create_test_table();
1792        let mut evaluator = ArithmeticEvaluator::new(&table);
1793
1794        // Exact division
1795        let result = evaluator
1796            .divide_values(&DataValue::Integer(10), &DataValue::Integer(2))
1797            .unwrap();
1798        assert_eq!(result, DataValue::Integer(5));
1799
1800        // Non-exact division
1801        let result = evaluator
1802            .divide_values(&DataValue::Integer(10), &DataValue::Integer(3))
1803            .unwrap();
1804        assert_eq!(result, DataValue::Float(10.0 / 3.0));
1805    }
1806
1807    #[test]
1808    fn test_division_by_zero() {
1809        let table = create_test_table();
1810        let mut evaluator = ArithmeticEvaluator::new(&table);
1811
1812        let result = evaluator.divide_values(&DataValue::Integer(10), &DataValue::Integer(0));
1813        assert!(result.is_err());
1814        assert!(result.unwrap_err().to_string().contains("Division by zero"));
1815    }
1816
1817    #[test]
1818    fn test_binary_op_expression() {
1819        let table = create_test_table();
1820        let mut evaluator = ArithmeticEvaluator::new(&table);
1821
1822        // a * b where a=10, b=2.5
1823        let expr = SqlExpression::BinaryOp {
1824            left: Box::new(SqlExpression::Column(ColumnRef::unquoted("a".to_string()))),
1825            op: "*".to_string(),
1826            right: Box::new(SqlExpression::Column(ColumnRef::unquoted("b".to_string()))),
1827        };
1828
1829        let result = evaluator.evaluate(&expr, 0).unwrap();
1830        assert_eq!(result, DataValue::Float(25.0));
1831    }
1832}