Skip to main content

mdql_core/
query_engine.rs

1//! Execute parsed queries over in-memory rows.
2
3use std::cmp::Ordering;
4use std::collections::HashMap;
5
6use regex::Regex;
7
8use crate::errors::MdqlError;
9use crate::model::{Row, Value};
10use crate::query_parser::*;
11use crate::schema::Schema;
12
13pub fn execute_query(
14    query: &SelectQuery,
15    rows: &[Row],
16    _schema: &Schema,
17) -> crate::errors::Result<(Vec<Row>, Vec<String>)> {
18    execute(query, rows, None)
19}
20
21/// Execute a query with optional B-tree index and FTS searcher.
22pub fn execute_query_indexed(
23    query: &SelectQuery,
24    rows: &[Row],
25    schema: &Schema,
26    index: Option<&crate::index::TableIndex>,
27    searcher: Option<&crate::search::TableSearcher>,
28) -> crate::errors::Result<(Vec<Row>, Vec<String>)> {
29    // Pre-compute FTS results for any LIKE clauses on section columns
30    let fts_results = if let (Some(ref wc), Some(searcher)) = (&query.where_clause, searcher) {
31        collect_fts_results(wc, schema, searcher)
32    } else {
33        HashMap::new()
34    };
35
36    execute_with_fts(query, rows, index, &fts_results)
37}
38
39/// Collect FTS results for LIKE comparisons on section columns.
40/// Returns a map from (column, pattern) → set of matching paths.
41fn collect_fts_results(
42    clause: &WhereClause,
43    schema: &Schema,
44    searcher: &crate::search::TableSearcher,
45) -> HashMap<(String, String), std::collections::HashSet<String>> {
46    let mut results = HashMap::new();
47    collect_fts_results_inner(clause, schema, searcher, &mut results);
48    results
49}
50
51fn collect_fts_results_inner(
52    clause: &WhereClause,
53    schema: &Schema,
54    searcher: &crate::search::TableSearcher,
55    results: &mut HashMap<(String, String), std::collections::HashSet<String>>,
56) {
57    match clause {
58        WhereClause::Comparison(cmp) => {
59            if (cmp.op == "LIKE" || cmp.op == "NOT LIKE") && schema.sections.contains_key(&cmp.column) {
60                if let Some(SqlValue::String(pattern)) = &cmp.value {
61                    // Strip SQL wildcards for Tantivy query
62                    let search_term = pattern.replace('%', " ").replace('_', " ").trim().to_string();
63                    if !search_term.is_empty() {
64                        if let Ok(paths) = searcher.search(&search_term, Some(&cmp.column)) {
65                            let key = (cmp.column.clone(), pattern.clone());
66                            results.insert(key, paths.into_iter().collect());
67                        }
68                    }
69                }
70            }
71        }
72        WhereClause::BoolOp(bop) => {
73            collect_fts_results_inner(&bop.left, schema, searcher, results);
74            collect_fts_results_inner(&bop.right, schema, searcher, results);
75        }
76    }
77}
78
79type FtsResults = HashMap<(String, String), std::collections::HashSet<String>>;
80
81fn execute_with_fts(
82    query: &SelectQuery,
83    rows: &[Row],
84    index: Option<&crate::index::TableIndex>,
85    fts: &FtsResults,
86) -> crate::errors::Result<(Vec<Row>, Vec<String>)> {
87    // Determine available columns
88    let mut all_columns: Vec<String> = Vec::new();
89    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
90    for r in rows {
91        for k in r.keys() {
92            if seen.insert(k.clone()) {
93                all_columns.push(k.clone());
94            }
95        }
96    }
97
98    // Check if query has aggregates
99    let has_aggregates = match &query.columns {
100        ColumnList::Named(exprs) => exprs.iter().any(|e| e.is_aggregate()),
101        _ => false,
102    };
103
104    // Output column names
105    let columns: Vec<String> = match &query.columns {
106        ColumnList::All => all_columns,
107        ColumnList::Named(exprs) => exprs.iter().map(|e| e.output_name()).collect(),
108    };
109
110    // Filter — try index first, fall back to full scan
111    let filtered: Vec<Row> = if let Some(ref wc) = query.where_clause {
112        let candidate_paths = index.and_then(|idx| try_index_filter(wc, idx));
113        if let Some(paths) = candidate_paths {
114            rows.iter()
115                .filter(|r| {
116                    r.get("path")
117                        .and_then(|v| v.as_str())
118                        .map_or(false, |p| paths.contains(p))
119                })
120                .filter(|r| evaluate_with_fts(wc, r, fts))
121                .cloned()
122                .collect()
123        } else {
124            rows.iter()
125                .filter(|r| evaluate_with_fts(wc, r, fts))
126                .cloned()
127                .collect()
128        }
129    } else {
130        rows.to_vec()
131    };
132
133    // Aggregate if needed
134    let mut result = if has_aggregates || query.group_by.is_some() {
135        let exprs = match &query.columns {
136            ColumnList::Named(exprs) => exprs.clone(),
137            _ => return Err(MdqlError::QueryExecution(
138                "SELECT * with GROUP BY is not supported".into(),
139            )),
140        };
141        let group_keys = query.group_by.as_deref().unwrap_or(&[]);
142        aggregate_rows(&filtered, &exprs, group_keys)?
143    } else {
144        filtered
145    };
146
147    // HAVING filter — apply after aggregation
148    if let Some(ref having) = query.having {
149        result.retain(|row| evaluate(having, row));
150    }
151
152    // Sort — resolve ORDER BY aliases against SELECT list
153    if let Some(ref order_by) = query.order_by {
154        let resolved = resolve_order_aliases(order_by, &query.columns);
155        sort_rows(&mut result, &resolved);
156    }
157
158    // Limit
159    if let Some(limit) = query.limit {
160        result.truncate(limit as usize);
161    }
162
163    // Project — evaluate expressions and strip to requested columns
164    if !matches!(query.columns, ColumnList::All) {
165        let named_exprs = match &query.columns {
166            ColumnList::Named(exprs) => exprs,
167            _ => unreachable!(),
168        };
169
170        // Compute expression columns first, then retain only requested columns
171        let has_expr_cols = named_exprs.iter().any(|e| matches!(e, SelectExpr::Expr { .. }));
172        if has_expr_cols {
173            for row in &mut result {
174                for expr in named_exprs {
175                    if let SelectExpr::Expr { expr: e, alias } = expr {
176                        let name = alias.clone().unwrap_or_else(|| e.display_name());
177                        let val = evaluate_expr(e, row);
178                        row.insert(name, val);
179                    }
180                }
181            }
182        }
183
184        let col_set: std::collections::HashSet<&str> =
185            columns.iter().map(|s| s.as_str()).collect();
186        for row in &mut result {
187            row.retain(|k, _| col_set.contains(k.as_str()));
188        }
189    }
190
191    Ok((result, columns))
192}
193
194fn aggregate_rows(
195    rows: &[Row],
196    exprs: &[SelectExpr],
197    group_keys: &[String],
198) -> crate::errors::Result<Vec<Row>> {
199    // Group rows by group_keys
200    let mut groups: Vec<(Vec<Value>, Vec<&Row>)> = Vec::new();
201    let mut key_index: HashMap<Vec<String>, usize> = HashMap::new();
202
203    if group_keys.is_empty() {
204        // No GROUP BY — all rows are one group
205        let all_refs: Vec<&Row> = rows.iter().collect();
206        groups.push((vec![], all_refs));
207    } else {
208        for row in rows {
209            let key: Vec<String> = group_keys
210                .iter()
211                .map(|k| {
212                    row.get(k)
213                        .map(|v| v.to_display_string())
214                        .unwrap_or_default()
215                })
216                .collect();
217            let key_vals: Vec<Value> = group_keys
218                .iter()
219                .map(|k| row.get(k).cloned().unwrap_or(Value::Null))
220                .collect();
221            if let Some(&idx) = key_index.get(&key) {
222                groups[idx].1.push(row);
223            } else {
224                let idx = groups.len();
225                key_index.insert(key, idx);
226                groups.push((key_vals, vec![row]));
227            }
228        }
229    }
230
231    // Compute aggregates per group
232    let mut result = Vec::new();
233    for (key_vals, group_rows) in &groups {
234        let mut out = Row::new();
235
236        // Fill in group key values
237        for (i, k) in group_keys.iter().enumerate() {
238            out.insert(k.clone(), key_vals[i].clone());
239        }
240
241        // Compute each expression
242        for expr in exprs {
243            match expr {
244                SelectExpr::Column(name) => {
245                    // Already filled if it's a group key; otherwise take first row's value
246                    if !out.contains_key(name) {
247                        if let Some(first) = group_rows.first() {
248                            out.insert(
249                                name.clone(),
250                                first.get(name).cloned().unwrap_or(Value::Null),
251                            );
252                        }
253                    }
254                }
255                SelectExpr::Aggregate { func, arg, arg_expr, alias } => {
256                    let out_name = alias
257                        .clone()
258                        .unwrap_or_else(|| expr.output_name());
259                    let val = compute_aggregate(func, arg, arg_expr.as_ref(), group_rows);
260                    out.insert(out_name, val);
261                }
262                SelectExpr::Expr { expr: e, alias } => {
263                    let out_name = alias.clone().unwrap_or_else(|| e.display_name());
264                    if let Some(first) = group_rows.first() {
265                        let val = evaluate_expr(e, first);
266                        out.insert(out_name, val);
267                    }
268                }
269            }
270        }
271
272        result.push(out);
273    }
274
275    Ok(result)
276}
277
278/// Resolve a per-row value for an aggregate argument.
279/// If `arg_expr` is set, evaluate it; otherwise look up `arg` as a column name.
280fn resolve_agg_value<'a>(arg: &str, arg_expr: Option<&Expr>, row: &'a Row) -> Value {
281    if let Some(expr) = arg_expr {
282        evaluate_expr(expr, row)
283    } else {
284        row.get(arg).cloned().unwrap_or(Value::Null)
285    }
286}
287
288fn compute_aggregate(func: &AggFunc, arg: &str, arg_expr: Option<&Expr>, rows: &[&Row]) -> Value {
289    match func {
290        AggFunc::Count => {
291            if arg == "*" && arg_expr.is_none() {
292                Value::Int(rows.len() as i64)
293            } else {
294                let count = rows
295                    .iter()
296                    .filter(|r| {
297                        let v = resolve_agg_value(arg, arg_expr, r);
298                        !v.is_null()
299                    })
300                    .count();
301                Value::Int(count as i64)
302            }
303        }
304        AggFunc::Sum => {
305            let mut total = 0.0f64;
306            let mut has_any = false;
307            for r in rows {
308                let v = resolve_agg_value(arg, arg_expr, r);
309                match v {
310                    Value::Int(n) => { total += n as f64; has_any = true; }
311                    Value::Float(f) => { total += f; has_any = true; }
312                    _ => {}
313                }
314            }
315            if has_any { Value::Float(total) } else { Value::Null }
316        }
317        AggFunc::Avg => {
318            let mut total = 0.0f64;
319            let mut count = 0usize;
320            for r in rows {
321                let v = resolve_agg_value(arg, arg_expr, r);
322                match v {
323                    Value::Int(n) => { total += n as f64; count += 1; }
324                    Value::Float(f) => { total += f; count += 1; }
325                    _ => {}
326                }
327            }
328            if count > 0 { Value::Float(total / count as f64) } else { Value::Null }
329        }
330        AggFunc::Min => {
331            let mut min_val: Option<Value> = None;
332            for r in rows {
333                let v = resolve_agg_value(arg, arg_expr, r);
334                if v.is_null() { continue; }
335                min_val = Some(match min_val {
336                    None => v,
337                    Some(ref current) => {
338                        if v.partial_cmp(current) == Some(std::cmp::Ordering::Less) {
339                            v
340                        } else {
341                            current.clone()
342                        }
343                    }
344                });
345            }
346            min_val.unwrap_or(Value::Null)
347        }
348        AggFunc::Max => {
349            let mut max_val: Option<Value> = None;
350            for r in rows {
351                let v = resolve_agg_value(arg, arg_expr, r);
352                if v.is_null() { continue; }
353                max_val = Some(match max_val {
354                    None => v,
355                    Some(ref current) => {
356                        if v.partial_cmp(current) == Some(std::cmp::Ordering::Greater) {
357                            v
358                        } else {
359                            current.clone()
360                        }
361                    }
362                });
363            }
364            max_val.unwrap_or(Value::Null)
365        }
366    }
367}
368
369fn evaluate_with_fts(clause: &WhereClause, row: &Row, fts: &FtsResults) -> bool {
370    match clause {
371        WhereClause::BoolOp(bop) => {
372            let left = evaluate_with_fts(&bop.left, row, fts);
373            match bop.op.as_str() {
374                "AND" => left && evaluate_with_fts(&bop.right, row, fts),
375                "OR" => left || evaluate_with_fts(&bop.right, row, fts),
376                _ => false,
377            }
378        }
379        WhereClause::Comparison(cmp) => {
380            // Check if we have FTS results for this comparison
381            if cmp.op == "LIKE" || cmp.op == "NOT LIKE" {
382                if let Some(SqlValue::String(pattern)) = &cmp.value {
383                    let key = (cmp.column.clone(), pattern.clone());
384                    if let Some(matching_paths) = fts.get(&key) {
385                        let row_path = row.get("path").and_then(|v| v.as_str()).unwrap_or("");
386                        let matched = matching_paths.contains(row_path);
387                        return if cmp.op == "LIKE" { matched } else { !matched };
388                    }
389                }
390            }
391            evaluate_comparison(cmp, row)
392        }
393    }
394}
395
396pub fn execute_join_query(
397    query: &SelectQuery,
398    tables: &HashMap<String, (Schema, Vec<Row>)>,
399) -> crate::errors::Result<(Vec<Row>, Vec<String>)> {
400    if query.joins.is_empty() {
401        return Err(MdqlError::QueryExecution("No JOIN clause in query".into()));
402    }
403
404    let left_name = &query.table;
405    let left_alias = query.table_alias.as_deref().unwrap_or(left_name);
406
407    // Build alias→table mapping for all tables
408    let mut aliases: HashMap<String, String> = HashMap::new();
409    aliases.insert(left_name.clone(), left_name.clone());
410    if let Some(ref a) = query.table_alias {
411        aliases.insert(a.clone(), left_name.clone());
412    }
413    for join in &query.joins {
414        aliases.insert(join.table.clone(), join.table.clone());
415        if let Some(ref a) = join.alias {
416            aliases.insert(a.clone(), join.table.clone());
417        }
418    }
419
420    // Start with the left table rows, prefixed with alias
421    let (_left_schema, left_rows) = tables.get(left_name.as_str()).ok_or_else(|| {
422        MdqlError::QueryExecution(format!("Unknown table '{}'", left_name))
423    })?;
424
425    let mut current_rows: Vec<Row> = left_rows
426        .iter()
427        .map(|r| {
428            let mut prefixed = Row::new();
429            for (k, v) in r {
430                prefixed.insert(format!("{}.{}", left_alias, k), v.clone());
431            }
432            prefixed
433        })
434        .collect();
435
436    // Process each JOIN sequentially
437    for join in &query.joins {
438        let right_name = &join.table;
439        let right_alias = join.alias.as_deref().unwrap_or(right_name);
440
441        let (_right_schema, right_rows) = tables.get(right_name.as_str()).ok_or_else(|| {
442            MdqlError::QueryExecution(format!("Unknown table '{}'", right_name))
443        })?;
444
445        // Resolve ON columns to determine which is left vs right
446        let (on_left_table, on_left_col) = resolve_dotted(&join.left_col, &aliases);
447        let (on_right_table, on_right_col) = resolve_dotted(&join.right_col, &aliases);
448
449        // Figure out which ON column refers to the new right table
450        let (left_key, right_key) = if on_right_table == *right_name {
451            // left_col is from the left side, right_col is from the right table
452            let left_alias_for_col = reverse_alias(&on_left_table, &aliases, query, &query.joins);
453            (format!("{}.{}", left_alias_for_col, on_left_col), on_right_col)
454        } else {
455            // right_col is from the left side, left_col is from the right table
456            let right_alias_for_col = reverse_alias(&on_right_table, &aliases, query, &query.joins);
457            (format!("{}.{}", right_alias_for_col, on_right_col), on_left_col)
458        };
459
460        // Build index on right table
461        let mut right_index: HashMap<String, Vec<&Row>> = HashMap::new();
462        for r in right_rows {
463            if let Some(key) = r.get(&right_key) {
464                let key_str = key.to_display_string();
465                right_index.entry(key_str).or_default().push(r);
466            }
467        }
468
469        // Join current rows with right table
470        let mut next_rows: Vec<Row> = Vec::new();
471        for lr in &current_rows {
472            if let Some(key) = lr.get(&left_key) {
473                let key_str = key.to_display_string();
474                if let Some(matching) = right_index.get(&key_str) {
475                    for rr in matching {
476                        let mut merged = lr.clone();
477                        for (k, v) in *rr {
478                            merged.insert(format!("{}.{}", right_alias, k), v.clone());
479                        }
480                        next_rows.push(merged);
481                    }
482                }
483            }
484        }
485        current_rows = next_rows;
486    }
487
488    let (mut result, columns) = execute(query, &current_rows, None)?;
489
490    // Add unprefixed aliases for non-colliding column names in the output.
491    // e.g., if result has s.title and b.sharpe (no other "title" or "sharpe"),
492    // add "title" and "sharpe" as shorthand keys.
493    if !result.is_empty() {
494        let mut base_counts: HashMap<String, usize> = HashMap::new();
495        for key in &columns {
496            if let Some((_prefix, base)) = key.split_once('.') {
497                *base_counts.entry(base.to_string()).or_default() += 1;
498            }
499        }
500        let unique_bases: Vec<String> = base_counts
501            .into_iter()
502            .filter(|(_, count)| *count == 1)
503            .map(|(base, _)| base)
504            .collect();
505
506        if !unique_bases.is_empty() {
507            let unique_set: std::collections::HashSet<&str> =
508                unique_bases.iter().map(|s| s.as_str()).collect();
509            for row in &mut result {
510                let additions: Vec<(String, Value)> = row
511                    .iter()
512                    .filter_map(|(k, v)| {
513                        k.split_once('.').and_then(|(_, base)| {
514                            if unique_set.contains(base) {
515                                Some((base.to_string(), v.clone()))
516                            } else {
517                                None
518                            }
519                        })
520                    })
521                    .collect();
522                for (k, v) in additions {
523                    row.insert(k, v);
524                }
525            }
526        }
527    }
528
529    Ok((result, columns))
530}
531
532/// Given a table name, find the alias used for it.
533fn reverse_alias(
534    table_name: &str,
535    aliases: &HashMap<String, String>,
536    query: &SelectQuery,
537    joins: &[JoinClause],
538) -> String {
539    // Check if the FROM table matches
540    if query.table == table_name {
541        return query.table_alias.as_deref().unwrap_or(&query.table).to_string();
542    }
543    // Check join tables
544    for j in joins {
545        if j.table == table_name {
546            return j.alias.as_deref().unwrap_or(&j.table).to_string();
547        }
548    }
549    // Fall back: check if table_name is itself an alias
550    if aliases.contains_key(table_name) {
551        return table_name.to_string();
552    }
553    table_name.to_string()
554}
555
556fn resolve_dotted(col: &str, aliases: &HashMap<String, String>) -> (String, String) {
557    if let Some((alias, column)) = col.split_once('.') {
558        let table = aliases.get(alias).cloned().unwrap_or_else(|| alias.to_string());
559        (table, column.to_string())
560    } else {
561        (String::new(), col.to_string())
562    }
563}
564
565fn execute(
566    query: &SelectQuery,
567    rows: &[Row],
568    index: Option<&crate::index::TableIndex>,
569) -> crate::errors::Result<(Vec<Row>, Vec<String>)> {
570    let empty_fts = HashMap::new();
571    execute_with_fts(query, rows, index, &empty_fts)
572}
573
574pub fn evaluate(clause: &WhereClause, row: &Row) -> bool {
575    match clause {
576        WhereClause::BoolOp(bop) => {
577            let left = evaluate(&bop.left, row);
578            match bop.op.as_str() {
579                "AND" => left && evaluate(&bop.right, row),
580                "OR" => left || evaluate(&bop.right, row),
581                _ => false,
582            }
583        }
584        WhereClause::Comparison(cmp) => evaluate_comparison(cmp, row),
585    }
586}
587
588/// Evaluate an Expr against a row, returning a Value.
589pub fn evaluate_expr(expr: &Expr, row: &Row) -> Value {
590    match expr {
591        Expr::Literal(SqlValue::Int(n)) => Value::Int(*n),
592        Expr::Literal(SqlValue::Float(f)) => Value::Float(*f),
593        Expr::Literal(SqlValue::String(s)) => Value::String(s.clone()),
594        Expr::Literal(SqlValue::Null) => Value::Null,
595        Expr::Literal(SqlValue::List(_)) => Value::Null,
596        Expr::Column(name) => {
597            if let Some(val) = row.get(name) {
598                return val.clone();
599            }
600            if let Some((dict_col, dict_key)) = name.split_once('.') {
601                if let Some(Value::Dict(map)) = row.get(dict_col) {
602                    return map.get(dict_key).cloned().unwrap_or(Value::Null);
603                }
604            }
605            Value::Null
606        }
607        Expr::UnaryMinus(inner) => {
608            match evaluate_expr(inner, row) {
609                Value::Int(n) => Value::Int(-n),
610                Value::Float(f) => Value::Float(-f),
611                Value::Null => Value::Null,
612                _ => Value::Null, // non-numeric → NULL
613            }
614        }
615        Expr::BinaryOp { left, op, right } => {
616            let lv = evaluate_expr(left, row);
617            let rv = evaluate_expr(right, row);
618
619            // NULL propagation: any NULL operand → NULL
620            if lv.is_null() || rv.is_null() {
621                return Value::Null;
622            }
623
624            // Extract numeric values with int→float coercion
625            match (&lv, &rv) {
626                (Value::Int(a), Value::Int(b)) => {
627                    match op {
628                        ArithOp::Add => Value::Int(a.wrapping_add(*b)),
629                        ArithOp::Sub => Value::Int(a.wrapping_sub(*b)),
630                        ArithOp::Mul => Value::Int(a.wrapping_mul(*b)),
631                        ArithOp::Div => {
632                            if *b == 0 { Value::Null } else { Value::Int(a / b) }
633                        }
634                        ArithOp::Mod => {
635                            if *b == 0 { Value::Null } else { Value::Int(a % b) }
636                        }
637                    }
638                }
639                _ => {
640                    // Coerce to float
641                    let a = match &lv {
642                        Value::Int(n) => *n as f64,
643                        Value::Float(f) => *f,
644                        _ => return Value::Null,
645                    };
646                    let b = match &rv {
647                        Value::Int(n) => *n as f64,
648                        Value::Float(f) => *f,
649                        _ => return Value::Null,
650                    };
651                    match op {
652                        ArithOp::Add => Value::Float(a + b),
653                        ArithOp::Sub => Value::Float(a - b),
654                        ArithOp::Mul => Value::Float(a * b),
655                        ArithOp::Div => {
656                            if b == 0.0 { Value::Null } else { Value::Float(a / b) }
657                        }
658                        ArithOp::Mod => {
659                            if b == 0.0 { Value::Null } else { Value::Float(a % b) }
660                        }
661                    }
662                }
663            }
664        }
665        Expr::Case { whens, else_expr } => {
666            for (condition, result) in whens {
667                if evaluate(condition, row) {
668                    return evaluate_expr(result, row);
669                }
670            }
671            match else_expr {
672                Some(e) => evaluate_expr(e, row),
673                None => Value::Null,
674            }
675        }
676        Expr::CurrentDate => {
677            Value::Date(chrono::Local::now().naive_local().date())
678        }
679        Expr::CurrentTimestamp => {
680            Value::DateTime(chrono::Local::now().naive_local())
681        }
682        Expr::DateAdd { date, days } => {
683            let date_val = evaluate_expr(date, row);
684            let days_val = evaluate_expr(days, row);
685            let n = match &days_val {
686                Value::Int(n) => *n,
687                Value::Float(f) => *f as i64,
688                _ => return Value::Null,
689            };
690            let duration = chrono::Duration::days(n);
691            match date_val {
692                Value::Date(d) => {
693                    match d.checked_add_signed(duration) {
694                        Some(result) => Value::Date(result),
695                        None => Value::Null,
696                    }
697                }
698                Value::DateTime(dt) => {
699                    match dt.checked_add_signed(duration) {
700                        Some(result) => Value::DateTime(result),
701                        None => Value::Null,
702                    }
703                }
704                _ => Value::Null,
705            }
706        }
707        Expr::DateDiff { left, right } => {
708            let lv = evaluate_expr(left, row);
709            let rv = evaluate_expr(right, row);
710            let left_date = match &lv {
711                Value::Date(d) => d.and_hms_opt(0, 0, 0).unwrap(),
712                Value::DateTime(dt) => *dt,
713                _ => return Value::Null,
714            };
715            let right_date = match &rv {
716                Value::Date(d) => d.and_hms_opt(0, 0, 0).unwrap(),
717                Value::DateTime(dt) => *dt,
718                _ => return Value::Null,
719            };
720            Value::Int((left_date - right_date).num_days())
721        }
722    }
723}
724
725fn evaluate_comparison(cmp: &Comparison, row: &Row) -> bool {
726    // If we have expression-based comparison (new path), use it for standard ops
727    if let (Some(left_expr), Some(right_expr)) = (&cmp.left_expr, &cmp.right_expr) {
728        if ["=", "!=", "<", ">", "<=", ">="].contains(&cmp.op.as_str()) {
729            let left_val = evaluate_expr(left_expr, row);
730            let right_val = evaluate_expr(right_expr, row);
731
732            // NULL comparison: always false (except IS NULL handled below)
733            if left_val.is_null() || right_val.is_null() {
734                return false;
735            }
736
737            // Coerce for comparison: if types differ, try int→float
738            let ord = compare_model_values(&left_val, &right_val);
739
740            return match cmp.op.as_str() {
741                "=" => ord == Some(Ordering::Equal),
742                "!=" => ord != Some(Ordering::Equal),
743                "<" => ord == Some(Ordering::Less),
744                ">" => ord == Some(Ordering::Greater),
745                "<=" => matches!(ord, Some(Ordering::Less | Ordering::Equal)),
746                ">=" => matches!(ord, Some(Ordering::Greater | Ordering::Equal)),
747                _ => false,
748            };
749        }
750    }
751
752    // Fall back to legacy column-based comparison for IS NULL, IN, LIKE, etc.
753    let actual = row.get(&cmp.column);
754
755    if cmp.op == "IS NULL" {
756        return actual.map_or(true, |v| v.is_null());
757    }
758    if cmp.op == "IS NOT NULL" {
759        return actual.map_or(false, |v| !v.is_null());
760    }
761
762    let actual = match actual {
763        Some(v) if !v.is_null() => v,
764        _ => return false,
765    };
766
767    let expected = match &cmp.value {
768        Some(v) => v,
769        None => return false,
770    };
771
772    match cmp.op.as_str() {
773        "=" => eq_match(actual, expected),
774        "!=" => !eq_match(actual, expected),
775        "<" => compare_values(actual, expected) == Some(Ordering::Less),
776        ">" => compare_values(actual, expected) == Some(Ordering::Greater),
777        "<=" => matches!(compare_values(actual, expected), Some(Ordering::Less | Ordering::Equal)),
778        ">=" => matches!(compare_values(actual, expected), Some(Ordering::Greater | Ordering::Equal)),
779        "LIKE" => like_match(actual, expected),
780        "NOT LIKE" => !like_match(actual, expected),
781        "IN" => {
782            if let SqlValue::List(items) = expected {
783                items.iter().any(|v| eq_match(actual, v))
784            } else {
785                eq_match(actual, expected)
786            }
787        }
788        _ => false,
789    }
790}
791
792/// Compare two model::Value instances, with int↔float coercion.
793fn compare_model_values(a: &Value, b: &Value) -> Option<Ordering> {
794    match (a, b) {
795        (Value::Int(x), Value::Float(y)) => (*x as f64).partial_cmp(y),
796        (Value::Float(x), Value::Int(y)) => x.partial_cmp(&(*y as f64)),
797        _ => a.partial_cmp(b),
798    }
799}
800
801fn coerce_sql_to_value(sql_val: &SqlValue, target: &Value) -> Value {
802    match sql_val {
803        SqlValue::Null => Value::Null,
804        SqlValue::String(s) => {
805            match target {
806                Value::Int(_) => s.parse::<i64>().map(Value::Int).unwrap_or(Value::String(s.clone())),
807                Value::Float(_) => s.parse::<f64>().map(Value::Float).unwrap_or(Value::String(s.clone())),
808                Value::Date(_) => {
809                    chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d")
810                        .map(Value::Date)
811                        .unwrap_or(Value::String(s.clone()))
812                }
813                Value::DateTime(_) => {
814                    chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S")
815                        .or_else(|_| chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f"))
816                        .map(Value::DateTime)
817                        .unwrap_or(Value::String(s.clone()))
818                }
819                _ => Value::String(s.clone()),
820            }
821        }
822        SqlValue::Int(n) => {
823            match target {
824                Value::Float(_) => Value::Float(*n as f64),
825                _ => Value::Int(*n),
826            }
827        }
828        SqlValue::Float(f) => Value::Float(*f),
829        SqlValue::List(_) => Value::Null, // Lists handled separately
830    }
831}
832
833fn eq_match(actual: &Value, expected: &SqlValue) -> bool {
834    // Special handling for lists (e.g., categories)
835    if let Value::List(items) = actual {
836        if let SqlValue::String(s) = expected {
837            return items.contains(s);
838        }
839    }
840
841    let coerced = coerce_sql_to_value(expected, actual);
842    actual == &coerced
843}
844
845fn like_match(actual: &Value, pattern: &SqlValue) -> bool {
846    let pattern_str = match pattern {
847        SqlValue::String(s) => s,
848        _ => return false,
849    };
850
851    // Convert SQL LIKE to regex
852    let mut regex_str = String::from("(?is)^");
853    for ch in pattern_str.chars() {
854        match ch {
855            '%' => regex_str.push_str(".*"),
856            '_' => regex_str.push('.'),
857            c => {
858                if regex::escape(&c.to_string()) != c.to_string() {
859                    regex_str.push_str(&regex::escape(&c.to_string()));
860                } else {
861                    regex_str.push(c);
862                }
863            }
864        }
865    }
866    regex_str.push('$');
867
868    let re = match Regex::new(&regex_str) {
869        Ok(r) => r,
870        Err(_) => return false,
871    };
872
873    match actual {
874        Value::List(items) => items.iter().any(|item| re.is_match(item)),
875        _ => re.is_match(&actual.to_display_string()),
876    }
877}
878
879fn compare_values(actual: &Value, expected: &SqlValue) -> Option<Ordering> {
880    let coerced = coerce_sql_to_value(expected, actual);
881    actual.partial_cmp(&coerced).map(|o| o)
882}
883
884/// Convert a SqlValue to a Value for index lookups (without a target type for coercion).
885fn sql_value_to_index_value(sv: &SqlValue) -> Value {
886    match sv {
887        SqlValue::String(s) => {
888            // Try datetime first (more specific)
889            if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S") {
890                return Value::DateTime(dt);
891            }
892            if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f") {
893                return Value::DateTime(dt);
894            }
895            // Try date
896            if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
897                return Value::Date(d);
898            }
899            Value::String(s.clone())
900        }
901        SqlValue::Int(n) => Value::Int(*n),
902        SqlValue::Float(f) => Value::Float(*f),
903        SqlValue::Null => Value::Null,
904        SqlValue::List(_) => Value::Null,
905    }
906}
907
908/// Try to use B-tree indexes to narrow the candidate row set.
909/// Returns Some(paths) if the entire WHERE clause could be resolved via index,
910/// or None if a full scan is needed.
911fn try_index_filter(
912    clause: &WhereClause,
913    index: &crate::index::TableIndex,
914) -> Option<std::collections::HashSet<String>> {
915    match clause {
916        WhereClause::Comparison(cmp) => {
917            if !index.has_index(&cmp.column) {
918                return None;
919            }
920            match cmp.op.as_str() {
921                "=" => {
922                    let val = sql_value_to_index_value(cmp.value.as_ref()?);
923                    let paths = index.lookup_eq(&cmp.column, &val);
924                    Some(paths.into_iter().map(|s| s.to_string()).collect())
925                }
926                "<" => {
927                    let val = sql_value_to_index_value(cmp.value.as_ref()?);
928                    // exclusive upper bound: use range with max < val
929                    // lookup_range is inclusive, so we get all <= val then remove exact matches
930                    let range_paths = index.lookup_range(&cmp.column, None, Some(&val));
931                    let eq_paths: std::collections::HashSet<&str> = index.lookup_eq(&cmp.column, &val).into_iter().collect();
932                    Some(range_paths.into_iter().filter(|p| !eq_paths.contains(p)).map(|s| s.to_string()).collect())
933                }
934                ">" => {
935                    let val = sql_value_to_index_value(cmp.value.as_ref()?);
936                    let range_paths = index.lookup_range(&cmp.column, Some(&val), None);
937                    let eq_paths: std::collections::HashSet<&str> = index.lookup_eq(&cmp.column, &val).into_iter().collect();
938                    Some(range_paths.into_iter().filter(|p| !eq_paths.contains(p)).map(|s| s.to_string()).collect())
939                }
940                "<=" => {
941                    let val = sql_value_to_index_value(cmp.value.as_ref()?);
942                    let paths = index.lookup_range(&cmp.column, None, Some(&val));
943                    Some(paths.into_iter().map(|s| s.to_string()).collect())
944                }
945                ">=" => {
946                    let val = sql_value_to_index_value(cmp.value.as_ref()?);
947                    let paths = index.lookup_range(&cmp.column, Some(&val), None);
948                    Some(paths.into_iter().map(|s| s.to_string()).collect())
949                }
950                "IN" => {
951                    if let Some(SqlValue::List(items)) = &cmp.value {
952                        let vals: Vec<Value> = items.iter().map(sql_value_to_index_value).collect();
953                        let paths = index.lookup_in(&cmp.column, &vals);
954                        Some(paths.into_iter().map(|s| s.to_string()).collect())
955                    } else {
956                        None
957                    }
958                }
959                _ => None, // LIKE, IS NULL, etc. can't use index
960            }
961        }
962        WhereClause::BoolOp(bop) => {
963            let left = try_index_filter(&bop.left, index);
964            let right = try_index_filter(&bop.right, index);
965            match bop.op.as_str() {
966                "AND" => {
967                    match (left, right) {
968                        (Some(l), Some(r)) => Some(l.intersection(&r).cloned().collect()),
969                        (Some(l), None) => Some(l), // narrow with left, scan-verify right
970                        (None, Some(r)) => Some(r),
971                        (None, None) => None,
972                    }
973                }
974                "OR" => {
975                    match (left, right) {
976                        (Some(l), Some(r)) => Some(l.union(&r).cloned().collect()),
977                        _ => None, // Can't use index if either side needs full scan
978                    }
979                }
980                _ => None,
981            }
982        }
983    }
984}
985
986/// If an ORDER BY column matches a SELECT alias, replace its expr with the
987/// aliased expression so sorting uses the computed value.
988fn resolve_order_aliases(specs: &[OrderSpec], columns: &ColumnList) -> Vec<OrderSpec> {
989    let named = match columns {
990        ColumnList::Named(exprs) => exprs,
991        _ => return specs.to_vec(),
992    };
993
994    // Build alias → expr map
995    let alias_map: HashMap<String, &Expr> = named
996        .iter()
997        .filter_map(|se| match se {
998            SelectExpr::Expr { expr, alias: Some(a) } => Some((a.clone(), expr)),
999            _ => None,
1000        })
1001        .collect();
1002
1003    specs
1004        .iter()
1005        .map(|spec| {
1006            // If the ORDER BY column name matches a SELECT alias, use that expression
1007            if let Some(expr) = alias_map.get(&spec.column) {
1008                OrderSpec {
1009                    column: spec.column.clone(),
1010                    expr: Some((*expr).clone()),
1011                    descending: spec.descending,
1012                }
1013            } else {
1014                spec.clone()
1015            }
1016        })
1017        .collect()
1018}
1019
1020fn sort_rows(rows: &mut Vec<Row>, specs: &[OrderSpec]) {
1021    rows.sort_by(|a, b| {
1022        for spec in specs {
1023            let (va, vb) = if let Some(ref expr) = spec.expr {
1024                (evaluate_expr(expr, a), evaluate_expr(expr, b))
1025            } else {
1026                (
1027                    a.get(&spec.column).cloned().unwrap_or(Value::Null),
1028                    b.get(&spec.column).cloned().unwrap_or(Value::Null),
1029                )
1030            };
1031
1032            // NULLs sort last
1033            let ordering = match (&va, &vb) {
1034                (Value::Null, Value::Null) => Ordering::Equal,
1035                (Value::Null, _) => Ordering::Greater,
1036                (_, Value::Null) => Ordering::Less,
1037                (a_val, b_val) => {
1038                    compare_model_values(a_val, b_val).unwrap_or(Ordering::Equal)
1039                }
1040            };
1041
1042            let ordering = if spec.descending {
1043                ordering.reverse()
1044            } else {
1045                ordering
1046            };
1047
1048            if ordering != Ordering::Equal {
1049                return ordering;
1050            }
1051        }
1052        Ordering::Equal
1053    });
1054}
1055
1056/// Convert a SqlValue to our model Value (for use in insert/update).
1057pub fn sql_value_to_value(sql_val: &SqlValue) -> Value {
1058    match sql_val {
1059        SqlValue::Null => Value::Null,
1060        SqlValue::String(s) => Value::String(s.clone()),
1061        SqlValue::Int(n) => Value::Int(*n),
1062        SqlValue::Float(f) => Value::Float(*f),
1063        SqlValue::List(items) => {
1064            let strings: Vec<String> = items
1065                .iter()
1066                .filter_map(|v| match v {
1067                    SqlValue::String(s) => Some(s.clone()),
1068                    _ => None,
1069                })
1070                .collect();
1071            Value::List(strings)
1072        }
1073    }
1074}
1075
1076#[cfg(test)]
1077mod tests {
1078    use super::*;
1079
1080    fn make_rows() -> Vec<Row> {
1081        vec![
1082            Row::from([
1083                ("path".into(), Value::String("a.md".into())),
1084                ("title".into(), Value::String("Alpha".into())),
1085                ("count".into(), Value::Int(10)),
1086            ]),
1087            Row::from([
1088                ("path".into(), Value::String("b.md".into())),
1089                ("title".into(), Value::String("Beta".into())),
1090                ("count".into(), Value::Int(5)),
1091            ]),
1092            Row::from([
1093                ("path".into(), Value::String("c.md".into())),
1094                ("title".into(), Value::String("Gamma".into())),
1095                ("count".into(), Value::Int(20)),
1096            ]),
1097        ]
1098    }
1099
1100    #[test]
1101    fn test_select_all() {
1102        let q = SelectQuery {
1103            columns: ColumnList::All,
1104            table: "test".into(),
1105            table_alias: None,
1106            joins: vec![],
1107            where_clause: None,
1108            group_by: None,
1109            having: None,
1110            order_by: None,
1111            limit: None,
1112        };
1113        let (rows, _cols) = execute(&q, &make_rows(), None).unwrap();
1114        assert_eq!(rows.len(), 3);
1115    }
1116
1117    #[test]
1118    fn test_where_gt() {
1119        let q = SelectQuery {
1120            columns: ColumnList::All,
1121            table: "test".into(),
1122            table_alias: None,
1123            joins: vec![],
1124            where_clause: Some(WhereClause::Comparison(Comparison {
1125                column: "count".into(),
1126                op: ">".into(),
1127                value: Some(SqlValue::Int(5)),
1128                left_expr: Some(Expr::Column("count".into())),
1129                right_expr: Some(Expr::Literal(SqlValue::Int(5))),
1130            })),
1131            group_by: None,
1132            having: None,
1133            order_by: None,
1134            limit: None,
1135        };
1136        let (rows, _) = execute(&q, &make_rows(), None).unwrap();
1137        assert_eq!(rows.len(), 2);
1138    }
1139
1140    #[test]
1141    fn test_order_by_desc() {
1142        let q = SelectQuery {
1143            columns: ColumnList::All,
1144            table: "test".into(),
1145            table_alias: None,
1146            joins: vec![],
1147            where_clause: None,
1148            group_by: None,
1149            having: None,
1150            order_by: Some(vec![OrderSpec {
1151                column: "count".into(),
1152                expr: Some(Expr::Column("count".into())),
1153                descending: true,
1154            }]),
1155            limit: None,
1156        };
1157        let (rows, _) = execute(&q, &make_rows(), None).unwrap();
1158        assert_eq!(rows[0]["count"], Value::Int(20));
1159        assert_eq!(rows[2]["count"], Value::Int(5));
1160    }
1161
1162    #[test]
1163    fn test_limit() {
1164        let q = SelectQuery {
1165            columns: ColumnList::All,
1166            table: "test".into(),
1167            table_alias: None,
1168            joins: vec![],
1169            where_clause: None,
1170            group_by: None,
1171            having: None,
1172            order_by: None,
1173            limit: Some(2),
1174        };
1175        let (rows, _) = execute(&q, &make_rows(), None).unwrap();
1176        assert_eq!(rows.len(), 2);
1177    }
1178
1179    #[test]
1180    fn test_like() {
1181        let q = SelectQuery {
1182            columns: ColumnList::All,
1183            table: "test".into(),
1184            table_alias: None,
1185            joins: vec![],
1186            where_clause: Some(WhereClause::Comparison(Comparison {
1187                column: "title".into(),
1188                op: "LIKE".into(),
1189                value: Some(SqlValue::String("%lph%".into())),
1190                left_expr: Some(Expr::Column("title".into())),
1191                right_expr: None,
1192            })),
1193            group_by: None,
1194            having: None,
1195            order_by: None,
1196            limit: None,
1197        };
1198        let (rows, _) = execute(&q, &make_rows(), None).unwrap();
1199        assert_eq!(rows.len(), 1);
1200        assert_eq!(rows[0]["title"], Value::String("Alpha".into()));
1201    }
1202
1203    #[test]
1204    fn test_is_null() {
1205        let mut rows = make_rows();
1206        rows[1].insert("optional".into(), Value::Null);
1207
1208        let q = SelectQuery {
1209            columns: ColumnList::All,
1210            table: "test".into(),
1211            table_alias: None,
1212            joins: vec![],
1213            where_clause: Some(WhereClause::Comparison(Comparison {
1214                column: "optional".into(),
1215                op: "IS NULL".into(),
1216                value: None,
1217                left_expr: Some(Expr::Column("optional".into())),
1218                right_expr: None,
1219            })),
1220            group_by: None,
1221            having: None,
1222            order_by: None,
1223            limit: None,
1224        };
1225        let (result, _) = execute(&q, &rows, None).unwrap();
1226        // All rows where optional is NULL or missing
1227        assert_eq!(result.len(), 3);
1228    }
1229
1230    // ── Expression evaluation tests ─────────────────────────��─────
1231
1232    #[test]
1233    fn test_evaluate_expr_literal() {
1234        let row = Row::new();
1235        assert_eq!(evaluate_expr(&Expr::Literal(SqlValue::Int(42)), &row), Value::Int(42));
1236        assert_eq!(evaluate_expr(&Expr::Literal(SqlValue::Float(3.14)), &row), Value::Float(3.14));
1237        assert_eq!(evaluate_expr(&Expr::Literal(SqlValue::Null), &row), Value::Null);
1238    }
1239
1240    #[test]
1241    fn test_evaluate_expr_column() {
1242        let row = Row::from([("x".into(), Value::Int(10))]);
1243        assert_eq!(evaluate_expr(&Expr::Column("x".into()), &row), Value::Int(10));
1244        assert_eq!(evaluate_expr(&Expr::Column("missing".into()), &row), Value::Null);
1245    }
1246
1247    #[test]
1248    fn test_evaluate_expr_int_arithmetic() {
1249        let row = Row::from([("a".into(), Value::Int(10)), ("b".into(), Value::Int(3))]);
1250        let add = Expr::BinaryOp {
1251            left: Box::new(Expr::Column("a".into())),
1252            op: ArithOp::Add,
1253            right: Box::new(Expr::Column("b".into())),
1254        };
1255        assert_eq!(evaluate_expr(&add, &row), Value::Int(13));
1256
1257        let sub = Expr::BinaryOp {
1258            left: Box::new(Expr::Column("a".into())),
1259            op: ArithOp::Sub,
1260            right: Box::new(Expr::Column("b".into())),
1261        };
1262        assert_eq!(evaluate_expr(&sub, &row), Value::Int(7));
1263
1264        let mul = Expr::BinaryOp {
1265            left: Box::new(Expr::Column("a".into())),
1266            op: ArithOp::Mul,
1267            right: Box::new(Expr::Column("b".into())),
1268        };
1269        assert_eq!(evaluate_expr(&mul, &row), Value::Int(30));
1270
1271        let div = Expr::BinaryOp {
1272            left: Box::new(Expr::Column("a".into())),
1273            op: ArithOp::Div,
1274            right: Box::new(Expr::Column("b".into())),
1275        };
1276        assert_eq!(evaluate_expr(&div, &row), Value::Int(3)); // integer division
1277
1278        let modulo = Expr::BinaryOp {
1279            left: Box::new(Expr::Column("a".into())),
1280            op: ArithOp::Mod,
1281            right: Box::new(Expr::Column("b".into())),
1282        };
1283        assert_eq!(evaluate_expr(&modulo, &row), Value::Int(1));
1284    }
1285
1286    #[test]
1287    fn test_evaluate_expr_float_coercion() {
1288        let row = Row::from([("a".into(), Value::Int(10)), ("b".into(), Value::Float(3.0))]);
1289        let add = Expr::BinaryOp {
1290            left: Box::new(Expr::Column("a".into())),
1291            op: ArithOp::Add,
1292            right: Box::new(Expr::Column("b".into())),
1293        };
1294        assert_eq!(evaluate_expr(&add, &row), Value::Float(13.0));
1295    }
1296
1297    #[test]
1298    fn test_evaluate_expr_null_propagation() {
1299        let row = Row::from([("a".into(), Value::Int(10))]);
1300        let add = Expr::BinaryOp {
1301            left: Box::new(Expr::Column("a".into())),
1302            op: ArithOp::Add,
1303            right: Box::new(Expr::Column("missing".into())),
1304        };
1305        assert_eq!(evaluate_expr(&add, &row), Value::Null);
1306    }
1307
1308    #[test]
1309    fn test_evaluate_expr_div_by_zero() {
1310        let row = Row::from([("a".into(), Value::Int(10)), ("b".into(), Value::Int(0))]);
1311        let div = Expr::BinaryOp {
1312            left: Box::new(Expr::Column("a".into())),
1313            op: ArithOp::Div,
1314            right: Box::new(Expr::Column("b".into())),
1315        };
1316        assert_eq!(evaluate_expr(&div, &row), Value::Null);
1317    }
1318
1319    #[test]
1320    fn test_evaluate_expr_unary_minus() {
1321        let row = Row::from([("x".into(), Value::Int(5))]);
1322        let neg = Expr::UnaryMinus(Box::new(Expr::Column("x".into())));
1323        assert_eq!(evaluate_expr(&neg, &row), Value::Int(-5));
1324    }
1325
1326    #[test]
1327    fn test_select_with_expression() {
1328        // Integration test: SELECT count * 2 AS doubled FROM test
1329        let stmt = crate::query_parser::parse_query(
1330            "SELECT count * 2 AS doubled FROM test"
1331        ).unwrap();
1332        if let crate::query_parser::Statement::Select(q) = stmt {
1333            let (rows, cols) = execute(&q, &make_rows(), None).unwrap();
1334            assert_eq!(cols, vec!["doubled"]);
1335            assert_eq!(rows.len(), 3);
1336            // Rows are: count=10, count=5, count=20
1337            let values: Vec<Value> = rows.iter().map(|r| r["doubled"].clone()).collect();
1338            assert!(values.contains(&Value::Int(20)));
1339            assert!(values.contains(&Value::Int(10)));
1340            assert!(values.contains(&Value::Int(40)));
1341        } else {
1342            panic!("Expected Select");
1343        }
1344    }
1345
1346    #[test]
1347    fn test_where_with_expression() {
1348        // SELECT * FROM test WHERE count * 2 > 15
1349        let stmt = crate::query_parser::parse_query(
1350            "SELECT * FROM test WHERE count * 2 > 15"
1351        ).unwrap();
1352        if let crate::query_parser::Statement::Select(q) = stmt {
1353            let (rows, _) = execute(&q, &make_rows(), None).unwrap();
1354            // count=10 → 20 > 15 ✓, count=5 → 10 > 15 ✗, count=20 → 40 > 15 ✓
1355            assert_eq!(rows.len(), 2);
1356        } else {
1357            panic!("Expected Select");
1358        }
1359    }
1360
1361    #[test]
1362    fn test_order_by_expression() {
1363        // SELECT * FROM test ORDER BY count * -1 ASC (effectively DESC by count)
1364        let stmt = crate::query_parser::parse_query(
1365            "SELECT title, count FROM test ORDER BY count * -1 ASC"
1366        ).unwrap();
1367        if let crate::query_parser::Statement::Select(q) = stmt {
1368            let (rows, _) = execute(&q, &make_rows(), None).unwrap();
1369            // count: 20 → -20, 10 → -10, 5 → -5, ASC means -20, -10, -5
1370            assert_eq!(rows[0]["count"], Value::Int(20));
1371            assert_eq!(rows[1]["count"], Value::Int(10));
1372            assert_eq!(rows[2]["count"], Value::Int(5));
1373        } else {
1374            panic!("Expected Select");
1375        }
1376    }
1377
1378    // ── CASE WHEN evaluation tests ────────────────────────────────
1379
1380    #[test]
1381    fn test_case_when_eval_basic() {
1382        let row = Row::from([("status".into(), Value::String("ACTIVE".into()))]);
1383        let expr = Expr::Case {
1384            whens: vec![(
1385                WhereClause::Comparison(Comparison {
1386                    column: "status".into(),
1387                    op: "=".into(),
1388                    value: Some(SqlValue::String("ACTIVE".into())),
1389                    left_expr: Some(Expr::Column("status".into())),
1390                    right_expr: Some(Expr::Literal(SqlValue::String("ACTIVE".into()))),
1391                }),
1392                Box::new(Expr::Literal(SqlValue::Int(1))),
1393            )],
1394            else_expr: Some(Box::new(Expr::Literal(SqlValue::Int(0)))),
1395        };
1396        assert_eq!(evaluate_expr(&expr, &row), Value::Int(1));
1397    }
1398
1399    #[test]
1400    fn test_case_when_eval_else() {
1401        let row = Row::from([("status".into(), Value::String("KILLED".into()))]);
1402        let expr = Expr::Case {
1403            whens: vec![(
1404                WhereClause::Comparison(Comparison {
1405                    column: "status".into(),
1406                    op: "=".into(),
1407                    value: Some(SqlValue::String("ACTIVE".into())),
1408                    left_expr: Some(Expr::Column("status".into())),
1409                    right_expr: Some(Expr::Literal(SqlValue::String("ACTIVE".into()))),
1410                }),
1411                Box::new(Expr::Literal(SqlValue::Int(1))),
1412            )],
1413            else_expr: Some(Box::new(Expr::Literal(SqlValue::Int(0)))),
1414        };
1415        assert_eq!(evaluate_expr(&expr, &row), Value::Int(0));
1416    }
1417
1418    #[test]
1419    fn test_case_when_eval_no_else_null() {
1420        let row = Row::from([("x".into(), Value::Int(99))]);
1421        let expr = Expr::Case {
1422            whens: vec![(
1423                WhereClause::Comparison(Comparison {
1424                    column: "x".into(),
1425                    op: "=".into(),
1426                    value: Some(SqlValue::Int(1)),
1427                    left_expr: Some(Expr::Column("x".into())),
1428                    right_expr: Some(Expr::Literal(SqlValue::Int(1))),
1429                }),
1430                Box::new(Expr::Literal(SqlValue::String("one".into()))),
1431            )],
1432            else_expr: None,
1433        };
1434        assert_eq!(evaluate_expr(&expr, &row), Value::Null);
1435    }
1436
1437    #[test]
1438    fn test_case_when_in_aggregate_query() {
1439        // SUM(CASE WHEN count > 5 THEN count ELSE 0 END)
1440        // Rows: count=10, count=5, count=20 → should sum 10 + 0 + 20 = 30
1441        let stmt = crate::query_parser::parse_query(
1442            "SELECT SUM(CASE WHEN count > 5 THEN count ELSE 0 END) AS total FROM test"
1443        ).unwrap();
1444        if let crate::query_parser::Statement::Select(q) = stmt {
1445            let (rows, cols) = execute(&q, &make_rows(), None).unwrap();
1446            assert_eq!(cols, vec!["total"]);
1447            assert_eq!(rows.len(), 1);
1448            assert_eq!(rows[0]["total"], Value::Float(30.0));
1449        } else {
1450            panic!("Expected Select");
1451        }
1452    }
1453
1454    #[test]
1455    fn test_case_when_with_unary_minus_in_aggregate() {
1456        // SUM(CASE WHEN title = 'Alpha' THEN count ELSE -count END)
1457        // Alpha: 10, Beta: -5, Gamma: -20 → 10 - 5 - 20 = -15
1458        let stmt = crate::query_parser::parse_query(
1459            "SELECT SUM(CASE WHEN title = 'Alpha' THEN count ELSE -count END) AS net FROM test"
1460        ).unwrap();
1461        if let crate::query_parser::Statement::Select(q) = stmt {
1462            let (rows, _) = execute(&q, &make_rows(), None).unwrap();
1463            assert_eq!(rows.len(), 1);
1464            assert_eq!(rows[0]["net"], Value::Float(-15.0));
1465        } else {
1466            panic!("Expected Select");
1467        }
1468    }
1469}