sql_cli/data/
query_engine.rs

1use anyhow::{anyhow, Result};
2use fxhash::FxHashSet;
3use std::cmp::min;
4use std::collections::HashMap;
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7use tracing::{debug, info};
8
9use crate::config::config::BehaviorConfig;
10use crate::config::global::get_date_notation;
11use crate::data::arithmetic_evaluator::ArithmeticEvaluator;
12use crate::data::data_view::DataView;
13use crate::data::datatable::{DataColumn, DataRow, DataTable, DataValue};
14use crate::data::evaluation_context::EvaluationContext;
15use crate::data::group_by_expressions::GroupByExpressions;
16use crate::data::hash_join::HashJoinExecutor;
17use crate::data::recursive_where_evaluator::RecursiveWhereEvaluator;
18use crate::data::row_expanders::RowExpanderRegistry;
19use crate::data::subquery_executor::SubqueryExecutor;
20use crate::data::temp_table_registry::TempTableRegistry;
21use crate::execution_plan::{ExecutionPlan, ExecutionPlanBuilder, StepType};
22use crate::sql::aggregates::{contains_aggregate, is_aggregate_compatible};
23use crate::sql::parser::ast::ColumnRef;
24use crate::sql::parser::ast::SetOperation;
25use crate::sql::parser::ast::TableSource;
26use crate::sql::recursive_parser::{
27    CTEType, OrderByItem, Parser, SelectItem, SelectStatement, SortDirection, SqlExpression,
28    TableFunction,
29};
30
31/// Execution context for tracking table aliases and scope during query execution
32#[derive(Debug, Clone)]
33pub struct ExecutionContext {
34    /// Map from alias to actual table/CTE name
35    /// Example: "t" -> "#tmp_trades", "a" -> "data"
36    alias_map: HashMap<String, String>,
37}
38
39impl ExecutionContext {
40    /// Create a new empty execution context
41    pub fn new() -> Self {
42        Self {
43            alias_map: HashMap::new(),
44        }
45    }
46
47    /// Register a table alias
48    pub fn register_alias(&mut self, alias: String, table_name: String) {
49        debug!("Registering alias: {} -> {}", alias, table_name);
50        self.alias_map.insert(alias, table_name);
51    }
52
53    /// Resolve an alias to its actual table name
54    /// Returns the alias itself if not found in the map
55    pub fn resolve_alias(&self, name: &str) -> String {
56        self.alias_map
57            .get(name)
58            .cloned()
59            .unwrap_or_else(|| name.to_string())
60    }
61
62    /// Check if a name is a registered alias
63    pub fn is_alias(&self, name: &str) -> bool {
64        self.alias_map.contains_key(name)
65    }
66
67    /// Get a copy of all registered aliases
68    pub fn get_aliases(&self) -> HashMap<String, String> {
69        self.alias_map.clone()
70    }
71
72    /// Resolve a column reference to its index in the table, handling aliases
73    ///
74    /// This is the unified column resolution function that should be used by all
75    /// SQL clauses (WHERE, SELECT, ORDER BY, GROUP BY) to ensure consistent
76    /// alias resolution behavior.
77    ///
78    /// Resolution strategy:
79    /// 1. If column_ref has a table_prefix (e.g., "t" in "t.amount"):
80    ///    a. Resolve the alias: t -> actual_table_name
81    ///    b. Try qualified lookup: "actual_table_name.amount"
82    ///    c. Fall back to unqualified: "amount"
83    /// 2. If column_ref has no prefix:
84    ///    a. Try simple column name lookup: "amount"
85    ///    b. Try as qualified name if it contains a dot: "table.column"
86    pub fn resolve_column_index(&self, table: &DataTable, column_ref: &ColumnRef) -> Result<usize> {
87        if let Some(table_prefix) = &column_ref.table_prefix {
88            // Qualified column reference: resolve the alias first
89            let actual_table = self.resolve_alias(table_prefix);
90
91            // Try qualified lookup: "actual_table.column"
92            let qualified_name = format!("{}.{}", actual_table, column_ref.name);
93            if let Some(idx) = table.find_column_by_qualified_name(&qualified_name) {
94                debug!(
95                    "Resolved {}.{} -> qualified column '{}' at index {}",
96                    table_prefix, column_ref.name, qualified_name, idx
97                );
98                return Ok(idx);
99            }
100
101            // Fall back to unqualified lookup
102            if let Some(idx) = table.get_column_index(&column_ref.name) {
103                debug!(
104                    "Resolved {}.{} -> unqualified column '{}' at index {}",
105                    table_prefix, column_ref.name, column_ref.name, idx
106                );
107                return Ok(idx);
108            }
109
110            // Not found with either qualified or unqualified name
111            Err(anyhow!(
112                "Column '{}' not found. Table '{}' may not support qualified column names",
113                qualified_name,
114                actual_table
115            ))
116        } else {
117            // Unqualified column reference
118            if let Some(idx) = table.get_column_index(&column_ref.name) {
119                debug!(
120                    "Resolved unqualified column '{}' at index {}",
121                    column_ref.name, idx
122                );
123                return Ok(idx);
124            }
125
126            // If the column name contains a dot, try it as a qualified name
127            if column_ref.name.contains('.') {
128                if let Some(idx) = table.find_column_by_qualified_name(&column_ref.name) {
129                    debug!(
130                        "Resolved '{}' as qualified column at index {}",
131                        column_ref.name, idx
132                    );
133                    return Ok(idx);
134                }
135            }
136
137            // Column not found - provide helpful error
138            let suggestion = self.find_similar_column(table, &column_ref.name);
139            match suggestion {
140                Some(similar) => Err(anyhow!(
141                    "Column '{}' not found. Did you mean '{}'?",
142                    column_ref.name,
143                    similar
144                )),
145                None => Err(anyhow!("Column '{}' not found", column_ref.name)),
146            }
147        }
148    }
149
150    /// Find a similar column name using edit distance (for better error messages)
151    fn find_similar_column(&self, table: &DataTable, name: &str) -> Option<String> {
152        let columns = table.column_names();
153        let mut best_match: Option<(String, usize)> = None;
154
155        for col in columns {
156            let distance = edit_distance(name, &col);
157            if distance <= 2 {
158                // Allow up to 2 character differences
159                match best_match {
160                    Some((_, best_dist)) if distance < best_dist => {
161                        best_match = Some((col.clone(), distance));
162                    }
163                    None => {
164                        best_match = Some((col.clone(), distance));
165                    }
166                    _ => {}
167                }
168            }
169        }
170
171        best_match.map(|(name, _)| name)
172    }
173}
174
175impl Default for ExecutionContext {
176    fn default() -> Self {
177        Self::new()
178    }
179}
180
181/// Calculate edit distance between two strings (Levenshtein distance)
182fn edit_distance(a: &str, b: &str) -> usize {
183    let len_a = a.chars().count();
184    let len_b = b.chars().count();
185
186    if len_a == 0 {
187        return len_b;
188    }
189    if len_b == 0 {
190        return len_a;
191    }
192
193    let mut matrix = vec![vec![0; len_b + 1]; len_a + 1];
194
195    for i in 0..=len_a {
196        matrix[i][0] = i;
197    }
198    for j in 0..=len_b {
199        matrix[0][j] = j;
200    }
201
202    let a_chars: Vec<char> = a.chars().collect();
203    let b_chars: Vec<char> = b.chars().collect();
204
205    for i in 1..=len_a {
206        for j in 1..=len_b {
207            let cost = if a_chars[i - 1] == b_chars[j - 1] {
208                0
209            } else {
210                1
211            };
212            matrix[i][j] = min(
213                min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1),
214                matrix[i - 1][j - 1] + cost,
215            );
216        }
217    }
218
219    matrix[len_a][len_b]
220}
221
222/// Query engine that executes SQL directly on `DataTable`
223#[derive(Clone)]
224pub struct QueryEngine {
225    case_insensitive: bool,
226    date_notation: String,
227    _behavior_config: Option<BehaviorConfig>,
228}
229
230impl Default for QueryEngine {
231    fn default() -> Self {
232        Self::new()
233    }
234}
235
236impl QueryEngine {
237    #[must_use]
238    pub fn new() -> Self {
239        Self {
240            case_insensitive: false,
241            date_notation: get_date_notation(),
242            _behavior_config: None,
243        }
244    }
245
246    #[must_use]
247    pub fn with_behavior_config(config: BehaviorConfig) -> Self {
248        let case_insensitive = config.case_insensitive_default;
249        // Use get_date_notation() to respect environment variable override
250        let date_notation = get_date_notation();
251        Self {
252            case_insensitive,
253            date_notation,
254            _behavior_config: Some(config),
255        }
256    }
257
258    #[must_use]
259    pub fn with_date_notation(_date_notation: String) -> Self {
260        Self {
261            case_insensitive: false,
262            date_notation: get_date_notation(), // Always use the global function
263            _behavior_config: None,
264        }
265    }
266
267    #[must_use]
268    pub fn with_case_insensitive(case_insensitive: bool) -> Self {
269        Self {
270            case_insensitive,
271            date_notation: get_date_notation(),
272            _behavior_config: None,
273        }
274    }
275
276    #[must_use]
277    pub fn with_case_insensitive_and_date_notation(
278        case_insensitive: bool,
279        _date_notation: String, // Keep parameter for compatibility but use get_date_notation()
280    ) -> Self {
281        Self {
282            case_insensitive,
283            date_notation: get_date_notation(), // Always use the global function
284            _behavior_config: None,
285        }
286    }
287
288    /// Find a column name similar to the given name using edit distance
289    fn find_similar_column(&self, table: &DataTable, name: &str) -> Option<String> {
290        let columns = table.column_names();
291        let mut best_match: Option<(String, usize)> = None;
292
293        for col in columns {
294            let distance = self.edit_distance(&col.to_lowercase(), &name.to_lowercase());
295            // Only suggest if distance is small (likely a typo)
296            // Allow up to 3 edits for longer names
297            let max_distance = if name.len() > 10 { 3 } else { 2 };
298            if distance <= max_distance {
299                match &best_match {
300                    None => best_match = Some((col, distance)),
301                    Some((_, best_dist)) if distance < *best_dist => {
302                        best_match = Some((col, distance));
303                    }
304                    _ => {}
305                }
306            }
307        }
308
309        best_match.map(|(name, _)| name)
310    }
311
312    /// Calculate Levenshtein edit distance between two strings
313    fn edit_distance(&self, s1: &str, s2: &str) -> usize {
314        let len1 = s1.len();
315        let len2 = s2.len();
316        let mut matrix = vec![vec![0; len2 + 1]; len1 + 1];
317
318        for i in 0..=len1 {
319            matrix[i][0] = i;
320        }
321        for j in 0..=len2 {
322            matrix[0][j] = j;
323        }
324
325        for (i, c1) in s1.chars().enumerate() {
326            for (j, c2) in s2.chars().enumerate() {
327                let cost = usize::from(c1 != c2);
328                matrix[i + 1][j + 1] = std::cmp::min(
329                    matrix[i][j + 1] + 1, // deletion
330                    std::cmp::min(
331                        matrix[i + 1][j] + 1, // insertion
332                        matrix[i][j] + cost,  // substitution
333                    ),
334                );
335            }
336        }
337
338        matrix[len1][len2]
339    }
340
341    /// Check if an expression contains UNNEST function call
342    fn contains_unnest(expr: &SqlExpression) -> bool {
343        match expr {
344            // Direct UNNEST variant
345            SqlExpression::Unnest { .. } => true,
346            SqlExpression::FunctionCall { name, args, .. } => {
347                if name.to_uppercase() == "UNNEST" {
348                    return true;
349                }
350                // Check recursively in function arguments
351                args.iter().any(Self::contains_unnest)
352            }
353            SqlExpression::BinaryOp { left, right, .. } => {
354                Self::contains_unnest(left) || Self::contains_unnest(right)
355            }
356            SqlExpression::Not { expr } => Self::contains_unnest(expr),
357            SqlExpression::CaseExpression {
358                when_branches,
359                else_branch,
360            } => {
361                when_branches.iter().any(|branch| {
362                    Self::contains_unnest(&branch.condition)
363                        || Self::contains_unnest(&branch.result)
364                }) || else_branch
365                    .as_ref()
366                    .map_or(false, |e| Self::contains_unnest(e))
367            }
368            SqlExpression::SimpleCaseExpression {
369                expr,
370                when_branches,
371                else_branch,
372            } => {
373                Self::contains_unnest(expr)
374                    || when_branches.iter().any(|branch| {
375                        Self::contains_unnest(&branch.value)
376                            || Self::contains_unnest(&branch.result)
377                    })
378                    || else_branch
379                        .as_ref()
380                        .map_or(false, |e| Self::contains_unnest(e))
381            }
382            SqlExpression::InList { expr, values } => {
383                Self::contains_unnest(expr) || values.iter().any(Self::contains_unnest)
384            }
385            SqlExpression::NotInList { expr, values } => {
386                Self::contains_unnest(expr) || values.iter().any(Self::contains_unnest)
387            }
388            SqlExpression::Between { expr, lower, upper } => {
389                Self::contains_unnest(expr)
390                    || Self::contains_unnest(lower)
391                    || Self::contains_unnest(upper)
392            }
393            SqlExpression::InSubquery { expr, .. } => Self::contains_unnest(expr),
394            SqlExpression::NotInSubquery { expr, .. } => Self::contains_unnest(expr),
395            SqlExpression::ScalarSubquery { .. } => false, // Subqueries are handled separately
396            SqlExpression::WindowFunction { args, .. } => args.iter().any(Self::contains_unnest),
397            SqlExpression::MethodCall { args, .. } => args.iter().any(Self::contains_unnest),
398            SqlExpression::ChainedMethodCall { base, args, .. } => {
399                Self::contains_unnest(base) || args.iter().any(Self::contains_unnest)
400            }
401            _ => false,
402        }
403    }
404
405    /// Execute a SQL query on a `DataTable` and return a `DataView` (for backward compatibility)
406    pub fn execute(&self, table: Arc<DataTable>, sql: &str) -> Result<DataView> {
407        let (view, _plan) = self.execute_with_plan(table, sql)?;
408        Ok(view)
409    }
410
411    /// Execute a SQL query with optional temp table registry access
412    pub fn execute_with_temp_tables(
413        &self,
414        table: Arc<DataTable>,
415        sql: &str,
416        temp_tables: Option<&TempTableRegistry>,
417    ) -> Result<DataView> {
418        let (view, _plan) = self.execute_with_plan_and_temp_tables(table, sql, temp_tables)?;
419        Ok(view)
420    }
421
422    /// Execute a parsed SelectStatement on a `DataTable` and return a `DataView`
423    pub fn execute_statement(
424        &self,
425        table: Arc<DataTable>,
426        statement: SelectStatement,
427    ) -> Result<DataView> {
428        self.execute_statement_with_temp_tables(table, statement, None)
429    }
430
431    /// Execute a parsed SelectStatement with optional temp table access
432    pub fn execute_statement_with_temp_tables(
433        &self,
434        table: Arc<DataTable>,
435        statement: SelectStatement,
436        temp_tables: Option<&TempTableRegistry>,
437    ) -> Result<DataView> {
438        // First process CTEs to build context
439        let mut cte_context = HashMap::new();
440
441        // Add temp tables to CTE context if provided
442        if let Some(temp_registry) = temp_tables {
443            for table_name in temp_registry.list_tables() {
444                if let Some(temp_table) = temp_registry.get(&table_name) {
445                    debug!("Adding temp table {} to CTE context", table_name);
446                    let view = DataView::new(temp_table);
447                    cte_context.insert(table_name, Arc::new(view));
448                }
449            }
450        }
451
452        for cte in &statement.ctes {
453            debug!("QueryEngine: Pre-processing CTE '{}'...", cte.name);
454            // Execute the CTE based on its type
455            let cte_result = match &cte.cte_type {
456                CTEType::Standard(query) => {
457                    // Execute the CTE query (it might reference earlier CTEs)
458                    let view = self.build_view_with_context(
459                        table.clone(),
460                        query.clone(),
461                        &mut cte_context,
462                    )?;
463
464                    // Materialize the view and enrich columns with qualified names
465                    let mut materialized = self.materialize_view(view)?;
466
467                    // Enrich columns with qualified names for proper scoping
468                    for column in materialized.columns_mut() {
469                        column.qualified_name = Some(format!("{}.{}", cte.name, column.name));
470                        column.source_table = Some(cte.name.clone());
471                    }
472
473                    DataView::new(Arc::new(materialized))
474                }
475                CTEType::Web(web_spec) => {
476                    // Fetch data from URL
477                    use crate::web::http_fetcher::WebDataFetcher;
478
479                    let fetcher = WebDataFetcher::new()?;
480                    // Pass None for query context (no full SQL available in these contexts)
481                    let mut data_table = fetcher.fetch(web_spec, &cte.name, None)?;
482
483                    // Enrich columns with qualified names for proper scoping
484                    for column in data_table.columns_mut() {
485                        column.qualified_name = Some(format!("{}.{}", cte.name, column.name));
486                        column.source_table = Some(cte.name.clone());
487                    }
488
489                    // Convert DataTable to DataView
490                    DataView::new(Arc::new(data_table))
491                }
492            };
493            // Store the result in the context for later use
494            cte_context.insert(cte.name.clone(), Arc::new(cte_result));
495            debug!(
496                "QueryEngine: CTE '{}' pre-processed, stored in context",
497                cte.name
498            );
499        }
500
501        // Now process subqueries with CTE context available
502        let mut subquery_executor =
503            SubqueryExecutor::with_cte_context(self.clone(), table.clone(), cte_context.clone());
504        let processed_statement = subquery_executor.execute_subqueries(&statement)?;
505
506        // Build the view with the same CTE context
507        self.build_view_with_context(table, processed_statement, &mut cte_context)
508    }
509
510    /// Execute a statement with provided CTE context (for subqueries)
511    pub fn execute_statement_with_cte_context(
512        &self,
513        table: Arc<DataTable>,
514        statement: SelectStatement,
515        cte_context: &HashMap<String, Arc<DataView>>,
516    ) -> Result<DataView> {
517        // Clone the context so we can add any CTEs from this statement
518        let mut local_context = cte_context.clone();
519
520        // Process any CTEs in this statement (they might be nested)
521        for cte in &statement.ctes {
522            debug!("QueryEngine: Processing nested CTE '{}'...", cte.name);
523            let cte_result = match &cte.cte_type {
524                CTEType::Standard(query) => {
525                    let view = self.build_view_with_context(
526                        table.clone(),
527                        query.clone(),
528                        &mut local_context,
529                    )?;
530
531                    // Materialize the view and enrich columns with qualified names
532                    let mut materialized = self.materialize_view(view)?;
533
534                    // Enrich columns with qualified names for proper scoping
535                    for column in materialized.columns_mut() {
536                        column.qualified_name = Some(format!("{}.{}", cte.name, column.name));
537                        column.source_table = Some(cte.name.clone());
538                    }
539
540                    DataView::new(Arc::new(materialized))
541                }
542                CTEType::Web(web_spec) => {
543                    // Fetch data from URL
544                    use crate::web::http_fetcher::WebDataFetcher;
545
546                    let fetcher = WebDataFetcher::new()?;
547                    // Pass None for query context (no full SQL available in these contexts)
548                    let mut data_table = fetcher.fetch(web_spec, &cte.name, None)?;
549
550                    // Enrich columns with qualified names for proper scoping
551                    for column in data_table.columns_mut() {
552                        column.qualified_name = Some(format!("{}.{}", cte.name, column.name));
553                        column.source_table = Some(cte.name.clone());
554                    }
555
556                    // Convert DataTable to DataView
557                    DataView::new(Arc::new(data_table))
558                }
559            };
560            local_context.insert(cte.name.clone(), Arc::new(cte_result));
561        }
562
563        // Process subqueries with the complete context
564        let mut subquery_executor =
565            SubqueryExecutor::with_cte_context(self.clone(), table.clone(), local_context.clone());
566        let processed_statement = subquery_executor.execute_subqueries(&statement)?;
567
568        // Build the view
569        self.build_view_with_context(table, processed_statement, &mut local_context)
570    }
571
572    /// Execute a query and return both the result and the execution plan
573    pub fn execute_with_plan(
574        &self,
575        table: Arc<DataTable>,
576        sql: &str,
577    ) -> Result<(DataView, ExecutionPlan)> {
578        self.execute_with_plan_and_temp_tables(table, sql, None)
579    }
580
581    /// Execute a query with temp tables and return both the result and the execution plan
582    pub fn execute_with_plan_and_temp_tables(
583        &self,
584        table: Arc<DataTable>,
585        sql: &str,
586        temp_tables: Option<&TempTableRegistry>,
587    ) -> Result<(DataView, ExecutionPlan)> {
588        let mut plan_builder = ExecutionPlanBuilder::new();
589        let start_time = Instant::now();
590
591        // Parse the SQL query
592        plan_builder.begin_step(StepType::Parse, "Parse SQL query".to_string());
593        plan_builder.add_detail(format!("Query: {}", sql));
594        let mut parser = Parser::new(sql);
595        let statement = parser
596            .parse()
597            .map_err(|e| anyhow::anyhow!("Parse error: {}", e))?;
598        plan_builder.add_detail(format!("Parsed successfully"));
599        if let Some(from) = &statement.from_table {
600            plan_builder.add_detail(format!("FROM: {}", from));
601        }
602        if statement.where_clause.is_some() {
603            plan_builder.add_detail("WHERE clause present".to_string());
604        }
605        plan_builder.end_step();
606
607        // First process CTEs to build context
608        let mut cte_context = HashMap::new();
609
610        // Add temp tables to CTE context if provided
611        if let Some(temp_registry) = temp_tables {
612            for table_name in temp_registry.list_tables() {
613                if let Some(temp_table) = temp_registry.get(&table_name) {
614                    debug!("Adding temp table {} to CTE context", table_name);
615                    let view = DataView::new(temp_table);
616                    cte_context.insert(table_name, Arc::new(view));
617                }
618            }
619        }
620
621        if !statement.ctes.is_empty() {
622            plan_builder.begin_step(
623                StepType::CTE,
624                format!("Process {} CTEs", statement.ctes.len()),
625            );
626
627            for cte in &statement.ctes {
628                let cte_start = Instant::now();
629                plan_builder.begin_step(StepType::CTE, format!("CTE '{}'", cte.name));
630
631                let cte_result = match &cte.cte_type {
632                    CTEType::Standard(query) => {
633                        // Add CTE query details
634                        if let Some(from) = &query.from_table {
635                            plan_builder.add_detail(format!("Source: {}", from));
636                        }
637                        if query.where_clause.is_some() {
638                            plan_builder.add_detail("Has WHERE clause".to_string());
639                        }
640                        if query.group_by.is_some() {
641                            plan_builder.add_detail("Has GROUP BY".to_string());
642                        }
643
644                        debug!(
645                            "QueryEngine: Processing CTE '{}' with existing context: {:?}",
646                            cte.name,
647                            cte_context.keys().collect::<Vec<_>>()
648                        );
649
650                        // Process subqueries in the CTE's query FIRST
651                        // This allows the subqueries to see all previously defined CTEs
652                        let mut subquery_executor = SubqueryExecutor::with_cte_context(
653                            self.clone(),
654                            table.clone(),
655                            cte_context.clone(),
656                        );
657                        let processed_query = subquery_executor.execute_subqueries(query)?;
658
659                        let view = self.build_view_with_context(
660                            table.clone(),
661                            processed_query,
662                            &mut cte_context,
663                        )?;
664
665                        // Materialize the view and enrich columns with qualified names
666                        let mut materialized = self.materialize_view(view)?;
667
668                        // Enrich columns with qualified names for proper scoping
669                        for column in materialized.columns_mut() {
670                            column.qualified_name = Some(format!("{}.{}", cte.name, column.name));
671                            column.source_table = Some(cte.name.clone());
672                        }
673
674                        DataView::new(Arc::new(materialized))
675                    }
676                    CTEType::Web(web_spec) => {
677                        plan_builder.add_detail(format!("URL: {}", web_spec.url));
678                        if let Some(format) = &web_spec.format {
679                            plan_builder.add_detail(format!("Format: {:?}", format));
680                        }
681                        if let Some(cache) = web_spec.cache_seconds {
682                            plan_builder.add_detail(format!("Cache: {} seconds", cache));
683                        }
684
685                        // Fetch data from URL
686                        use crate::web::http_fetcher::WebDataFetcher;
687
688                        let fetcher = WebDataFetcher::new()?;
689                        // Pass None for query context - each WEB CTE is independent
690                        let mut data_table = fetcher.fetch(web_spec, &cte.name, None)?;
691
692                        // Enrich columns with qualified names for proper scoping
693                        for column in data_table.columns_mut() {
694                            column.qualified_name = Some(format!("{}.{}", cte.name, column.name));
695                            column.source_table = Some(cte.name.clone());
696                        }
697
698                        // Convert DataTable to DataView
699                        DataView::new(Arc::new(data_table))
700                    }
701                };
702
703                // Record CTE statistics
704                plan_builder.set_rows_out(cte_result.row_count());
705                plan_builder.add_detail(format!(
706                    "Result: {} rows, {} columns",
707                    cte_result.row_count(),
708                    cte_result.column_count()
709                ));
710                plan_builder.add_detail(format!(
711                    "Execution time: {:.3}ms",
712                    cte_start.elapsed().as_secs_f64() * 1000.0
713                ));
714
715                debug!(
716                    "QueryEngine: Storing CTE '{}' in context with {} rows",
717                    cte.name,
718                    cte_result.row_count()
719                );
720                cte_context.insert(cte.name.clone(), Arc::new(cte_result));
721                plan_builder.end_step();
722            }
723
724            plan_builder.add_detail(format!(
725                "All {} CTEs cached in context",
726                statement.ctes.len()
727            ));
728            plan_builder.end_step();
729        }
730
731        // Process subqueries in the statement with CTE context
732        plan_builder.begin_step(StepType::Subquery, "Process subqueries".to_string());
733        let mut subquery_executor =
734            SubqueryExecutor::with_cte_context(self.clone(), table.clone(), cte_context.clone());
735
736        // Check if there are subqueries to process
737        let has_subqueries = statement.where_clause.as_ref().map_or(false, |w| {
738            // This is a simplified check - in reality we'd need to walk the AST
739            format!("{:?}", w).contains("Subquery")
740        });
741
742        if has_subqueries {
743            plan_builder.add_detail("Evaluating subqueries in WHERE clause".to_string());
744        }
745
746        let processed_statement = subquery_executor.execute_subqueries(&statement)?;
747
748        if has_subqueries {
749            plan_builder.add_detail("Subqueries replaced with materialized values".to_string());
750        } else {
751            plan_builder.add_detail("No subqueries to process".to_string());
752        }
753
754        plan_builder.end_step();
755        let result = self.build_view_with_context_and_plan(
756            table,
757            processed_statement,
758            &mut cte_context,
759            &mut plan_builder,
760        )?;
761
762        let total_duration = start_time.elapsed();
763        info!(
764            "Query execution complete: total={:?}, rows={}",
765            total_duration,
766            result.row_count()
767        );
768
769        let plan = plan_builder.build();
770        Ok((result, plan))
771    }
772
773    /// Build a `DataView` from a parsed SQL statement
774    fn build_view(&self, table: Arc<DataTable>, statement: SelectStatement) -> Result<DataView> {
775        let mut cte_context = HashMap::new();
776        self.build_view_with_context(table, statement, &mut cte_context)
777    }
778
779    /// Build a DataView from a SelectStatement with CTE context
780    fn build_view_with_context(
781        &self,
782        table: Arc<DataTable>,
783        statement: SelectStatement,
784        cte_context: &mut HashMap<String, Arc<DataView>>,
785    ) -> Result<DataView> {
786        let mut dummy_plan = ExecutionPlanBuilder::new();
787        let mut exec_context = ExecutionContext::new();
788        self.build_view_with_context_and_plan_and_exec(
789            table,
790            statement,
791            cte_context,
792            &mut dummy_plan,
793            &mut exec_context,
794        )
795    }
796
797    /// Build a DataView from a SelectStatement with CTE context and execution plan tracking
798    fn build_view_with_context_and_plan(
799        &self,
800        table: Arc<DataTable>,
801        statement: SelectStatement,
802        cte_context: &mut HashMap<String, Arc<DataView>>,
803        plan: &mut ExecutionPlanBuilder,
804    ) -> Result<DataView> {
805        let mut exec_context = ExecutionContext::new();
806        self.build_view_with_context_and_plan_and_exec(
807            table,
808            statement,
809            cte_context,
810            plan,
811            &mut exec_context,
812        )
813    }
814
815    /// Build a DataView with CTE context, execution plan, and alias resolution context
816    fn build_view_with_context_and_plan_and_exec(
817        &self,
818        table: Arc<DataTable>,
819        statement: SelectStatement,
820        cte_context: &mut HashMap<String, Arc<DataView>>,
821        plan: &mut ExecutionPlanBuilder,
822        exec_context: &mut ExecutionContext,
823    ) -> Result<DataView> {
824        // First, process any CTEs that aren't already in the context
825        for cte in &statement.ctes {
826            // Skip if already processed (e.g., by execute_select for WEB CTEs)
827            if cte_context.contains_key(&cte.name) {
828                debug!(
829                    "QueryEngine: CTE '{}' already in context, skipping",
830                    cte.name
831                );
832                continue;
833            }
834
835            debug!("QueryEngine: Processing CTE '{}'...", cte.name);
836            debug!(
837                "QueryEngine: Available CTEs for '{}': {:?}",
838                cte.name,
839                cte_context.keys().collect::<Vec<_>>()
840            );
841
842            // Execute the CTE query (it might reference earlier CTEs)
843            let cte_result = match &cte.cte_type {
844                CTEType::Standard(query) => {
845                    let view =
846                        self.build_view_with_context(table.clone(), query.clone(), cte_context)?;
847
848                    // Materialize the view and enrich columns with qualified names
849                    let mut materialized = self.materialize_view(view)?;
850
851                    // Enrich columns with qualified names for proper scoping
852                    for column in materialized.columns_mut() {
853                        column.qualified_name = Some(format!("{}.{}", cte.name, column.name));
854                        column.source_table = Some(cte.name.clone());
855                    }
856
857                    DataView::new(Arc::new(materialized))
858                }
859                CTEType::Web(_web_spec) => {
860                    // Web CTEs should have been processed earlier in execute_select
861                    return Err(anyhow!(
862                        "Web CTEs should be processed in execute_select method"
863                    ));
864                }
865            };
866
867            // Store the result in the context for later use
868            cte_context.insert(cte.name.clone(), Arc::new(cte_result));
869            debug!(
870                "QueryEngine: CTE '{}' processed, stored in context",
871                cte.name
872            );
873        }
874
875        // Determine the source table for the main query
876        let source_table = if let Some(ref table_func) = statement.from_function {
877            // Handle table functions like RANGE()
878            debug!("QueryEngine: Processing table function...");
879            match table_func {
880                TableFunction::Generator { name, args } => {
881                    // Use the generator registry to create the table
882                    use crate::sql::generators::GeneratorRegistry;
883
884                    // Create generator registry (could be cached in QueryEngine)
885                    let registry = GeneratorRegistry::new();
886
887                    if let Some(generator) = registry.get(name) {
888                        // Evaluate arguments
889                        let mut evaluator = ArithmeticEvaluator::with_date_notation(
890                            &table,
891                            self.date_notation.clone(),
892                        );
893                        let dummy_row = 0;
894
895                        let mut evaluated_args = Vec::new();
896                        for arg in args {
897                            evaluated_args.push(evaluator.evaluate(arg, dummy_row)?);
898                        }
899
900                        // Generate the table
901                        generator.generate(evaluated_args)?
902                    } else {
903                        return Err(anyhow!("Unknown generator function: {}", name));
904                    }
905                }
906            }
907        } else if let Some(ref subquery) = statement.from_subquery {
908            // Execute the subquery and use its result as the source
909            debug!("QueryEngine: Processing FROM subquery...");
910            let subquery_result =
911                self.build_view_with_context(table.clone(), *subquery.clone(), cte_context)?;
912
913            // Convert the DataView to a DataTable for use as source
914            // This materializes the subquery result
915            let materialized = self.materialize_view(subquery_result)?;
916            Arc::new(materialized)
917        } else if let Some(ref table_name) = statement.from_table {
918            // Check if this references a CTE
919            if let Some(cte_view) = cte_context.get(table_name) {
920                debug!("QueryEngine: Using CTE '{}' as source table", table_name);
921                // Materialize the CTE view as a table
922                let mut materialized = self.materialize_view((**cte_view).clone())?;
923
924                // Apply alias to qualified column names if present
925                if let Some(ref alias) = statement.from_alias {
926                    debug!(
927                        "QueryEngine: Applying alias '{}' to CTE '{}' qualified column names",
928                        alias, table_name
929                    );
930                    for column in materialized.columns_mut() {
931                        // Replace the CTE name with the alias in qualified names
932                        if let Some(ref qualified_name) = column.qualified_name {
933                            if qualified_name.starts_with(&format!("{}.", table_name)) {
934                                column.qualified_name =
935                                    Some(qualified_name.replace(
936                                        &format!("{}.", table_name),
937                                        &format!("{}.", alias),
938                                    ));
939                            }
940                        }
941                        // Update source table to reflect the alias
942                        if column.source_table.as_ref() == Some(table_name) {
943                            column.source_table = Some(alias.clone());
944                        }
945                    }
946                }
947
948                Arc::new(materialized)
949            } else {
950                // Regular table reference - use the provided table
951                table.clone()
952            }
953        } else {
954            // No FROM clause - use the provided table
955            table.clone()
956        };
957
958        // Register alias in execution context if present
959        if let Some(ref alias) = statement.from_alias {
960            if let Some(ref table_name) = statement.from_table {
961                exec_context.register_alias(alias.clone(), table_name.clone());
962            }
963        }
964
965        // Process JOINs if present
966        let final_table = if !statement.joins.is_empty() {
967            plan.begin_step(
968                StepType::Join,
969                format!("Process {} JOINs", statement.joins.len()),
970            );
971            plan.set_rows_in(source_table.row_count());
972
973            let join_executor = HashJoinExecutor::new(self.case_insensitive);
974            let mut current_table = source_table;
975
976            for (idx, join_clause) in statement.joins.iter().enumerate() {
977                let join_start = Instant::now();
978                plan.begin_step(StepType::Join, format!("JOIN #{}", idx + 1));
979                plan.add_detail(format!("Type: {:?}", join_clause.join_type));
980                plan.add_detail(format!("Left table: {} rows", current_table.row_count()));
981                plan.add_detail(format!(
982                    "Executing {:?} JOIN on {} condition(s)",
983                    join_clause.join_type,
984                    join_clause.condition.conditions.len()
985                ));
986
987                // Resolve the right table for the join
988                let right_table = match &join_clause.table {
989                    TableSource::Table(name) => {
990                        // Check if it's a CTE reference
991                        if let Some(cte_view) = cte_context.get(name) {
992                            let mut materialized = self.materialize_view((**cte_view).clone())?;
993
994                            // Apply alias to qualified column names if present
995                            if let Some(ref alias) = join_clause.alias {
996                                debug!("QueryEngine: Applying JOIN alias '{}' to CTE '{}' qualified column names", alias, name);
997                                for column in materialized.columns_mut() {
998                                    // Replace the CTE name with the alias in qualified names
999                                    if let Some(ref qualified_name) = column.qualified_name {
1000                                        if qualified_name.starts_with(&format!("{}.", name)) {
1001                                            column.qualified_name = Some(qualified_name.replace(
1002                                                &format!("{}.", name),
1003                                                &format!("{}.", alias),
1004                                            ));
1005                                        }
1006                                    }
1007                                    // Update source table to reflect the alias
1008                                    if column.source_table.as_ref() == Some(name) {
1009                                        column.source_table = Some(alias.clone());
1010                                    }
1011                                }
1012                            }
1013
1014                            Arc::new(materialized)
1015                        } else {
1016                            // For now, we need the actual table data
1017                            // In a real implementation, this would load from file
1018                            return Err(anyhow!("Cannot resolve table '{}' for JOIN", name));
1019                        }
1020                    }
1021                    TableSource::DerivedTable { query, alias: _ } => {
1022                        // Execute the subquery
1023                        let subquery_result = self.build_view_with_context(
1024                            table.clone(),
1025                            *query.clone(),
1026                            cte_context,
1027                        )?;
1028                        let materialized = self.materialize_view(subquery_result)?;
1029                        Arc::new(materialized)
1030                    }
1031                };
1032
1033                // Execute the join
1034                let joined = join_executor.execute_join(
1035                    current_table.clone(),
1036                    join_clause,
1037                    right_table.clone(),
1038                )?;
1039
1040                plan.add_detail(format!("Right table: {} rows", right_table.row_count()));
1041                plan.set_rows_out(joined.row_count());
1042                plan.add_detail(format!("Result: {} rows", joined.row_count()));
1043                plan.add_detail(format!(
1044                    "Join time: {:.3}ms",
1045                    join_start.elapsed().as_secs_f64() * 1000.0
1046                ));
1047                plan.end_step();
1048
1049                current_table = Arc::new(joined);
1050            }
1051
1052            plan.set_rows_out(current_table.row_count());
1053            plan.add_detail(format!(
1054                "Final result after all joins: {} rows",
1055                current_table.row_count()
1056            ));
1057            plan.end_step();
1058            current_table
1059        } else {
1060            source_table
1061        };
1062
1063        // Continue with the existing build_view logic but using final_table
1064        self.build_view_internal_with_plan_and_exec(
1065            final_table,
1066            statement,
1067            plan,
1068            Some(exec_context),
1069        )
1070    }
1071
1072    /// Materialize a DataView into a new DataTable
1073    pub fn materialize_view(&self, view: DataView) -> Result<DataTable> {
1074        let source = view.source();
1075        let mut result_table = DataTable::new("derived");
1076
1077        // Get the visible columns from the view
1078        let visible_cols = view.visible_column_indices().to_vec();
1079
1080        // Copy column definitions
1081        for col_idx in &visible_cols {
1082            let col = &source.columns[*col_idx];
1083            let new_col = DataColumn {
1084                name: col.name.clone(),
1085                data_type: col.data_type.clone(),
1086                nullable: col.nullable,
1087                unique_values: col.unique_values,
1088                null_count: col.null_count,
1089                metadata: col.metadata.clone(),
1090                qualified_name: col.qualified_name.clone(), // Preserve qualified name
1091                source_table: col.source_table.clone(),     // Preserve source table
1092            };
1093            result_table.add_column(new_col);
1094        }
1095
1096        // Copy visible rows
1097        for row_idx in view.visible_row_indices() {
1098            let source_row = &source.rows[*row_idx];
1099            let mut new_row = DataRow { values: Vec::new() };
1100
1101            for col_idx in &visible_cols {
1102                new_row.values.push(source_row.values[*col_idx].clone());
1103            }
1104
1105            result_table.add_row(new_row);
1106        }
1107
1108        Ok(result_table)
1109    }
1110
1111    fn build_view_internal(
1112        &self,
1113        table: Arc<DataTable>,
1114        statement: SelectStatement,
1115    ) -> Result<DataView> {
1116        let mut dummy_plan = ExecutionPlanBuilder::new();
1117        self.build_view_internal_with_plan(table, statement, &mut dummy_plan)
1118    }
1119
1120    fn build_view_internal_with_plan(
1121        &self,
1122        table: Arc<DataTable>,
1123        statement: SelectStatement,
1124        plan: &mut ExecutionPlanBuilder,
1125    ) -> Result<DataView> {
1126        self.build_view_internal_with_plan_and_exec(table, statement, plan, None)
1127    }
1128
1129    fn build_view_internal_with_plan_and_exec(
1130        &self,
1131        table: Arc<DataTable>,
1132        statement: SelectStatement,
1133        plan: &mut ExecutionPlanBuilder,
1134        exec_context: Option<&ExecutionContext>,
1135    ) -> Result<DataView> {
1136        debug!(
1137            "QueryEngine::build_view - select_items: {:?}",
1138            statement.select_items
1139        );
1140        debug!(
1141            "QueryEngine::build_view - where_clause: {:?}",
1142            statement.where_clause
1143        );
1144
1145        // Start with all rows visible
1146        let mut visible_rows: Vec<usize> = (0..table.row_count()).collect();
1147
1148        // Apply WHERE clause filtering using recursive evaluator
1149        if let Some(where_clause) = &statement.where_clause {
1150            let total_rows = table.row_count();
1151            debug!("QueryEngine: Applying WHERE clause to {} rows", total_rows);
1152            debug!("QueryEngine: WHERE clause = {:?}", where_clause);
1153
1154            plan.begin_step(StepType::Filter, "WHERE clause filtering".to_string());
1155            plan.set_rows_in(total_rows);
1156            plan.add_detail(format!("Input: {} rows", total_rows));
1157
1158            // Add details about WHERE conditions
1159            for condition in &where_clause.conditions {
1160                plan.add_detail(format!("Condition: {:?}", condition.expr));
1161            }
1162
1163            let filter_start = Instant::now();
1164            // Create an evaluation context for caching compiled regexes
1165            let mut eval_context = EvaluationContext::new(self.case_insensitive);
1166
1167            // Create evaluator ONCE before the loop for performance
1168            let mut evaluator = if let Some(exec_ctx) = exec_context {
1169                // Use both contexts: exec_context for alias resolution, eval_context for regex caching
1170                RecursiveWhereEvaluator::with_both_contexts(&table, &mut eval_context, exec_ctx)
1171            } else {
1172                RecursiveWhereEvaluator::with_context(&table, &mut eval_context)
1173            };
1174
1175            // Filter visible rows based on WHERE clause
1176            let mut filtered_rows = Vec::new();
1177            for row_idx in visible_rows {
1178                // Only log for first few rows to avoid performance impact
1179                if row_idx < 3 {
1180                    debug!("QueryEngine: Evaluating WHERE clause for row {}", row_idx);
1181                }
1182
1183                match evaluator.evaluate(where_clause, row_idx) {
1184                    Ok(result) => {
1185                        if row_idx < 3 {
1186                            debug!("QueryEngine: Row {} WHERE result: {}", row_idx, result);
1187                        }
1188                        if result {
1189                            filtered_rows.push(row_idx);
1190                        }
1191                    }
1192                    Err(e) => {
1193                        if row_idx < 3 {
1194                            debug!(
1195                                "QueryEngine: WHERE evaluation error for row {}: {}",
1196                                row_idx, e
1197                            );
1198                        }
1199                        // Propagate WHERE clause errors instead of silently ignoring them
1200                        return Err(e);
1201                    }
1202                }
1203            }
1204
1205            // Log regex cache statistics
1206            let (compilations, cache_hits) = eval_context.get_stats();
1207            if compilations > 0 || cache_hits > 0 {
1208                debug!(
1209                    "LIKE pattern cache: {} compilations, {} cache hits",
1210                    compilations, cache_hits
1211                );
1212            }
1213            visible_rows = filtered_rows;
1214            let filter_duration = filter_start.elapsed();
1215            info!(
1216                "WHERE clause filtering: {} rows -> {} rows in {:?}",
1217                total_rows,
1218                visible_rows.len(),
1219                filter_duration
1220            );
1221
1222            plan.set_rows_out(visible_rows.len());
1223            plan.add_detail(format!("Output: {} rows", visible_rows.len()));
1224            plan.add_detail(format!(
1225                "Filter time: {:.3}ms",
1226                filter_duration.as_secs_f64() * 1000.0
1227            ));
1228            plan.end_step();
1229        }
1230
1231        // Create initial DataView with filtered rows
1232        let mut view = DataView::new(table.clone());
1233        view = view.with_rows(visible_rows);
1234
1235        // Handle GROUP BY if present
1236        if let Some(group_by_exprs) = &statement.group_by {
1237            if !group_by_exprs.is_empty() {
1238                debug!("QueryEngine: Processing GROUP BY: {:?}", group_by_exprs);
1239
1240                plan.begin_step(
1241                    StepType::GroupBy,
1242                    format!("GROUP BY {} expressions", group_by_exprs.len()),
1243                );
1244                plan.set_rows_in(view.row_count());
1245                plan.add_detail(format!("Input: {} rows", view.row_count()));
1246                for expr in group_by_exprs {
1247                    plan.add_detail(format!("Group by: {:?}", expr));
1248                }
1249
1250                let group_start = Instant::now();
1251                view = self.apply_group_by(
1252                    view,
1253                    group_by_exprs,
1254                    &statement.select_items,
1255                    statement.having.as_ref(),
1256                    plan,
1257                )?;
1258
1259                plan.set_rows_out(view.row_count());
1260                plan.add_detail(format!("Output: {} groups", view.row_count()));
1261                plan.add_detail(format!(
1262                    "Overall time: {:.3}ms",
1263                    group_start.elapsed().as_secs_f64() * 1000.0
1264                ));
1265                plan.end_step();
1266            }
1267        } else {
1268            // Apply column projection or computed expressions (SELECT clause) - do this AFTER filtering
1269            if !statement.select_items.is_empty() {
1270                // Check if we have ANY non-star items (not just the first one)
1271                let has_non_star_items = statement
1272                    .select_items
1273                    .iter()
1274                    .any(|item| !matches!(item, SelectItem::Star { .. }));
1275
1276                // Apply select items if:
1277                // 1. We have computed expressions or explicit columns
1278                // 2. OR we have a mix of star and other items (e.g., SELECT *, computed_col)
1279                if has_non_star_items || statement.select_items.len() > 1 {
1280                    view = self.apply_select_items(
1281                        view,
1282                        &statement.select_items,
1283                        &statement,
1284                        exec_context,
1285                    )?;
1286                }
1287                // If it's just a single star, no projection needed
1288            } else if !statement.columns.is_empty() && statement.columns[0] != "*" {
1289                debug!("QueryEngine: Using legacy columns path");
1290                // Fallback to legacy column projection for backward compatibility
1291                // Use the current view's source table, not the original table
1292                let source_table = view.source();
1293                let column_indices =
1294                    self.resolve_column_indices(source_table, &statement.columns)?;
1295                view = view.with_columns(column_indices);
1296            }
1297        }
1298
1299        // Apply DISTINCT if specified
1300        if statement.distinct {
1301            plan.begin_step(StepType::Distinct, "Remove duplicate rows".to_string());
1302            plan.set_rows_in(view.row_count());
1303            plan.add_detail(format!("Input: {} rows", view.row_count()));
1304
1305            let distinct_start = Instant::now();
1306            view = self.apply_distinct(view)?;
1307
1308            plan.set_rows_out(view.row_count());
1309            plan.add_detail(format!("Output: {} unique rows", view.row_count()));
1310            plan.add_detail(format!(
1311                "Distinct time: {:.3}ms",
1312                distinct_start.elapsed().as_secs_f64() * 1000.0
1313            ));
1314            plan.end_step();
1315        }
1316
1317        // Apply ORDER BY sorting
1318        if let Some(order_by_columns) = &statement.order_by {
1319            if !order_by_columns.is_empty() {
1320                plan.begin_step(
1321                    StepType::Sort,
1322                    format!("ORDER BY {} columns", order_by_columns.len()),
1323                );
1324                plan.set_rows_in(view.row_count());
1325                for col in order_by_columns {
1326                    // Format the expression (simplified for now - just show column name or "expr")
1327                    let expr_str = match &col.expr {
1328                        SqlExpression::Column(col_ref) => col_ref.name.clone(),
1329                        _ => "expr".to_string(),
1330                    };
1331                    plan.add_detail(format!("{} {:?}", expr_str, col.direction));
1332                }
1333
1334                let sort_start = Instant::now();
1335                view =
1336                    self.apply_multi_order_by_with_context(view, order_by_columns, exec_context)?;
1337
1338                plan.add_detail(format!(
1339                    "Sort time: {:.3}ms",
1340                    sort_start.elapsed().as_secs_f64() * 1000.0
1341                ));
1342                plan.end_step();
1343            }
1344        }
1345
1346        // Apply LIMIT/OFFSET
1347        if let Some(limit) = statement.limit {
1348            let offset = statement.offset.unwrap_or(0);
1349            plan.begin_step(StepType::Limit, format!("LIMIT {}", limit));
1350            plan.set_rows_in(view.row_count());
1351            if offset > 0 {
1352                plan.add_detail(format!("OFFSET: {}", offset));
1353            }
1354            view = view.with_limit(limit, offset);
1355            plan.set_rows_out(view.row_count());
1356            plan.add_detail(format!("Output: {} rows", view.row_count()));
1357            plan.end_step();
1358        }
1359
1360        // Process set operations (UNION ALL, UNION, INTERSECT, EXCEPT)
1361        if !statement.set_operations.is_empty() {
1362            plan.begin_step(
1363                StepType::SetOperation,
1364                format!("Process {} set operations", statement.set_operations.len()),
1365            );
1366            plan.set_rows_in(view.row_count());
1367
1368            // Materialize the first result set
1369            let mut combined_table = self.materialize_view(view)?;
1370            let first_columns = combined_table.column_names();
1371            let first_column_count = first_columns.len();
1372
1373            // Track if any operation requires deduplication
1374            let mut needs_deduplication = false;
1375
1376            // Process each set operation
1377            for (idx, (operation, next_statement)) in statement.set_operations.iter().enumerate() {
1378                let op_start = Instant::now();
1379                plan.begin_step(
1380                    StepType::SetOperation,
1381                    format!("{:?} operation #{}", operation, idx + 1),
1382                );
1383
1384                // Execute the next SELECT statement
1385                // We need to pass the original table and exec_context for proper resolution
1386                let next_view = if let Some(exec_ctx) = exec_context {
1387                    self.build_view_internal_with_plan_and_exec(
1388                        table.clone(),
1389                        *next_statement.clone(),
1390                        plan,
1391                        Some(exec_ctx),
1392                    )?
1393                } else {
1394                    self.build_view_internal_with_plan(
1395                        table.clone(),
1396                        *next_statement.clone(),
1397                        plan,
1398                    )?
1399                };
1400
1401                // Materialize the next result set
1402                let next_table = self.materialize_view(next_view)?;
1403                let next_columns = next_table.column_names();
1404                let next_column_count = next_columns.len();
1405
1406                // Validate schema compatibility
1407                if first_column_count != next_column_count {
1408                    return Err(anyhow!(
1409                        "UNION queries must have the same number of columns: first query has {} columns, but query #{} has {} columns",
1410                        first_column_count,
1411                        idx + 2,
1412                        next_column_count
1413                    ));
1414                }
1415
1416                // Warn if column names don't match (but allow it - some SQL dialects do)
1417                for (col_idx, (first_col, next_col)) in
1418                    first_columns.iter().zip(next_columns.iter()).enumerate()
1419                {
1420                    if !first_col.eq_ignore_ascii_case(next_col) {
1421                        debug!(
1422                            "UNION column name mismatch at position {}: '{}' vs '{}' (using first query's name)",
1423                            col_idx + 1,
1424                            first_col,
1425                            next_col
1426                        );
1427                    }
1428                }
1429
1430                plan.add_detail(format!("Left: {} rows", combined_table.row_count()));
1431                plan.add_detail(format!("Right: {} rows", next_table.row_count()));
1432
1433                // Perform the set operation
1434                match operation {
1435                    SetOperation::UnionAll => {
1436                        // UNION ALL: Simply concatenate all rows without deduplication
1437                        for row in next_table.rows.iter() {
1438                            combined_table.add_row(row.clone());
1439                        }
1440                        plan.add_detail(format!(
1441                            "Result: {} rows (no deduplication)",
1442                            combined_table.row_count()
1443                        ));
1444                    }
1445                    SetOperation::Union => {
1446                        // UNION: Concatenate all rows first, deduplicate at the end
1447                        for row in next_table.rows.iter() {
1448                            combined_table.add_row(row.clone());
1449                        }
1450                        needs_deduplication = true;
1451                        plan.add_detail(format!(
1452                            "Combined: {} rows (deduplication pending)",
1453                            combined_table.row_count()
1454                        ));
1455                    }
1456                    SetOperation::Intersect => {
1457                        // INTERSECT: Keep only rows that appear in both
1458                        // TODO: Implement intersection logic
1459                        return Err(anyhow!("INTERSECT is not yet implemented"));
1460                    }
1461                    SetOperation::Except => {
1462                        // EXCEPT: Keep only rows from left that don't appear in right
1463                        // TODO: Implement except logic
1464                        return Err(anyhow!("EXCEPT is not yet implemented"));
1465                    }
1466                }
1467
1468                plan.add_detail(format!(
1469                    "Operation time: {:.3}ms",
1470                    op_start.elapsed().as_secs_f64() * 1000.0
1471                ));
1472                plan.set_rows_out(combined_table.row_count());
1473                plan.end_step();
1474            }
1475
1476            plan.set_rows_out(combined_table.row_count());
1477            plan.add_detail(format!(
1478                "Combined result: {} rows after {} operations",
1479                combined_table.row_count(),
1480                statement.set_operations.len()
1481            ));
1482            plan.end_step();
1483
1484            // Create a new view from the combined table
1485            view = DataView::new(Arc::new(combined_table));
1486
1487            // Apply deduplication if any UNION (not UNION ALL) operation was used
1488            if needs_deduplication {
1489                plan.begin_step(
1490                    StepType::Distinct,
1491                    "UNION deduplication - remove duplicate rows".to_string(),
1492                );
1493                plan.set_rows_in(view.row_count());
1494                plan.add_detail(format!("Input: {} rows", view.row_count()));
1495
1496                let distinct_start = Instant::now();
1497                view = self.apply_distinct(view)?;
1498
1499                plan.set_rows_out(view.row_count());
1500                plan.add_detail(format!("Output: {} unique rows", view.row_count()));
1501                plan.add_detail(format!(
1502                    "Deduplication time: {:.3}ms",
1503                    distinct_start.elapsed().as_secs_f64() * 1000.0
1504                ));
1505                plan.end_step();
1506            }
1507        }
1508
1509        Ok(view)
1510    }
1511
1512    /// Resolve column names to indices
1513    fn resolve_column_indices(&self, table: &DataTable, columns: &[String]) -> Result<Vec<usize>> {
1514        let mut indices = Vec::new();
1515        let table_columns = table.column_names();
1516
1517        for col_name in columns {
1518            let index = table_columns
1519                .iter()
1520                .position(|c| c.eq_ignore_ascii_case(col_name))
1521                .ok_or_else(|| {
1522                    let suggestion = self.find_similar_column(table, col_name);
1523                    match suggestion {
1524                        Some(similar) => anyhow::anyhow!(
1525                            "Column '{}' not found. Did you mean '{}'?",
1526                            col_name,
1527                            similar
1528                        ),
1529                        None => anyhow::anyhow!("Column '{}' not found", col_name),
1530                    }
1531                })?;
1532            indices.push(index);
1533        }
1534
1535        Ok(indices)
1536    }
1537
1538    /// Apply SELECT items (columns and computed expressions) to create new view
1539    fn apply_select_items(
1540        &self,
1541        view: DataView,
1542        select_items: &[SelectItem],
1543        _statement: &SelectStatement,
1544        exec_context: Option<&ExecutionContext>,
1545    ) -> Result<DataView> {
1546        debug!(
1547            "QueryEngine::apply_select_items - items: {:?}",
1548            select_items
1549        );
1550        debug!(
1551            "QueryEngine::apply_select_items - input view has {} rows",
1552            view.row_count()
1553        );
1554
1555        // Check if any SELECT item contains UNNEST - if so, use row expansion mode
1556        let has_unnest = select_items.iter().any(|item| match item {
1557            SelectItem::Expression { expr, .. } => Self::contains_unnest(expr),
1558            _ => false,
1559        });
1560
1561        if has_unnest {
1562            debug!("QueryEngine::apply_select_items - UNNEST detected, using row expansion");
1563            return self.apply_select_with_row_expansion(view, select_items);
1564        }
1565
1566        // Check if this is an aggregate query:
1567        // 1. At least one aggregate function exists
1568        // 2. All other items are either aggregates or constants (aggregate-compatible)
1569        let has_aggregates = select_items.iter().any(|item| match item {
1570            SelectItem::Expression { expr, .. } => contains_aggregate(expr),
1571            SelectItem::Column { .. } => false,
1572            SelectItem::Star { .. } => false,
1573        });
1574
1575        let all_aggregate_compatible = select_items.iter().all(|item| match item {
1576            SelectItem::Expression { expr, .. } => is_aggregate_compatible(expr),
1577            SelectItem::Column { .. } => false, // Columns are not aggregate-compatible
1578            SelectItem::Star { .. } => false,   // Star is not aggregate-compatible
1579        });
1580
1581        if has_aggregates && all_aggregate_compatible && view.row_count() > 0 {
1582            // Special handling for aggregate queries with constants (no GROUP BY)
1583            // These should produce exactly one row
1584            debug!("QueryEngine::apply_select_items - detected aggregate query with constants");
1585            return self.apply_aggregate_select(view, select_items);
1586        }
1587
1588        // Check if we need to create computed columns
1589        let has_computed_expressions = select_items
1590            .iter()
1591            .any(|item| matches!(item, SelectItem::Expression { .. }));
1592
1593        debug!(
1594            "QueryEngine::apply_select_items - has_computed_expressions: {}",
1595            has_computed_expressions
1596        );
1597
1598        if !has_computed_expressions {
1599            // Simple case: only columns, use existing projection logic
1600            let column_indices = self.resolve_select_columns(view.source(), select_items)?;
1601            return Ok(view.with_columns(column_indices));
1602        }
1603
1604        // Complex case: we have computed expressions
1605        // IMPORTANT: We create a PROJECTED view, not a new table
1606        // This preserves the original DataTable reference
1607
1608        let source_table = view.source();
1609        let visible_rows = view.visible_row_indices();
1610
1611        // Create a temporary table just for the computed result view
1612        // But this table is only used for the current query result
1613        let mut computed_table = DataTable::new("query_result");
1614
1615        // First, expand any Star selectors to actual columns
1616        let mut expanded_items = Vec::new();
1617        for item in select_items {
1618            match item {
1619                SelectItem::Star { table_prefix, .. } => {
1620                    if let Some(prefix) = table_prefix {
1621                        // Scoped expansion: table.* expands only columns from that table
1622                        debug!("QueryEngine::apply_select_items - expanding {}.*", prefix);
1623                        for col in &source_table.columns {
1624                            if Self::column_matches_table(col, prefix) {
1625                                expanded_items.push(SelectItem::Column {
1626                                    column: ColumnRef::unquoted(col.name.clone()),
1627                                    leading_comments: vec![],
1628                                    trailing_comment: None,
1629                                });
1630                            }
1631                        }
1632                    } else {
1633                        // Unscoped expansion: * expands to all columns
1634                        debug!("QueryEngine::apply_select_items - expanding *");
1635                        for col_name in source_table.column_names() {
1636                            expanded_items.push(SelectItem::Column {
1637                                column: ColumnRef::unquoted(col_name.to_string()),
1638                                leading_comments: vec![],
1639                                trailing_comment: None,
1640                            });
1641                        }
1642                    }
1643                }
1644                _ => expanded_items.push(item.clone()),
1645            }
1646        }
1647
1648        // Add columns based on expanded SelectItems, handling duplicates
1649        let mut column_name_counts: std::collections::HashMap<String, usize> =
1650            std::collections::HashMap::new();
1651
1652        for item in &expanded_items {
1653            let base_name = match item {
1654                SelectItem::Column {
1655                    column: col_ref, ..
1656                } => col_ref.name.clone(),
1657                SelectItem::Expression { alias, .. } => alias.clone(),
1658                SelectItem::Star { .. } => unreachable!("Star should have been expanded"),
1659            };
1660
1661            // Check if this column name has been used before
1662            let count = column_name_counts.entry(base_name.clone()).or_insert(0);
1663            let column_name = if *count == 0 {
1664                // First occurrence, use the name as-is
1665                base_name.clone()
1666            } else {
1667                // Duplicate, append a suffix
1668                format!("{base_name}_{count}")
1669            };
1670            *count += 1;
1671
1672            computed_table.add_column(DataColumn::new(&column_name));
1673        }
1674
1675        // Calculate values for each row
1676        let mut evaluator =
1677            ArithmeticEvaluator::with_date_notation(source_table, self.date_notation.clone());
1678
1679        // Populate table aliases from exec_context if available
1680        if let Some(exec_ctx) = exec_context {
1681            let aliases = exec_ctx.get_aliases();
1682            if !aliases.is_empty() {
1683                debug!(
1684                    "Applying {} aliases to evaluator: {:?}",
1685                    aliases.len(),
1686                    aliases
1687                );
1688                evaluator = evaluator.with_table_aliases(aliases);
1689            }
1690        }
1691
1692        for &row_idx in visible_rows {
1693            let mut row_values = Vec::new();
1694
1695            for item in &expanded_items {
1696                let value = match item {
1697                    SelectItem::Column {
1698                        column: col_ref, ..
1699                    } => {
1700                        // Use evaluator for column resolution (handles aliases properly)
1701                        match evaluator.evaluate(&SqlExpression::Column(col_ref.clone()), row_idx) {
1702                            Ok(val) => val,
1703                            Err(e) => {
1704                                return Err(anyhow!(
1705                                    "Failed to evaluate column {}: {}",
1706                                    col_ref.to_sql(),
1707                                    e
1708                                ));
1709                            }
1710                        }
1711                    }
1712                    SelectItem::Expression { expr, .. } => {
1713                        // Computed expression
1714                        evaluator.evaluate(&expr, row_idx)?
1715                    }
1716                    SelectItem::Star { .. } => unreachable!("Star should have been expanded"),
1717                };
1718                row_values.push(value);
1719            }
1720
1721            computed_table
1722                .add_row(DataRow::new(row_values))
1723                .map_err(|e| anyhow::anyhow!("Failed to add row: {}", e))?;
1724        }
1725
1726        // Return a view of the computed result
1727        // This is a temporary view for this query only
1728        Ok(DataView::new(Arc::new(computed_table)))
1729    }
1730
1731    /// Apply SELECT with row expansion (for UNNEST, EXPLODE, etc.)
1732    fn apply_select_with_row_expansion(
1733        &self,
1734        view: DataView,
1735        select_items: &[SelectItem],
1736    ) -> Result<DataView> {
1737        debug!("QueryEngine::apply_select_with_row_expansion - expanding rows");
1738
1739        let source_table = view.source();
1740        let visible_rows = view.visible_row_indices();
1741        let expander_registry = RowExpanderRegistry::new();
1742
1743        // Create result table
1744        let mut result_table = DataTable::new("unnest_result");
1745
1746        // Expand * to columns and set up result columns
1747        let mut expanded_items = Vec::new();
1748        for item in select_items {
1749            match item {
1750                SelectItem::Star { table_prefix, .. } => {
1751                    if let Some(prefix) = table_prefix {
1752                        // Scoped expansion: table.* expands only columns from that table
1753                        debug!(
1754                            "QueryEngine::apply_select_with_row_expansion - expanding {}.*",
1755                            prefix
1756                        );
1757                        for col in &source_table.columns {
1758                            if Self::column_matches_table(col, prefix) {
1759                                expanded_items.push(SelectItem::Column {
1760                                    column: ColumnRef::unquoted(col.name.clone()),
1761                                    leading_comments: vec![],
1762                                    trailing_comment: None,
1763                                });
1764                            }
1765                        }
1766                    } else {
1767                        // Unscoped expansion: * expands to all columns
1768                        debug!("QueryEngine::apply_select_with_row_expansion - expanding *");
1769                        for col_name in source_table.column_names() {
1770                            expanded_items.push(SelectItem::Column {
1771                                column: ColumnRef::unquoted(col_name.to_string()),
1772                                leading_comments: vec![],
1773                                trailing_comment: None,
1774                            });
1775                        }
1776                    }
1777                }
1778                _ => expanded_items.push(item.clone()),
1779            }
1780        }
1781
1782        // Add columns to result table
1783        for item in &expanded_items {
1784            let column_name = match item {
1785                SelectItem::Column {
1786                    column: col_ref, ..
1787                } => col_ref.name.clone(),
1788                SelectItem::Expression { alias, .. } => alias.clone(),
1789                SelectItem::Star { .. } => unreachable!("Star should have been expanded"),
1790            };
1791            result_table.add_column(DataColumn::new(&column_name));
1792        }
1793
1794        // Process each input row
1795        let mut evaluator =
1796            ArithmeticEvaluator::with_date_notation(source_table, self.date_notation.clone());
1797
1798        for &row_idx in visible_rows {
1799            // First pass: identify UNNEST expressions and collect their expansion arrays
1800            let mut unnest_expansions = Vec::new();
1801            let mut unnest_indices = Vec::new();
1802
1803            for (col_idx, item) in expanded_items.iter().enumerate() {
1804                if let SelectItem::Expression { expr, .. } = item {
1805                    if let Some(expansion_result) = self.try_expand_unnest(
1806                        &expr,
1807                        source_table,
1808                        row_idx,
1809                        &mut evaluator,
1810                        &expander_registry,
1811                    )? {
1812                        unnest_expansions.push(expansion_result);
1813                        unnest_indices.push(col_idx);
1814                    }
1815                }
1816            }
1817
1818            // Determine how many output rows to generate
1819            let expansion_count = if unnest_expansions.is_empty() {
1820                1 // No UNNEST, just one row
1821            } else {
1822                unnest_expansions
1823                    .iter()
1824                    .map(|exp| exp.row_count())
1825                    .max()
1826                    .unwrap_or(1)
1827            };
1828
1829            // Generate output rows
1830            for output_idx in 0..expansion_count {
1831                let mut row_values = Vec::new();
1832
1833                for (col_idx, item) in expanded_items.iter().enumerate() {
1834                    // Check if this column is an UNNEST column
1835                    let unnest_position = unnest_indices.iter().position(|&idx| idx == col_idx);
1836
1837                    let value = if let Some(unnest_idx) = unnest_position {
1838                        // Get value from expansion array (or NULL if exhausted)
1839                        let expansion = &unnest_expansions[unnest_idx];
1840                        expansion
1841                            .values
1842                            .get(output_idx)
1843                            .cloned()
1844                            .unwrap_or(DataValue::Null)
1845                    } else {
1846                        // Regular column or non-UNNEST expression - replicate from input
1847                        match item {
1848                            SelectItem::Column {
1849                                column: col_ref, ..
1850                            } => {
1851                                let col_idx =
1852                                    source_table.get_column_index(&col_ref.name).ok_or_else(
1853                                        || anyhow::anyhow!("Column '{}' not found", col_ref.name),
1854                                    )?;
1855                                let row = source_table
1856                                    .get_row(row_idx)
1857                                    .ok_or_else(|| anyhow::anyhow!("Row {} not found", row_idx))?;
1858                                row.get(col_idx)
1859                                    .ok_or_else(|| {
1860                                        anyhow::anyhow!("Column {} not found in row", col_idx)
1861                                    })?
1862                                    .clone()
1863                            }
1864                            SelectItem::Expression { expr, .. } => {
1865                                // Non-UNNEST expression - evaluate once and replicate
1866                                evaluator.evaluate(&expr, row_idx)?
1867                            }
1868                            SelectItem::Star { .. } => unreachable!(),
1869                        }
1870                    };
1871
1872                    row_values.push(value);
1873                }
1874
1875                result_table
1876                    .add_row(DataRow::new(row_values))
1877                    .map_err(|e| anyhow::anyhow!("Failed to add expanded row: {}", e))?;
1878            }
1879        }
1880
1881        debug!(
1882            "QueryEngine::apply_select_with_row_expansion - input rows: {}, output rows: {}",
1883            visible_rows.len(),
1884            result_table.row_count()
1885        );
1886
1887        Ok(DataView::new(Arc::new(result_table)))
1888    }
1889
1890    /// Try to expand an expression if it's an UNNEST call
1891    /// Returns Some(ExpansionResult) if successful, None if not an UNNEST
1892    fn try_expand_unnest(
1893        &self,
1894        expr: &SqlExpression,
1895        _source_table: &DataTable,
1896        row_idx: usize,
1897        evaluator: &mut ArithmeticEvaluator,
1898        expander_registry: &RowExpanderRegistry,
1899    ) -> Result<Option<crate::data::row_expanders::ExpansionResult>> {
1900        // Check for UNNEST variant (direct syntax)
1901        if let SqlExpression::Unnest { column, delimiter } = expr {
1902            // Evaluate the column expression
1903            let column_value = evaluator.evaluate(column, row_idx)?;
1904
1905            // Delimiter is already a string literal
1906            let delimiter_value = DataValue::String(delimiter.clone());
1907
1908            // Get the UNNEST expander
1909            let expander = expander_registry
1910                .get("UNNEST")
1911                .ok_or_else(|| anyhow::anyhow!("UNNEST expander not found"))?;
1912
1913            // Expand the value
1914            let expansion = expander.expand(&column_value, &[delimiter_value])?;
1915            return Ok(Some(expansion));
1916        }
1917
1918        // Also check for FunctionCall form (for compatibility)
1919        if let SqlExpression::FunctionCall { name, args, .. } = expr {
1920            if name.to_uppercase() == "UNNEST" {
1921                // UNNEST(column, delimiter)
1922                if args.len() != 2 {
1923                    return Err(anyhow::anyhow!(
1924                        "UNNEST requires exactly 2 arguments: UNNEST(column, delimiter)"
1925                    ));
1926                }
1927
1928                // Evaluate the column expression (first arg)
1929                let column_value = evaluator.evaluate(&args[0], row_idx)?;
1930
1931                // Evaluate the delimiter expression (second arg)
1932                let delimiter_value = evaluator.evaluate(&args[1], row_idx)?;
1933
1934                // Get the UNNEST expander
1935                let expander = expander_registry
1936                    .get("UNNEST")
1937                    .ok_or_else(|| anyhow::anyhow!("UNNEST expander not found"))?;
1938
1939                // Expand the value
1940                let expansion = expander.expand(&column_value, &[delimiter_value])?;
1941                return Ok(Some(expansion));
1942            }
1943        }
1944
1945        Ok(None)
1946    }
1947
1948    /// Apply aggregate-only SELECT (no GROUP BY - produces single row)
1949    fn apply_aggregate_select(
1950        &self,
1951        view: DataView,
1952        select_items: &[SelectItem],
1953    ) -> Result<DataView> {
1954        debug!("QueryEngine::apply_aggregate_select - creating single row aggregate result");
1955
1956        let source_table = view.source();
1957        let mut result_table = DataTable::new("aggregate_result");
1958
1959        // Add columns for each select item
1960        for item in select_items {
1961            let column_name = match item {
1962                SelectItem::Expression { alias, .. } => alias.clone(),
1963                _ => unreachable!("Should only have expressions in aggregate-only query"),
1964            };
1965            result_table.add_column(DataColumn::new(&column_name));
1966        }
1967
1968        // Create evaluator with visible rows from the view (for filtered aggregates)
1969        let visible_rows = view.visible_row_indices().to_vec();
1970        let mut evaluator =
1971            ArithmeticEvaluator::with_date_notation(source_table, self.date_notation.clone())
1972                .with_visible_rows(visible_rows);
1973
1974        // Evaluate each aggregate expression once (they handle all rows internally)
1975        let mut row_values = Vec::new();
1976        for item in select_items {
1977            match item {
1978                SelectItem::Expression { expr, .. } => {
1979                    // The evaluator will handle aggregates over all rows
1980                    // We pass row_index=0 but aggregates ignore it and process all rows
1981                    let value = evaluator.evaluate(expr, 0)?;
1982                    row_values.push(value);
1983                }
1984                _ => unreachable!("Should only have expressions in aggregate-only query"),
1985            }
1986        }
1987
1988        // Add the single result row
1989        result_table
1990            .add_row(DataRow::new(row_values))
1991            .map_err(|e| anyhow::anyhow!("Failed to add aggregate result row: {}", e))?;
1992
1993        Ok(DataView::new(Arc::new(result_table)))
1994    }
1995
1996    /// Check if a column belongs to a specific table based on source_table or qualified_name
1997    ///
1998    /// This is used for table-scoped star expansion (e.g., `SELECT user.*`)
1999    /// to filter which columns should be included.
2000    ///
2001    /// # Arguments
2002    /// * `col` - The column to check
2003    /// * `table_name` - The table name or alias to match against
2004    ///
2005    /// # Returns
2006    /// `true` if the column belongs to the specified table
2007    fn column_matches_table(col: &DataColumn, table_name: &str) -> bool {
2008        // First, check the source_table field
2009        if let Some(ref source) = col.source_table {
2010            // Direct match or matches with schema qualification
2011            if source == table_name || source.ends_with(&format!(".{}", table_name)) {
2012                return true;
2013            }
2014        }
2015
2016        // Second, check the qualified_name field
2017        if let Some(ref qualified) = col.qualified_name {
2018            // Check if qualified name starts with "table_name."
2019            if qualified.starts_with(&format!("{}.", table_name)) {
2020                return true;
2021            }
2022        }
2023
2024        false
2025    }
2026
2027    /// Resolve `SelectItem` columns to indices (for simple column projections only)
2028    fn resolve_select_columns(
2029        &self,
2030        table: &DataTable,
2031        select_items: &[SelectItem],
2032    ) -> Result<Vec<usize>> {
2033        let mut indices = Vec::new();
2034        let table_columns = table.column_names();
2035
2036        for item in select_items {
2037            match item {
2038                SelectItem::Column {
2039                    column: col_ref, ..
2040                } => {
2041                    // Check if this has a table prefix
2042                    let index = if let Some(table_prefix) = &col_ref.table_prefix {
2043                        // For qualified references, ONLY try qualified lookup - no fallback
2044                        let qualified_name = format!("{}.{}", table_prefix, col_ref.name);
2045                        table.find_column_by_qualified_name(&qualified_name)
2046                            .ok_or_else(|| {
2047                                // Check if any columns have qualified names for better error message
2048                                let has_qualified = table.columns.iter()
2049                                    .any(|c| c.qualified_name.is_some());
2050                                if !has_qualified {
2051                                    anyhow::anyhow!(
2052                                        "Column '{}' not found. Note: Table '{}' may not support qualified column names",
2053                                        qualified_name, table_prefix
2054                                    )
2055                                } else {
2056                                    anyhow::anyhow!("Column '{}' not found", qualified_name)
2057                                }
2058                            })?
2059                    } else {
2060                        // Simple column name lookup
2061                        table_columns
2062                            .iter()
2063                            .position(|c| c.eq_ignore_ascii_case(&col_ref.name))
2064                            .ok_or_else(|| {
2065                                let suggestion = self.find_similar_column(table, &col_ref.name);
2066                                match suggestion {
2067                                    Some(similar) => anyhow::anyhow!(
2068                                        "Column '{}' not found. Did you mean '{}'?",
2069                                        col_ref.name,
2070                                        similar
2071                                    ),
2072                                    None => anyhow::anyhow!("Column '{}' not found", col_ref.name),
2073                                }
2074                            })?
2075                    };
2076                    indices.push(index);
2077                }
2078                SelectItem::Star { table_prefix, .. } => {
2079                    if let Some(prefix) = table_prefix {
2080                        // Scoped expansion: table.* expands only columns from that table
2081                        for (i, col) in table.columns.iter().enumerate() {
2082                            if Self::column_matches_table(col, prefix) {
2083                                indices.push(i);
2084                            }
2085                        }
2086                    } else {
2087                        // Unscoped expansion: * expands to all column indices
2088                        for i in 0..table_columns.len() {
2089                            indices.push(i);
2090                        }
2091                    }
2092                }
2093                SelectItem::Expression { .. } => {
2094                    return Err(anyhow::anyhow!(
2095                        "Computed expressions require new table creation"
2096                    ));
2097                }
2098            }
2099        }
2100
2101        Ok(indices)
2102    }
2103
2104    /// Apply DISTINCT to remove duplicate rows
2105    fn apply_distinct(&self, view: DataView) -> Result<DataView> {
2106        use std::collections::HashSet;
2107
2108        let source = view.source();
2109        let visible_cols = view.visible_column_indices();
2110        let visible_rows = view.visible_row_indices();
2111
2112        // Build a set to track unique rows
2113        let mut seen_rows = HashSet::new();
2114        let mut unique_row_indices = Vec::new();
2115
2116        for &row_idx in visible_rows {
2117            // Build a key representing this row's visible column values
2118            let mut row_key = Vec::new();
2119            for &col_idx in visible_cols {
2120                let value = source
2121                    .get_value(row_idx, col_idx)
2122                    .ok_or_else(|| anyhow!("Invalid cell reference"))?;
2123                // Convert value to a hashable representation
2124                row_key.push(format!("{:?}", value));
2125            }
2126
2127            // Check if we've seen this row before
2128            if seen_rows.insert(row_key) {
2129                // First time seeing this row combination
2130                unique_row_indices.push(row_idx);
2131            }
2132        }
2133
2134        // Create a new view with only unique rows
2135        Ok(view.with_rows(unique_row_indices))
2136    }
2137
2138    /// Apply multi-column ORDER BY sorting to the view
2139    fn apply_multi_order_by(
2140        &self,
2141        view: DataView,
2142        order_by_columns: &[OrderByItem],
2143    ) -> Result<DataView> {
2144        self.apply_multi_order_by_with_context(view, order_by_columns, None)
2145    }
2146
2147    /// Apply multi-column ORDER BY sorting with exec_context for alias resolution
2148    fn apply_multi_order_by_with_context(
2149        &self,
2150        mut view: DataView,
2151        order_by_columns: &[OrderByItem],
2152        _exec_context: Option<&ExecutionContext>,
2153    ) -> Result<DataView> {
2154        // Build list of (source_column_index, ascending) tuples
2155        let mut sort_columns = Vec::new();
2156
2157        for order_col in order_by_columns {
2158            // Extract column name from expression (currently only supports simple columns)
2159            let column_name = match &order_col.expr {
2160                SqlExpression::Column(col_ref) => col_ref.name.clone(),
2161                _ => {
2162                    // TODO: Support expression evaluation in ORDER BY
2163                    return Err(anyhow!(
2164                        "ORDER BY expressions not yet supported - only simple columns allowed"
2165                    ));
2166                }
2167            };
2168
2169            // Try to find the column index, handling qualified column names (table.column)
2170            let col_index = if column_name.contains('.') {
2171                // Qualified column name - extract unqualified part
2172                if let Some(dot_pos) = column_name.rfind('.') {
2173                    let col_name = &column_name[dot_pos + 1..];
2174
2175                    // After SELECT processing, columns are unqualified
2176                    // So just use the column name part
2177                    debug!(
2178                        "ORDER BY: Extracting unqualified column '{}' from '{}'",
2179                        col_name, column_name
2180                    );
2181                    view.source().get_column_index(col_name)
2182                } else {
2183                    view.source().get_column_index(&column_name)
2184                }
2185            } else {
2186                // Simple column name
2187                view.source().get_column_index(&column_name)
2188            }
2189            .ok_or_else(|| {
2190                // If not found, provide helpful error with suggestions
2191                let suggestion = self.find_similar_column(view.source(), &column_name);
2192                match suggestion {
2193                    Some(similar) => anyhow::anyhow!(
2194                        "Column '{}' not found. Did you mean '{}'?",
2195                        column_name,
2196                        similar
2197                    ),
2198                    None => {
2199                        // Also list available columns for debugging
2200                        let available_cols = view.source().column_names().join(", ");
2201                        anyhow::anyhow!(
2202                            "Column '{}' not found. Available columns: {}",
2203                            column_name,
2204                            available_cols
2205                        )
2206                    }
2207                }
2208            })?;
2209
2210            let ascending = matches!(order_col.direction, SortDirection::Asc);
2211            sort_columns.push((col_index, ascending));
2212        }
2213
2214        // Apply multi-column sorting
2215        view.apply_multi_sort(&sort_columns)?;
2216        Ok(view)
2217    }
2218
2219    /// Apply GROUP BY to the view with optional HAVING clause
2220    fn apply_group_by(
2221        &self,
2222        view: DataView,
2223        group_by_exprs: &[SqlExpression],
2224        select_items: &[SelectItem],
2225        having: Option<&SqlExpression>,
2226        plan: &mut ExecutionPlanBuilder,
2227    ) -> Result<DataView> {
2228        // Use the new expression-based GROUP BY implementation
2229        let (result_view, phase_info) = self.apply_group_by_expressions(
2230            view,
2231            group_by_exprs,
2232            select_items,
2233            having,
2234            self.case_insensitive,
2235            self.date_notation.clone(),
2236        )?;
2237
2238        // Add detailed phase information to the execution plan
2239        plan.add_detail(format!("=== GROUP BY Phase Breakdown ==="));
2240        plan.add_detail(format!(
2241            "Phase 1 - Group Building: {:.3}ms",
2242            phase_info.phase2_key_building.as_secs_f64() * 1000.0
2243        ));
2244        plan.add_detail(format!(
2245            "  • Processing {} rows into {} groups",
2246            phase_info.total_rows, phase_info.num_groups
2247        ));
2248        plan.add_detail(format!(
2249            "Phase 2 - Aggregation: {:.3}ms",
2250            phase_info.phase4_aggregation.as_secs_f64() * 1000.0
2251        ));
2252        if phase_info.phase4_having_evaluation > Duration::ZERO {
2253            plan.add_detail(format!(
2254                "Phase 3 - HAVING Filter: {:.3}ms",
2255                phase_info.phase4_having_evaluation.as_secs_f64() * 1000.0
2256            ));
2257            plan.add_detail(format!(
2258                "  • Filtered {} groups",
2259                phase_info.groups_filtered_by_having
2260            ));
2261        }
2262        plan.add_detail(format!(
2263            "Total GROUP BY time: {:.3}ms",
2264            phase_info.total_time.as_secs_f64() * 1000.0
2265        ));
2266
2267        Ok(result_view)
2268    }
2269
2270    /// Estimate the cardinality (number of unique groups) for GROUP BY operations
2271    /// This helps pre-size hash tables for better performance
2272    pub fn estimate_group_cardinality(
2273        &self,
2274        view: &DataView,
2275        group_by_exprs: &[SqlExpression],
2276    ) -> usize {
2277        // If we have few rows, just return the row count as upper bound
2278        let row_count = view.get_visible_rows().len();
2279        if row_count <= 100 {
2280            return row_count;
2281        }
2282
2283        // Sample first 1000 rows or 10% of data, whichever is smaller
2284        let sample_size = min(1000, row_count / 10).max(100);
2285        let mut seen = FxHashSet::default();
2286
2287        let visible_rows = view.get_visible_rows();
2288        for (i, &row_idx) in visible_rows.iter().enumerate() {
2289            if i >= sample_size {
2290                break;
2291            }
2292
2293            // Evaluate GROUP BY expressions for this row
2294            let mut key_values = Vec::new();
2295            for expr in group_by_exprs {
2296                let mut evaluator = ArithmeticEvaluator::new(view.source());
2297                let value = evaluator.evaluate(expr, row_idx).unwrap_or(DataValue::Null);
2298                key_values.push(value);
2299            }
2300
2301            seen.insert(key_values);
2302        }
2303
2304        // Estimate total cardinality based on sample
2305        let sample_cardinality = seen.len();
2306        let estimated = (sample_cardinality * row_count) / sample_size;
2307
2308        // Cap at row count and ensure minimum of sample cardinality
2309        estimated.min(row_count).max(sample_cardinality)
2310    }
2311}
2312
2313#[cfg(test)]
2314mod tests {
2315    use super::*;
2316    use crate::data::datatable::{DataColumn, DataRow, DataValue};
2317
2318    fn create_test_table() -> Arc<DataTable> {
2319        let mut table = DataTable::new("test");
2320
2321        // Add columns
2322        table.add_column(DataColumn::new("id"));
2323        table.add_column(DataColumn::new("name"));
2324        table.add_column(DataColumn::new("age"));
2325
2326        // Add rows
2327        table
2328            .add_row(DataRow::new(vec![
2329                DataValue::Integer(1),
2330                DataValue::String("Alice".to_string()),
2331                DataValue::Integer(30),
2332            ]))
2333            .unwrap();
2334
2335        table
2336            .add_row(DataRow::new(vec![
2337                DataValue::Integer(2),
2338                DataValue::String("Bob".to_string()),
2339                DataValue::Integer(25),
2340            ]))
2341            .unwrap();
2342
2343        table
2344            .add_row(DataRow::new(vec![
2345                DataValue::Integer(3),
2346                DataValue::String("Charlie".to_string()),
2347                DataValue::Integer(35),
2348            ]))
2349            .unwrap();
2350
2351        Arc::new(table)
2352    }
2353
2354    #[test]
2355    fn test_select_all() {
2356        let table = create_test_table();
2357        let engine = QueryEngine::new();
2358
2359        let view = engine
2360            .execute(table.clone(), "SELECT * FROM users")
2361            .unwrap();
2362        assert_eq!(view.row_count(), 3);
2363        assert_eq!(view.column_count(), 3);
2364    }
2365
2366    #[test]
2367    fn test_select_columns() {
2368        let table = create_test_table();
2369        let engine = QueryEngine::new();
2370
2371        let view = engine
2372            .execute(table.clone(), "SELECT name, age FROM users")
2373            .unwrap();
2374        assert_eq!(view.row_count(), 3);
2375        assert_eq!(view.column_count(), 2);
2376    }
2377
2378    #[test]
2379    fn test_select_with_limit() {
2380        let table = create_test_table();
2381        let engine = QueryEngine::new();
2382
2383        let view = engine
2384            .execute(table.clone(), "SELECT * FROM users LIMIT 2")
2385            .unwrap();
2386        assert_eq!(view.row_count(), 2);
2387    }
2388
2389    #[test]
2390    fn test_type_coercion_contains() {
2391        // Initialize tracing for debug output
2392        let _ = tracing_subscriber::fmt()
2393            .with_max_level(tracing::Level::DEBUG)
2394            .try_init();
2395
2396        let mut table = DataTable::new("test");
2397        table.add_column(DataColumn::new("id"));
2398        table.add_column(DataColumn::new("status"));
2399        table.add_column(DataColumn::new("price"));
2400
2401        // Add test data with mixed types
2402        table
2403            .add_row(DataRow::new(vec![
2404                DataValue::Integer(1),
2405                DataValue::String("Pending".to_string()),
2406                DataValue::Float(99.99),
2407            ]))
2408            .unwrap();
2409
2410        table
2411            .add_row(DataRow::new(vec![
2412                DataValue::Integer(2),
2413                DataValue::String("Confirmed".to_string()),
2414                DataValue::Float(150.50),
2415            ]))
2416            .unwrap();
2417
2418        table
2419            .add_row(DataRow::new(vec![
2420                DataValue::Integer(3),
2421                DataValue::String("Pending".to_string()),
2422                DataValue::Float(75.00),
2423            ]))
2424            .unwrap();
2425
2426        let table = Arc::new(table);
2427        let engine = QueryEngine::new();
2428
2429        println!("\n=== Testing WHERE clause with Contains ===");
2430        println!("Table has {} rows", table.row_count());
2431        for i in 0..table.row_count() {
2432            let status = table.get_value(i, 1);
2433            println!("Row {i}: status = {status:?}");
2434        }
2435
2436        // Test 1: Basic string contains (should work)
2437        println!("\n--- Test 1: status.Contains('pend') ---");
2438        let result = engine.execute(
2439            table.clone(),
2440            "SELECT * FROM test WHERE status.Contains('pend')",
2441        );
2442        match result {
2443            Ok(view) => {
2444                println!("SUCCESS: Found {} matching rows", view.row_count());
2445                assert_eq!(view.row_count(), 2); // Should find both Pending rows
2446            }
2447            Err(e) => {
2448                panic!("Query failed: {e}");
2449            }
2450        }
2451
2452        // Test 2: Numeric contains (should work with type coercion)
2453        println!("\n--- Test 2: price.Contains('9') ---");
2454        let result = engine.execute(
2455            table.clone(),
2456            "SELECT * FROM test WHERE price.Contains('9')",
2457        );
2458        match result {
2459            Ok(view) => {
2460                println!(
2461                    "SUCCESS: Found {} matching rows with price containing '9'",
2462                    view.row_count()
2463                );
2464                // Should find 99.99 row
2465                assert!(view.row_count() >= 1);
2466            }
2467            Err(e) => {
2468                panic!("Numeric coercion query failed: {e}");
2469            }
2470        }
2471
2472        println!("\n=== All tests passed! ===");
2473    }
2474
2475    #[test]
2476    fn test_not_in_clause() {
2477        // Initialize tracing for debug output
2478        let _ = tracing_subscriber::fmt()
2479            .with_max_level(tracing::Level::DEBUG)
2480            .try_init();
2481
2482        let mut table = DataTable::new("test");
2483        table.add_column(DataColumn::new("id"));
2484        table.add_column(DataColumn::new("country"));
2485
2486        // Add test data
2487        table
2488            .add_row(DataRow::new(vec![
2489                DataValue::Integer(1),
2490                DataValue::String("CA".to_string()),
2491            ]))
2492            .unwrap();
2493
2494        table
2495            .add_row(DataRow::new(vec![
2496                DataValue::Integer(2),
2497                DataValue::String("US".to_string()),
2498            ]))
2499            .unwrap();
2500
2501        table
2502            .add_row(DataRow::new(vec![
2503                DataValue::Integer(3),
2504                DataValue::String("UK".to_string()),
2505            ]))
2506            .unwrap();
2507
2508        let table = Arc::new(table);
2509        let engine = QueryEngine::new();
2510
2511        println!("\n=== Testing NOT IN clause ===");
2512        println!("Table has {} rows", table.row_count());
2513        for i in 0..table.row_count() {
2514            let country = table.get_value(i, 1);
2515            println!("Row {i}: country = {country:?}");
2516        }
2517
2518        // Test NOT IN clause - should exclude CA, return US and UK (2 rows)
2519        println!("\n--- Test: country NOT IN ('CA') ---");
2520        let result = engine.execute(
2521            table.clone(),
2522            "SELECT * FROM test WHERE country NOT IN ('CA')",
2523        );
2524        match result {
2525            Ok(view) => {
2526                println!("SUCCESS: Found {} rows not in ('CA')", view.row_count());
2527                assert_eq!(view.row_count(), 2); // Should find US and UK
2528            }
2529            Err(e) => {
2530                panic!("NOT IN query failed: {e}");
2531            }
2532        }
2533
2534        println!("\n=== NOT IN test complete! ===");
2535    }
2536
2537    #[test]
2538    fn test_case_insensitive_in_and_not_in() {
2539        // Initialize tracing for debug output
2540        let _ = tracing_subscriber::fmt()
2541            .with_max_level(tracing::Level::DEBUG)
2542            .try_init();
2543
2544        let mut table = DataTable::new("test");
2545        table.add_column(DataColumn::new("id"));
2546        table.add_column(DataColumn::new("country"));
2547
2548        // Add test data with mixed case
2549        table
2550            .add_row(DataRow::new(vec![
2551                DataValue::Integer(1),
2552                DataValue::String("CA".to_string()), // uppercase
2553            ]))
2554            .unwrap();
2555
2556        table
2557            .add_row(DataRow::new(vec![
2558                DataValue::Integer(2),
2559                DataValue::String("us".to_string()), // lowercase
2560            ]))
2561            .unwrap();
2562
2563        table
2564            .add_row(DataRow::new(vec![
2565                DataValue::Integer(3),
2566                DataValue::String("UK".to_string()), // uppercase
2567            ]))
2568            .unwrap();
2569
2570        let table = Arc::new(table);
2571
2572        println!("\n=== Testing Case-Insensitive IN clause ===");
2573        println!("Table has {} rows", table.row_count());
2574        for i in 0..table.row_count() {
2575            let country = table.get_value(i, 1);
2576            println!("Row {i}: country = {country:?}");
2577        }
2578
2579        // Test case-insensitive IN - should match 'CA' with 'ca'
2580        println!("\n--- Test: country IN ('ca') with case_insensitive=true ---");
2581        let engine = QueryEngine::with_case_insensitive(true);
2582        let result = engine.execute(table.clone(), "SELECT * FROM test WHERE country IN ('ca')");
2583        match result {
2584            Ok(view) => {
2585                println!(
2586                    "SUCCESS: Found {} rows matching 'ca' (case-insensitive)",
2587                    view.row_count()
2588                );
2589                assert_eq!(view.row_count(), 1); // Should find CA row
2590            }
2591            Err(e) => {
2592                panic!("Case-insensitive IN query failed: {e}");
2593            }
2594        }
2595
2596        // Test case-insensitive NOT IN - should exclude 'CA' when searching for 'ca'
2597        println!("\n--- Test: country NOT IN ('ca') with case_insensitive=true ---");
2598        let result = engine.execute(
2599            table.clone(),
2600            "SELECT * FROM test WHERE country NOT IN ('ca')",
2601        );
2602        match result {
2603            Ok(view) => {
2604                println!(
2605                    "SUCCESS: Found {} rows not matching 'ca' (case-insensitive)",
2606                    view.row_count()
2607                );
2608                assert_eq!(view.row_count(), 2); // Should find us and UK rows
2609            }
2610            Err(e) => {
2611                panic!("Case-insensitive NOT IN query failed: {e}");
2612            }
2613        }
2614
2615        // Test case-sensitive (default) - should NOT match 'CA' with 'ca'
2616        println!("\n--- Test: country IN ('ca') with case_insensitive=false ---");
2617        let engine_case_sensitive = QueryEngine::new(); // defaults to case_insensitive=false
2618        let result = engine_case_sensitive
2619            .execute(table.clone(), "SELECT * FROM test WHERE country IN ('ca')");
2620        match result {
2621            Ok(view) => {
2622                println!(
2623                    "SUCCESS: Found {} rows matching 'ca' (case-sensitive)",
2624                    view.row_count()
2625                );
2626                assert_eq!(view.row_count(), 0); // Should find no rows (CA != ca)
2627            }
2628            Err(e) => {
2629                panic!("Case-sensitive IN query failed: {e}");
2630            }
2631        }
2632
2633        println!("\n=== Case-insensitive IN/NOT IN test complete! ===");
2634    }
2635
2636    #[test]
2637    #[ignore = "Parentheses in WHERE clause not yet implemented"]
2638    fn test_parentheses_in_where_clause() {
2639        // Initialize tracing for debug output
2640        let _ = tracing_subscriber::fmt()
2641            .with_max_level(tracing::Level::DEBUG)
2642            .try_init();
2643
2644        let mut table = DataTable::new("test");
2645        table.add_column(DataColumn::new("id"));
2646        table.add_column(DataColumn::new("status"));
2647        table.add_column(DataColumn::new("priority"));
2648
2649        // Add test data
2650        table
2651            .add_row(DataRow::new(vec![
2652                DataValue::Integer(1),
2653                DataValue::String("Pending".to_string()),
2654                DataValue::String("High".to_string()),
2655            ]))
2656            .unwrap();
2657
2658        table
2659            .add_row(DataRow::new(vec![
2660                DataValue::Integer(2),
2661                DataValue::String("Complete".to_string()),
2662                DataValue::String("High".to_string()),
2663            ]))
2664            .unwrap();
2665
2666        table
2667            .add_row(DataRow::new(vec![
2668                DataValue::Integer(3),
2669                DataValue::String("Pending".to_string()),
2670                DataValue::String("Low".to_string()),
2671            ]))
2672            .unwrap();
2673
2674        table
2675            .add_row(DataRow::new(vec![
2676                DataValue::Integer(4),
2677                DataValue::String("Complete".to_string()),
2678                DataValue::String("Low".to_string()),
2679            ]))
2680            .unwrap();
2681
2682        let table = Arc::new(table);
2683        let engine = QueryEngine::new();
2684
2685        println!("\n=== Testing Parentheses in WHERE clause ===");
2686        println!("Table has {} rows", table.row_count());
2687        for i in 0..table.row_count() {
2688            let status = table.get_value(i, 1);
2689            let priority = table.get_value(i, 2);
2690            println!("Row {i}: status = {status:?}, priority = {priority:?}");
2691        }
2692
2693        // Test OR with parentheses - should get (Pending AND High) OR (Complete AND Low)
2694        println!("\n--- Test: (status = 'Pending' AND priority = 'High') OR (status = 'Complete' AND priority = 'Low') ---");
2695        let result = engine.execute(
2696            table.clone(),
2697            "SELECT * FROM test WHERE (status = 'Pending' AND priority = 'High') OR (status = 'Complete' AND priority = 'Low')",
2698        );
2699        match result {
2700            Ok(view) => {
2701                println!(
2702                    "SUCCESS: Found {} rows with parenthetical logic",
2703                    view.row_count()
2704                );
2705                assert_eq!(view.row_count(), 2); // Should find rows 1 and 4
2706            }
2707            Err(e) => {
2708                panic!("Parentheses query failed: {e}");
2709            }
2710        }
2711
2712        println!("\n=== Parentheses test complete! ===");
2713    }
2714
2715    #[test]
2716    #[ignore = "Numeric type coercion needs fixing"]
2717    fn test_numeric_type_coercion() {
2718        // Initialize tracing for debug output
2719        let _ = tracing_subscriber::fmt()
2720            .with_max_level(tracing::Level::DEBUG)
2721            .try_init();
2722
2723        let mut table = DataTable::new("test");
2724        table.add_column(DataColumn::new("id"));
2725        table.add_column(DataColumn::new("price"));
2726        table.add_column(DataColumn::new("quantity"));
2727
2728        // Add test data with different numeric types
2729        table
2730            .add_row(DataRow::new(vec![
2731                DataValue::Integer(1),
2732                DataValue::Float(99.50), // Contains '.'
2733                DataValue::Integer(100),
2734            ]))
2735            .unwrap();
2736
2737        table
2738            .add_row(DataRow::new(vec![
2739                DataValue::Integer(2),
2740                DataValue::Float(150.0), // Contains '.' and '0'
2741                DataValue::Integer(200),
2742            ]))
2743            .unwrap();
2744
2745        table
2746            .add_row(DataRow::new(vec![
2747                DataValue::Integer(3),
2748                DataValue::Integer(75), // No decimal point
2749                DataValue::Integer(50),
2750            ]))
2751            .unwrap();
2752
2753        let table = Arc::new(table);
2754        let engine = QueryEngine::new();
2755
2756        println!("\n=== Testing Numeric Type Coercion ===");
2757        println!("Table has {} rows", table.row_count());
2758        for i in 0..table.row_count() {
2759            let price = table.get_value(i, 1);
2760            let quantity = table.get_value(i, 2);
2761            println!("Row {i}: price = {price:?}, quantity = {quantity:?}");
2762        }
2763
2764        // Test Contains on float values - should find rows with decimal points
2765        println!("\n--- Test: price.Contains('.') ---");
2766        let result = engine.execute(
2767            table.clone(),
2768            "SELECT * FROM test WHERE price.Contains('.')",
2769        );
2770        match result {
2771            Ok(view) => {
2772                println!(
2773                    "SUCCESS: Found {} rows with decimal points in price",
2774                    view.row_count()
2775                );
2776                assert_eq!(view.row_count(), 2); // Should find 99.50 and 150.0
2777            }
2778            Err(e) => {
2779                panic!("Numeric Contains query failed: {e}");
2780            }
2781        }
2782
2783        // Test Contains on integer values converted to string
2784        println!("\n--- Test: quantity.Contains('0') ---");
2785        let result = engine.execute(
2786            table.clone(),
2787            "SELECT * FROM test WHERE quantity.Contains('0')",
2788        );
2789        match result {
2790            Ok(view) => {
2791                println!(
2792                    "SUCCESS: Found {} rows with '0' in quantity",
2793                    view.row_count()
2794                );
2795                assert_eq!(view.row_count(), 2); // Should find 100 and 200
2796            }
2797            Err(e) => {
2798                panic!("Integer Contains query failed: {e}");
2799            }
2800        }
2801
2802        println!("\n=== Numeric type coercion test complete! ===");
2803    }
2804
2805    #[test]
2806    fn test_datetime_comparisons() {
2807        // Initialize tracing for debug output
2808        let _ = tracing_subscriber::fmt()
2809            .with_max_level(tracing::Level::DEBUG)
2810            .try_init();
2811
2812        let mut table = DataTable::new("test");
2813        table.add_column(DataColumn::new("id"));
2814        table.add_column(DataColumn::new("created_date"));
2815
2816        // Add test data with date strings (as they would come from CSV)
2817        table
2818            .add_row(DataRow::new(vec![
2819                DataValue::Integer(1),
2820                DataValue::String("2024-12-15".to_string()),
2821            ]))
2822            .unwrap();
2823
2824        table
2825            .add_row(DataRow::new(vec![
2826                DataValue::Integer(2),
2827                DataValue::String("2025-01-15".to_string()),
2828            ]))
2829            .unwrap();
2830
2831        table
2832            .add_row(DataRow::new(vec![
2833                DataValue::Integer(3),
2834                DataValue::String("2025-02-15".to_string()),
2835            ]))
2836            .unwrap();
2837
2838        let table = Arc::new(table);
2839        let engine = QueryEngine::new();
2840
2841        println!("\n=== Testing DateTime Comparisons ===");
2842        println!("Table has {} rows", table.row_count());
2843        for i in 0..table.row_count() {
2844            let date = table.get_value(i, 1);
2845            println!("Row {i}: created_date = {date:?}");
2846        }
2847
2848        // Test DateTime constructor comparison - should find dates after 2025-01-01
2849        println!("\n--- Test: created_date > DateTime(2025,1,1) ---");
2850        let result = engine.execute(
2851            table.clone(),
2852            "SELECT * FROM test WHERE created_date > DateTime(2025,1,1)",
2853        );
2854        match result {
2855            Ok(view) => {
2856                println!("SUCCESS: Found {} rows after 2025-01-01", view.row_count());
2857                assert_eq!(view.row_count(), 2); // Should find 2025-01-15 and 2025-02-15
2858            }
2859            Err(e) => {
2860                panic!("DateTime comparison query failed: {e}");
2861            }
2862        }
2863
2864        println!("\n=== DateTime comparison test complete! ===");
2865    }
2866
2867    #[test]
2868    fn test_not_with_method_calls() {
2869        // Initialize tracing for debug output
2870        let _ = tracing_subscriber::fmt()
2871            .with_max_level(tracing::Level::DEBUG)
2872            .try_init();
2873
2874        let mut table = DataTable::new("test");
2875        table.add_column(DataColumn::new("id"));
2876        table.add_column(DataColumn::new("status"));
2877
2878        // Add test data
2879        table
2880            .add_row(DataRow::new(vec![
2881                DataValue::Integer(1),
2882                DataValue::String("Pending Review".to_string()),
2883            ]))
2884            .unwrap();
2885
2886        table
2887            .add_row(DataRow::new(vec![
2888                DataValue::Integer(2),
2889                DataValue::String("Complete".to_string()),
2890            ]))
2891            .unwrap();
2892
2893        table
2894            .add_row(DataRow::new(vec![
2895                DataValue::Integer(3),
2896                DataValue::String("Pending Approval".to_string()),
2897            ]))
2898            .unwrap();
2899
2900        let table = Arc::new(table);
2901        let engine = QueryEngine::with_case_insensitive(true);
2902
2903        println!("\n=== Testing NOT with Method Calls ===");
2904        println!("Table has {} rows", table.row_count());
2905        for i in 0..table.row_count() {
2906            let status = table.get_value(i, 1);
2907            println!("Row {i}: status = {status:?}");
2908        }
2909
2910        // Test NOT with Contains - should exclude rows containing "pend"
2911        println!("\n--- Test: NOT status.Contains('pend') ---");
2912        let result = engine.execute(
2913            table.clone(),
2914            "SELECT * FROM test WHERE NOT status.Contains('pend')",
2915        );
2916        match result {
2917            Ok(view) => {
2918                println!(
2919                    "SUCCESS: Found {} rows NOT containing 'pend'",
2920                    view.row_count()
2921                );
2922                assert_eq!(view.row_count(), 1); // Should find only "Complete"
2923            }
2924            Err(e) => {
2925                panic!("NOT Contains query failed: {e}");
2926            }
2927        }
2928
2929        // Test NOT with StartsWith
2930        println!("\n--- Test: NOT status.StartsWith('Pending') ---");
2931        let result = engine.execute(
2932            table.clone(),
2933            "SELECT * FROM test WHERE NOT status.StartsWith('Pending')",
2934        );
2935        match result {
2936            Ok(view) => {
2937                println!(
2938                    "SUCCESS: Found {} rows NOT starting with 'Pending'",
2939                    view.row_count()
2940                );
2941                assert_eq!(view.row_count(), 1); // Should find only "Complete"
2942            }
2943            Err(e) => {
2944                panic!("NOT StartsWith query failed: {e}");
2945            }
2946        }
2947
2948        println!("\n=== NOT with method calls test complete! ===");
2949    }
2950
2951    #[test]
2952    #[ignore = "Complex logical expressions with parentheses not yet implemented"]
2953    fn test_complex_logical_expressions() {
2954        // Initialize tracing for debug output
2955        let _ = tracing_subscriber::fmt()
2956            .with_max_level(tracing::Level::DEBUG)
2957            .try_init();
2958
2959        let mut table = DataTable::new("test");
2960        table.add_column(DataColumn::new("id"));
2961        table.add_column(DataColumn::new("status"));
2962        table.add_column(DataColumn::new("priority"));
2963        table.add_column(DataColumn::new("assigned"));
2964
2965        // Add comprehensive test data
2966        table
2967            .add_row(DataRow::new(vec![
2968                DataValue::Integer(1),
2969                DataValue::String("Pending".to_string()),
2970                DataValue::String("High".to_string()),
2971                DataValue::String("John".to_string()),
2972            ]))
2973            .unwrap();
2974
2975        table
2976            .add_row(DataRow::new(vec![
2977                DataValue::Integer(2),
2978                DataValue::String("Complete".to_string()),
2979                DataValue::String("High".to_string()),
2980                DataValue::String("Jane".to_string()),
2981            ]))
2982            .unwrap();
2983
2984        table
2985            .add_row(DataRow::new(vec![
2986                DataValue::Integer(3),
2987                DataValue::String("Pending".to_string()),
2988                DataValue::String("Low".to_string()),
2989                DataValue::String("John".to_string()),
2990            ]))
2991            .unwrap();
2992
2993        table
2994            .add_row(DataRow::new(vec![
2995                DataValue::Integer(4),
2996                DataValue::String("In Progress".to_string()),
2997                DataValue::String("Medium".to_string()),
2998                DataValue::String("Jane".to_string()),
2999            ]))
3000            .unwrap();
3001
3002        let table = Arc::new(table);
3003        let engine = QueryEngine::new();
3004
3005        println!("\n=== Testing Complex Logical Expressions ===");
3006        println!("Table has {} rows", table.row_count());
3007        for i in 0..table.row_count() {
3008            let status = table.get_value(i, 1);
3009            let priority = table.get_value(i, 2);
3010            let assigned = table.get_value(i, 3);
3011            println!(
3012                "Row {i}: status = {status:?}, priority = {priority:?}, assigned = {assigned:?}"
3013            );
3014        }
3015
3016        // Test complex AND/OR logic
3017        println!("\n--- Test: status = 'Pending' AND (priority = 'High' OR assigned = 'John') ---");
3018        let result = engine.execute(
3019            table.clone(),
3020            "SELECT * FROM test WHERE status = 'Pending' AND (priority = 'High' OR assigned = 'John')",
3021        );
3022        match result {
3023            Ok(view) => {
3024                println!(
3025                    "SUCCESS: Found {} rows with complex logic",
3026                    view.row_count()
3027                );
3028                assert_eq!(view.row_count(), 2); // Should find rows 1 and 3 (both Pending, one High priority, both assigned to John)
3029            }
3030            Err(e) => {
3031                panic!("Complex logic query failed: {e}");
3032            }
3033        }
3034
3035        // Test NOT with complex expressions
3036        println!("\n--- Test: NOT (status.Contains('Complete') OR priority = 'Low') ---");
3037        let result = engine.execute(
3038            table.clone(),
3039            "SELECT * FROM test WHERE NOT (status.Contains('Complete') OR priority = 'Low')",
3040        );
3041        match result {
3042            Ok(view) => {
3043                println!(
3044                    "SUCCESS: Found {} rows with NOT complex logic",
3045                    view.row_count()
3046                );
3047                assert_eq!(view.row_count(), 2); // Should find rows 1 (Pending+High) and 4 (In Progress+Medium)
3048            }
3049            Err(e) => {
3050                panic!("NOT complex logic query failed: {e}");
3051            }
3052        }
3053
3054        println!("\n=== Complex logical expressions test complete! ===");
3055    }
3056
3057    #[test]
3058    fn test_mixed_data_types_and_edge_cases() {
3059        // Initialize tracing for debug output
3060        let _ = tracing_subscriber::fmt()
3061            .with_max_level(tracing::Level::DEBUG)
3062            .try_init();
3063
3064        let mut table = DataTable::new("test");
3065        table.add_column(DataColumn::new("id"));
3066        table.add_column(DataColumn::new("value"));
3067        table.add_column(DataColumn::new("nullable_field"));
3068
3069        // Add test data with mixed types and edge cases
3070        table
3071            .add_row(DataRow::new(vec![
3072                DataValue::Integer(1),
3073                DataValue::String("123.45".to_string()),
3074                DataValue::String("present".to_string()),
3075            ]))
3076            .unwrap();
3077
3078        table
3079            .add_row(DataRow::new(vec![
3080                DataValue::Integer(2),
3081                DataValue::Float(678.90),
3082                DataValue::Null,
3083            ]))
3084            .unwrap();
3085
3086        table
3087            .add_row(DataRow::new(vec![
3088                DataValue::Integer(3),
3089                DataValue::Boolean(true),
3090                DataValue::String("also present".to_string()),
3091            ]))
3092            .unwrap();
3093
3094        table
3095            .add_row(DataRow::new(vec![
3096                DataValue::Integer(4),
3097                DataValue::String("false".to_string()),
3098                DataValue::Null,
3099            ]))
3100            .unwrap();
3101
3102        let table = Arc::new(table);
3103        let engine = QueryEngine::new();
3104
3105        println!("\n=== Testing Mixed Data Types and Edge Cases ===");
3106        println!("Table has {} rows", table.row_count());
3107        for i in 0..table.row_count() {
3108            let value = table.get_value(i, 1);
3109            let nullable = table.get_value(i, 2);
3110            println!("Row {i}: value = {value:?}, nullable_field = {nullable:?}");
3111        }
3112
3113        // Test type coercion with boolean Contains
3114        println!("\n--- Test: value.Contains('true') (boolean to string coercion) ---");
3115        let result = engine.execute(
3116            table.clone(),
3117            "SELECT * FROM test WHERE value.Contains('true')",
3118        );
3119        match result {
3120            Ok(view) => {
3121                println!(
3122                    "SUCCESS: Found {} rows with boolean coercion",
3123                    view.row_count()
3124                );
3125                assert_eq!(view.row_count(), 1); // Should find the boolean true row
3126            }
3127            Err(e) => {
3128                panic!("Boolean coercion query failed: {e}");
3129            }
3130        }
3131
3132        // Test multiple IN values with mixed types
3133        println!("\n--- Test: id IN (1, 3) ---");
3134        let result = engine.execute(table.clone(), "SELECT * FROM test WHERE id IN (1, 3)");
3135        match result {
3136            Ok(view) => {
3137                println!("SUCCESS: Found {} rows with IN clause", view.row_count());
3138                assert_eq!(view.row_count(), 2); // Should find rows with id 1 and 3
3139            }
3140            Err(e) => {
3141                panic!("Multiple IN values query failed: {e}");
3142            }
3143        }
3144
3145        println!("\n=== Mixed data types test complete! ===");
3146    }
3147
3148    /// Test that aggregate-only queries return exactly one row (regression test)
3149    #[test]
3150    fn test_aggregate_only_single_row() {
3151        let table = create_test_stock_data();
3152        let engine = QueryEngine::new();
3153
3154        // Test query with multiple aggregates - should return exactly 1 row
3155        let result = engine
3156            .execute(
3157                table.clone(),
3158                "SELECT COUNT(*), MIN(close), MAX(close), AVG(close) FROM stock",
3159            )
3160            .expect("Query should succeed");
3161
3162        assert_eq!(
3163            result.row_count(),
3164            1,
3165            "Aggregate-only query should return exactly 1 row"
3166        );
3167        assert_eq!(result.column_count(), 4, "Should have 4 aggregate columns");
3168
3169        // Verify the actual values are correct
3170        let source = result.source();
3171        let row = source.get_row(0).expect("Should have first row");
3172
3173        // COUNT(*) should be 5 (total rows)
3174        assert_eq!(row.values[0], DataValue::Integer(5));
3175
3176        // MIN should be 99.5
3177        assert_eq!(row.values[1], DataValue::Float(99.5));
3178
3179        // MAX should be 105.0
3180        assert_eq!(row.values[2], DataValue::Float(105.0));
3181
3182        // AVG should be approximately 102.4
3183        if let DataValue::Float(avg) = &row.values[3] {
3184            assert!(
3185                (avg - 102.4).abs() < 0.01,
3186                "Average should be approximately 102.4, got {}",
3187                avg
3188            );
3189        } else {
3190            panic!("AVG should return a Float value");
3191        }
3192    }
3193
3194    /// Test single aggregate function returns single row
3195    #[test]
3196    fn test_single_aggregate_single_row() {
3197        let table = create_test_stock_data();
3198        let engine = QueryEngine::new();
3199
3200        let result = engine
3201            .execute(table.clone(), "SELECT COUNT(*) FROM stock")
3202            .expect("Query should succeed");
3203
3204        assert_eq!(
3205            result.row_count(),
3206            1,
3207            "Single aggregate query should return exactly 1 row"
3208        );
3209        assert_eq!(result.column_count(), 1, "Should have 1 column");
3210
3211        let source = result.source();
3212        let row = source.get_row(0).expect("Should have first row");
3213        assert_eq!(row.values[0], DataValue::Integer(5));
3214    }
3215
3216    /// Test aggregate with WHERE clause filtering
3217    #[test]
3218    fn test_aggregate_with_where_single_row() {
3219        let table = create_test_stock_data();
3220        let engine = QueryEngine::new();
3221
3222        // Filter to only high-value stocks (>= 103.0) and aggregate
3223        let result = engine
3224            .execute(
3225                table.clone(),
3226                "SELECT COUNT(*), MIN(close), MAX(close) FROM stock WHERE close >= 103.0",
3227            )
3228            .expect("Query should succeed");
3229
3230        assert_eq!(
3231            result.row_count(),
3232            1,
3233            "Filtered aggregate query should return exactly 1 row"
3234        );
3235        assert_eq!(result.column_count(), 3, "Should have 3 aggregate columns");
3236
3237        let source = result.source();
3238        let row = source.get_row(0).expect("Should have first row");
3239
3240        // Should find 2 rows (103.5 and 105.0)
3241        assert_eq!(row.values[0], DataValue::Integer(2));
3242        assert_eq!(row.values[1], DataValue::Float(103.5)); // MIN
3243        assert_eq!(row.values[2], DataValue::Float(105.0)); // MAX
3244    }
3245
3246    #[test]
3247    fn test_not_in_parsing() {
3248        use crate::sql::recursive_parser::Parser;
3249
3250        let query = "SELECT * FROM test WHERE country NOT IN ('CA')";
3251        println!("\n=== Testing NOT IN parsing ===");
3252        println!("Parsing query: {query}");
3253
3254        let mut parser = Parser::new(query);
3255        match parser.parse() {
3256            Ok(statement) => {
3257                println!("Parsed statement: {statement:#?}");
3258                if let Some(where_clause) = statement.where_clause {
3259                    println!("WHERE conditions: {:#?}", where_clause.conditions);
3260                    if let Some(first_condition) = where_clause.conditions.first() {
3261                        println!("First condition expression: {:#?}", first_condition.expr);
3262                    }
3263                }
3264            }
3265            Err(e) => {
3266                panic!("Parse error: {e}");
3267            }
3268        }
3269    }
3270
3271    /// Create test stock data for aggregate testing
3272    fn create_test_stock_data() -> Arc<DataTable> {
3273        let mut table = DataTable::new("stock");
3274
3275        table.add_column(DataColumn::new("symbol"));
3276        table.add_column(DataColumn::new("close"));
3277        table.add_column(DataColumn::new("volume"));
3278
3279        // Add 5 rows of test data
3280        let test_data = vec![
3281            ("AAPL", 99.5, 1000),
3282            ("AAPL", 101.2, 1500),
3283            ("AAPL", 103.5, 2000),
3284            ("AAPL", 105.0, 1200),
3285            ("AAPL", 102.8, 1800),
3286        ];
3287
3288        for (symbol, close, volume) in test_data {
3289            table
3290                .add_row(DataRow::new(vec![
3291                    DataValue::String(symbol.to_string()),
3292                    DataValue::Float(close),
3293                    DataValue::Integer(volume),
3294                ]))
3295                .expect("Should add row successfully");
3296        }
3297
3298        Arc::new(table)
3299    }
3300}
3301
3302#[cfg(test)]
3303#[path = "query_engine_tests.rs"]
3304mod query_engine_tests;