Skip to main content

tegdb/
query_processor.rs

1//! Modern query processor for TegDB with native row format support
2//!
3//! This module provides the core query execution engine that works directly with the
4//! native binary row format for optimal performance.
5
6use crate::catalog::IndexInfo;
7use crate::parser::{
8    ColumnConstraint, Condition, CreateTableStatement, DataType, DropTableStatement, Expression,
9    IndexType, OrderDirection, SqlValue,
10};
11
12use crate::storage_engine::Transaction;
13use crate::storage_format::StorageFormat;
14use crate::{Error, Result};
15use std::collections::HashMap;
16use std::rc::Rc;
17
18/// Type alias for scan iterator to reduce complexity
19type ScanIterator<'a> = Box<dyn Iterator<Item = (Vec<u8>, std::rc::Rc<[u8]>)> + 'a>;
20
21/// Native primary key types that avoid string conversion
22#[derive(Debug, Clone)]
23pub enum NativeKey {
24    Integer(i64),
25    Real(f64),
26    Text(String),
27    Vector(Vec<f64>),
28    Null,
29}
30
31impl NativeKey {
32    /// Convert SqlValue to NativeKey (zero-copy where possible)
33    pub fn from_sql_value(value: &SqlValue) -> Result<Self> {
34        match value {
35            SqlValue::Integer(i) => Ok(NativeKey::Integer(*i)),
36            SqlValue::Real(r) => Ok(NativeKey::Real(*r)),
37            SqlValue::Text(t) => Ok(NativeKey::Text(t.clone())), // Only clone needed
38            SqlValue::Vector(v) => Ok(NativeKey::Vector(v.clone())), // Clone needed for vector
39            SqlValue::Null => Ok(NativeKey::Null),
40            SqlValue::Parameter(_) => Err(Error::SqlError(
41                "Parameter placeholder found in key generation - parameter binding failed"
42                    .to_string(),
43            )),
44        }
45    }
46
47    /// Serialize to bytes for storage (efficient binary format)
48    pub fn to_bytes(&self) -> Vec<u8> {
49        match self {
50            NativeKey::Integer(i) => {
51                // Pre-allocate exact size to avoid reallocations
52                let mut bytes = Vec::with_capacity(9);
53                bytes.push(0x01); // Type tag for Integer
54                bytes.extend_from_slice(&i.to_be_bytes()); // Use big-endian for correct ordering
55                bytes
56            }
57            NativeKey::Real(r) => {
58                // Pre-allocate exact size to avoid reallocations
59                let mut bytes = Vec::with_capacity(9);
60                bytes.push(0x02); // Type tag for Real
61                bytes.extend_from_slice(&r.to_be_bytes()); // Use big-endian for correct ordering
62                bytes
63            }
64            NativeKey::Text(t) => {
65                // Pre-allocate exact size to avoid reallocations
66                let mut bytes = Vec::with_capacity(5 + t.len());
67                bytes.push(0x03); // Type tag for Text
68                bytes.extend_from_slice(&(t.len() as u32).to_le_bytes());
69                bytes.extend_from_slice(t.as_bytes());
70                bytes
71            }
72            NativeKey::Vector(v) => {
73                // Pre-allocate exact size to avoid reallocations
74                let mut bytes = Vec::with_capacity(5 + v.len() * 8);
75                bytes.push(0x04); // Type tag for Vector
76                bytes.extend_from_slice(&(v.len() as u32).to_le_bytes());
77                for &val in v {
78                    bytes.extend_from_slice(&val.to_be_bytes()); // Use big-endian for correct ordering
79                }
80                bytes
81            }
82            NativeKey::Null => {
83                vec![0x00] // Type tag for Null
84            }
85        }
86    }
87}
88
89/// High-level primary key that combines table name with native key
90#[derive(Debug, Clone)]
91pub struct PrimaryKey {
92    table_name: String,
93    key: NativeKey,
94}
95
96impl PrimaryKey {
97    /// Create a new primary key
98    pub fn new(table_name: String, key: NativeKey) -> Self {
99        Self { table_name, key }
100    }
101
102    /// Serialize to storage bytes (efficient binary format)
103    pub fn to_storage_bytes(&self) -> Vec<u8> {
104        // Pre-allocate with exact capacity to avoid reallocations
105        let mut bytes = Vec::with_capacity(4 + self.table_name.len() + 1 + 9); // table_len + table + separator + key
106        bytes.extend_from_slice(&(self.table_name.len() as u32).to_le_bytes());
107        bytes.extend_from_slice(self.table_name.as_bytes());
108        bytes.push(crate::catalog::STORAGE_SEPARATOR); // Separator
109        bytes.extend_from_slice(&self.key.to_bytes());
110        bytes
111    }
112
113    /// Create range start key (for range scans)
114    pub fn range_start(table_name: &str, start_key: &NativeKey, inclusive: bool) -> Self {
115        let mut pk = Self::new(table_name.to_string(), start_key.clone());
116        if !inclusive {
117            // For exclusive bounds, we need to increment the key
118            // This ensures we start after the specified value
119            match &mut pk.key {
120                NativeKey::Integer(i) => *i += 1,
121                NativeKey::Real(r) => *r += f64::EPSILON,
122                NativeKey::Text(s) => {
123                    // For text, append a character that sorts after the current string
124                    s.push('\u{10FFFF}'); // Highest Unicode character
125                }
126                NativeKey::Vector(v) => {
127                    // For vectors, add a small epsilon to the first element
128                    if !v.is_empty() {
129                        v[0] += f64::EPSILON;
130                    }
131                }
132                NativeKey::Null => {
133                    // For null, we can't increment, so we'll use a special marker
134                    pk.key = NativeKey::Text("".to_string());
135                }
136            }
137        }
138        pk
139    }
140
141    /// Create range end key (for range scans)
142    pub fn range_end(table_name: &str, end_key: &NativeKey, inclusive: bool) -> Self {
143        let mut pk = Self::new(table_name.to_string(), end_key.clone());
144        match &mut pk.key {
145            NativeKey::Integer(i) => {
146                if inclusive {
147                    *i += 1;
148                }
149                // else: leave as is for exclusive
150            }
151            NativeKey::Real(r) => {
152                if inclusive {
153                    *r = f64::from_bits(r.to_bits() + 1); // next representable float
154                }
155                // else: leave as is for exclusive
156            }
157            NativeKey::Text(s) => {
158                if inclusive {
159                    s.push('\u{10FFFF}');
160                }
161                // else: leave as is for exclusive
162            }
163            NativeKey::Vector(v) => {
164                if inclusive && !v.is_empty() {
165                    v[0] = f64::from_bits(v[0].to_bits() + 1); // next representable float
166                }
167                // else: leave as is for exclusive
168            }
169            NativeKey::Null => {
170                pk.key = NativeKey::Text("".to_string());
171            }
172        }
173        pk
174    }
175
176    /// Create table prefix for full table scans
177    pub fn table_prefix(table_name: &str) -> Vec<u8> {
178        // Pre-allocate with exact capacity to avoid reallocations
179        let mut bytes = Vec::with_capacity(4 + table_name.len() + 1);
180        bytes.extend_from_slice(&(table_name.len() as u32).to_le_bytes());
181        bytes.extend_from_slice(table_name.as_bytes());
182        bytes.push(crate::catalog::STORAGE_SEPARATOR); // Separator
183        bytes
184    }
185
186    /// Create table end marker for full table scans
187    pub fn table_end_marker(table_name: &str) -> Vec<u8> {
188        // Pre-allocate with exact capacity to avoid reallocations
189        let mut bytes = Vec::with_capacity(4 + table_name.len() + 1);
190        bytes.extend_from_slice(&(table_name.len() as u32).to_le_bytes());
191        bytes.extend_from_slice(table_name.as_bytes());
192        bytes.push(crate::catalog::TABLE_END_SENTINEL); // End marker
193        bytes
194    }
195}
196
197/// Column information for table schema with embedded storage metadata
198#[derive(Debug, Clone)]
199pub struct ColumnInfo {
200    pub name: String,
201    pub data_type: DataType,
202    pub constraints: Vec<ColumnConstraint>,
203    // Embedded storage metadata for ultra-fast access
204    pub storage_offset: usize,
205    pub storage_size: usize,
206    pub storage_type_code: u8,
207}
208
209/// Table schema definition
210#[derive(Debug, Clone)]
211pub struct TableSchema {
212    pub name: String,
213    pub columns: Vec<ColumnInfo>,
214    pub indexes: Vec<IndexInfo>,
215}
216
217/// Optimized schema validation methods
218impl TableSchema {
219    /// Check if a column exists in this schema (optimized with early return)
220    pub fn has_column(&self, column_name: &str) -> bool {
221        self.columns.iter().any(|col| col.name == column_name)
222    }
223
224    /// Get column index by name (optimized with early return)
225    pub fn get_column_index(&self, column_name: &str) -> Option<usize> {
226        self.columns.iter().position(|col| col.name == column_name)
227    }
228
229    /// Get primary key column name (cached lookup)
230    pub fn get_primary_key_column(&self) -> Option<&str> {
231        // Use find() which stops at first match
232        self.columns
233            .iter()
234            .find(|col| col.constraints.contains(&ColumnConstraint::PrimaryKey))
235            .map(|col| col.name.as_str())
236    }
237
238    /// Check if a column is required (NOT NULL or PRIMARY KEY) - optimized
239    pub fn is_column_required(&self, column_name: &str) -> bool {
240        // Use find() which stops at first match
241        self.columns
242            .iter()
243            .find(|col| col.name == column_name)
244            .map(|col| {
245                col.constraints.contains(&ColumnConstraint::NotNull)
246                    || col.constraints.contains(&ColumnConstraint::PrimaryKey)
247            })
248            .unwrap_or(false)
249    }
250
251    /// Get all column names as a vector
252    pub fn get_column_names(&self) -> Vec<&str> {
253        self.columns.iter().map(|col| col.name.as_str()).collect()
254    }
255
256    /// Get column by name (optimized)
257    pub fn get_column(&self, column_name: &str) -> Option<&ColumnInfo> {
258        self.columns.iter().find(|col| col.name == column_name)
259    }
260}
261
262/// Query schema for fast column access
263#[derive(Clone, Debug)]
264pub struct QuerySchema {
265    pub column_names: Vec<String>,
266    pub column_indices: Vec<usize>,
267    pub expressions: Option<Vec<Expression>>, // New field for expressions
268}
269
270impl QuerySchema {
271    pub fn new(selected_columns: &[String], schema: &TableSchema) -> Self {
272        let mut column_indices = Vec::new();
273        for column_name in selected_columns {
274            if let Some(index) = schema.get_column_index(column_name) {
275                column_indices.push(index);
276            } else {
277                // For expressions or non-existent columns, use a placeholder index
278                column_indices.push(0);
279            }
280        }
281        Self {
282            column_names: selected_columns.to_vec(),
283            column_indices,
284            expressions: None,
285        }
286    }
287
288    pub fn new_with_expressions(
289        selected_columns: &[crate::parser::Expression],
290        schema: &TableSchema,
291    ) -> Self {
292        let mut column_names = Vec::new();
293        let mut column_indices = Vec::new();
294        let mut expressions = Vec::new();
295
296        for (i, expr) in selected_columns.iter().enumerate() {
297            match expr {
298                crate::parser::Expression::Column(name) => {
299                    // Special case: "*" is not a real column, treat as expression
300                    if name == "*" {
301                        column_names.push(format!("expr_{i}"));
302                        column_indices.push(0); // Placeholder for expressions
303                        expressions.push(expr.clone());
304                    } else {
305                        // This is a regular column
306                        column_names.push(name.clone());
307                        if let Some(index) = schema.get_column_index(name) {
308                            column_indices.push(index);
309                        } else {
310                            column_indices.push(0); // Placeholder
311                        }
312                        expressions.push(expr.clone());
313                    }
314                }
315                _ => {
316                    // This is an expression (function call, etc.)
317                    column_names.push(format!("expr_{i}"));
318                    column_indices.push(0); // Placeholder for expressions
319                    expressions.push(expr.clone());
320                }
321            }
322        }
323
324        Self {
325            column_names,
326            column_indices,
327            expressions: Some(expressions),
328        }
329    }
330}
331
332/// Streaming iterator for SELECT query results
333/// This provides a streaming interface that yields rows on-demand
334pub struct SelectRowIterator<'a> {
335    /// Iterator over the scan results
336    scan_iter: ScanIterator<'a>,
337    /// Schema for deserializing rows
338    schema: std::rc::Rc<TableSchema>,
339    /// Query schema for fast column access
340    query_schema: QuerySchema,
341    /// Optional filter condition
342    filter: Option<Condition>,
343    /// Storage format for deserialization
344    storage_format: StorageFormat,
345    /// Optional limit on number of rows
346    limit: Option<u64>,
347    /// Current count of yielded rows
348    count: u64,
349    /// Aggregate mode - if Some, contains the aggregate result to return
350    aggregate_result: Option<Vec<SqlValue>>,
351    /// Sorted mode - if Some, contains the sorted results to return
352    sorted_results: Option<std::vec::IntoIter<Vec<SqlValue>>>,
353    /// Optional extension registry for custom functions
354    extensions: Option<&'a crate::extension::ExtensionRegistry>,
355}
356
357impl<'a> SelectRowIterator<'a> {
358    /// Create a new select row iterator
359    pub fn new(
360        scan_iter: ScanIterator<'a>,
361        schema: std::rc::Rc<TableSchema>,
362        query_schema: QuerySchema,
363        filter: Option<Condition>,
364        limit: Option<u64>,
365    ) -> Self {
366        let storage_format = StorageFormat::new();
367
368        Self {
369            scan_iter,
370            schema,
371            query_schema,
372            filter,
373            storage_format,
374            limit,
375            count: 0,
376            aggregate_result: None,
377            sorted_results: None,
378            extensions: None,
379        }
380    }
381
382    /// Create a new select row iterator with extension support
383    pub fn new_with_extensions(
384        scan_iter: ScanIterator<'a>,
385        schema: std::rc::Rc<TableSchema>,
386        query_schema: QuerySchema,
387        filter: Option<Condition>,
388        limit: Option<u64>,
389        extensions: &'a crate::extension::ExtensionRegistry,
390    ) -> Self {
391        let storage_format = StorageFormat::new();
392
393        Self {
394            scan_iter,
395            schema,
396            query_schema,
397            filter,
398            storage_format,
399            limit,
400            count: 0,
401            aggregate_result: None,
402            sorted_results: None,
403            extensions: Some(extensions),
404        }
405    }
406
407    /// Set extensions for this iterator (builder pattern)
408    pub fn with_extensions(
409        mut self,
410        extensions: Option<&'a crate::extension::ExtensionRegistry>,
411    ) -> Self {
412        self.extensions = extensions;
413        self
414    }
415
416    /// Collect all remaining rows into a Vec for backward compatibility
417    /// Optimized to reduce memory allocations and copying
418    pub fn collect_rows(self) -> Result<Vec<Vec<SqlValue>>> {
419        // Use collect() which is already optimized by the standard library
420        // The iterator will yield rows one by one, avoiding large memmove operations
421        self.collect()
422    }
423
424    fn evaluate_expression(
425        expression: &Expression,
426        row_data: &HashMap<String, SqlValue>,
427        _row_bytes: &[u8],
428        extensions: Option<&crate::extension::ExtensionRegistry>,
429    ) -> Result<SqlValue> {
430        match expression {
431            Expression::Value(value) => Ok(value.clone()),
432            Expression::Column(column_name) => row_data
433                .get(column_name)
434                .cloned()
435                .ok_or_else(|| crate::Error::Other(format!("Column '{column_name}' not found"))),
436            Expression::BinaryOp {
437                left,
438                operator,
439                right,
440            } => {
441                let left_val = Self::evaluate_expression(left, row_data, _row_bytes, extensions)?;
442                let right_val = Self::evaluate_expression(right, row_data, _row_bytes, extensions)?;
443
444                match (left_val, right_val) {
445                    (SqlValue::Integer(a), SqlValue::Integer(b)) => {
446                        let result = match operator {
447                            crate::parser::ArithmeticOperator::Add => a + b,
448                            crate::parser::ArithmeticOperator::Subtract => a - b,
449                            crate::parser::ArithmeticOperator::Multiply => a * b,
450                            crate::parser::ArithmeticOperator::Divide => {
451                                if b == 0 {
452                                    return Err(crate::Error::Other(format!(
453                                        "Division by zero in expression: {a} / {b}"
454                                    )));
455                                }
456                                a / b
457                            }
458                            crate::parser::ArithmeticOperator::Modulo => {
459                                if b == 0 {
460                                    return Err(crate::Error::Other(format!(
461                                        "Modulo by zero in expression: {a} % {b}"
462                                    )));
463                                }
464                                a % b
465                            }
466                        };
467                        Ok(SqlValue::Integer(result))
468                    }
469                    (SqlValue::Real(a), SqlValue::Real(b)) => {
470                        let result = match operator {
471                            crate::parser::ArithmeticOperator::Add => a + b,
472                            crate::parser::ArithmeticOperator::Subtract => a - b,
473                            crate::parser::ArithmeticOperator::Multiply => a * b,
474                            crate::parser::ArithmeticOperator::Divide => {
475                                if b == 0.0 {
476                                    return Err(crate::Error::Other(format!(
477                                        "Division by zero in expression: {a} / {b}"
478                                    )));
479                                }
480                                a / b
481                            }
482                            crate::parser::ArithmeticOperator::Modulo => {
483                                if b == 0.0 {
484                                    return Err(crate::Error::Other(format!(
485                                        "Modulo by zero in expression: {a} % {b}"
486                                    )));
487                                }
488                                a % b
489                            }
490                        };
491                        Ok(SqlValue::Real(result))
492                    }
493                    // Support mixed types: Integer + Real
494                    (SqlValue::Integer(a), SqlValue::Real(b)) => {
495                        let a_f64 = a as f64;
496                        let result = match operator {
497                            crate::parser::ArithmeticOperator::Add => a_f64 + b,
498                            crate::parser::ArithmeticOperator::Subtract => a_f64 - b,
499                            crate::parser::ArithmeticOperator::Multiply => a_f64 * b,
500                            crate::parser::ArithmeticOperator::Divide => {
501                                if b == 0.0 {
502                                    return Err(crate::Error::Other(format!(
503                                        "Division by zero in expression: {a} / {b}"
504                                    )));
505                                }
506                                a_f64 / b
507                            }
508                            crate::parser::ArithmeticOperator::Modulo => {
509                                if b == 0.0 {
510                                    return Err(crate::Error::Other(format!(
511                                        "Modulo by zero in expression: {a} % {b}"
512                                    )));
513                                }
514                                a_f64 % b
515                            }
516                        };
517                        Ok(SqlValue::Real(result))
518                    }
519                    // Support mixed types: Real + Integer
520                    (SqlValue::Real(a), SqlValue::Integer(b)) => {
521                        let b_f64 = b as f64;
522                        let result = match operator {
523                            crate::parser::ArithmeticOperator::Add => a + b_f64,
524                            crate::parser::ArithmeticOperator::Subtract => a - b_f64,
525                            crate::parser::ArithmeticOperator::Multiply => a * b_f64,
526                            crate::parser::ArithmeticOperator::Divide => {
527                                if b_f64 == 0.0 {
528                                    return Err(crate::Error::Other(format!(
529                                        "Division by zero in expression: {a} / {b}"
530                                    )));
531                                }
532                                a / b_f64
533                            }
534                            crate::parser::ArithmeticOperator::Modulo => {
535                                if b_f64 == 0.0 {
536                                    return Err(crate::Error::Other(format!(
537                                        "Modulo by zero in expression: {a} % {b}"
538                                    )));
539                                }
540                                a % b_f64
541                            }
542                        };
543                        Ok(SqlValue::Real(result))
544                    }
545                    _ => Err(crate::Error::Other(format!(
546                        "Unsupported operation for mixed types: {operator:?}"
547                    ))),
548                }
549            }
550            Expression::FunctionCall { name, args } => {
551                // Evaluate all arguments first
552                let evaluated_args: Result<Vec<SqlValue>> = args
553                    .iter()
554                    .map(|arg| Self::evaluate_expression(arg, row_data, _row_bytes, extensions))
555                    .collect();
556                let evaluated_args = evaluated_args?;
557
558                // Check if this is an extension function
559                if let Some(ext_registry) = extensions {
560                    if ext_registry.has_scalar_function(name) {
561                        return ext_registry
562                            .execute_scalar(name, &evaluated_args)
563                            .map_err(|e| {
564                                crate::Error::Other(format!("Extension function error: {e}"))
565                            });
566                    }
567                }
568
569                // Fall back to built-in functions
570                // Create expression values for the built-in evaluate
571                let expr_args: Vec<Expression> =
572                    evaluated_args.into_iter().map(Expression::Value).collect();
573
574                let func_call = Expression::FunctionCall {
575                    name: name.clone(),
576                    args: expr_args,
577                };
578
579                // Evaluate the function call using the Expression::evaluate method
580                func_call
581                    .evaluate(row_data)
582                    .map_err(|e| crate::Error::Other(format!("Function evaluation error: {e}")))
583            }
584            Expression::AggregateFunction { name, arg } => {
585                // For now, we'll evaluate the argument but not perform aggregation
586                // This will be handled by the query processor during execution
587                let _arg_value = Self::evaluate_expression(arg, row_data, _row_bytes, extensions)?;
588                match name.to_uppercase().as_str() {
589                    "COUNT" => Ok(SqlValue::Integer(1)), // Placeholder
590                    "SUM" => Ok(SqlValue::Integer(0)),   // Placeholder
591                    "AVG" => Ok(SqlValue::Real(0.0)),    // Placeholder
592                    "MAX" => Ok(SqlValue::Integer(0)),   // Placeholder
593                    "MIN" => Ok(SqlValue::Integer(0)),   // Placeholder
594                    _ => Err(crate::Error::Other(format!(
595                        "Aggregate function '{name}' is not implemented. Supported functions: COUNT, SUM, AVG, MAX, MIN"
596                    ))),
597                }
598            }
599        }
600    }
601}
602
603impl<'a> Iterator for SelectRowIterator<'a> {
604    type Item = Result<Vec<SqlValue>>;
605
606    fn next(&mut self) -> Option<Self::Item> {
607        // Handle aggregate result mode
608        if let Some(ref aggregate_result) = self.aggregate_result {
609            if self.count == 0 {
610                self.count += 1;
611                return Some(Ok(aggregate_result.clone()));
612            } else {
613                return None;
614            }
615        }
616
617        // Handle sorted results mode
618        if let Some(ref mut sorted_iter) = self.sorted_results {
619            if let Some(row) = sorted_iter.next() {
620                self.count += 1;
621                return Some(Ok(row));
622            } else {
623                return None;
624            }
625        }
626
627        // Check limit
628        if let Some(limit) = self.limit {
629            if self.count >= limit {
630                return None;
631            }
632        }
633
634        // Process rows until we find one that matches the filter
635        for (_, value) in self.scan_iter.by_ref() {
636            // Check if we need to apply a filter
637            let matches = if let Some(ref filter) = self.filter {
638                // Use cached metadata for ultra-fast condition evaluation
639                match self.storage_format.matches_condition_with_metadata(
640                    &value,
641                    &self.schema,
642                    filter,
643                ) {
644                    Ok(matches) => matches,
645                    Err(_) => {
646                        return Some(Err(Error::Other(
647                            "Failed to evaluate condition".to_string(),
648                        )))
649                    }
650                }
651            } else {
652                true // No filter, so it matches
653            };
654
655            if matches {
656                // Use cached metadata for ultra-fast column access
657                let row_values_result = self.storage_format.get_columns_by_indices_with_metadata(
658                    &value,
659                    &self.schema,
660                    &self.query_schema.column_indices,
661                );
662
663                match row_values_result {
664                    Ok(row_values) => {
665                        // If we have expressions, evaluate them
666                        let final_values = if let Some(ref expressions) =
667                            self.query_schema.expressions
668                        {
669                            // Expression case: evaluate each expression
670                            let mut final_values = Vec::new();
671
672                            // Create row data for expression evaluation
673                            let mut row_data = HashMap::new();
674                            for (i, &col_idx) in self.query_schema.column_indices.iter().enumerate()
675                            {
676                                if let Some(col_name) =
677                                    self.schema.columns.get(col_idx).map(|c| &c.name)
678                                {
679                                    if i < row_values.len() {
680                                        row_data.insert(col_name.clone(), row_values[i].clone());
681                                    }
682                                }
683                            }
684
685                            // Evaluate each expression
686                            for expr in expressions {
687                                match Self::evaluate_expression(
688                                    expr,
689                                    &row_data,
690                                    &value,
691                                    self.extensions,
692                                ) {
693                                    Ok(value) => final_values.push(value),
694                                    Err(e) => return Some(Err(e)),
695                                }
696                            }
697                            final_values
698                        } else {
699                            // Standard case: column names match row values
700                            row_values
701                        };
702
703                        self.count += 1;
704                        return Some(Ok(final_values));
705                    }
706                    Err(e) => return Some(Err(e)),
707                }
708            }
709            // If row doesn't match filter, continue to next row
710        }
711
712        // No more matching rows found
713        None
714    }
715}
716
717impl<'a> std::fmt::Debug for SelectRowIterator<'a> {
718    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
719        f.debug_struct("SelectRowIterator")
720            .field("schema", &self.schema.name)
721            .field("selected_columns", &self.query_schema.column_names)
722            .field("filter", &self.filter)
723            .field("limit", &self.limit)
724            .field("count", &self.count)
725            .finish()
726    }
727}
728
729/// Query execution result
730#[derive(Debug)]
731pub enum ResultSet<'a> {
732    /// SELECT query result with streaming support
733    Select {
734        columns: Vec<String>,
735        rows: Box<SelectRowIterator<'a>>,
736    },
737    /// INSERT query result
738    Insert { rows_affected: usize },
739    /// UPDATE query result
740    Update { rows_affected: usize },
741    /// DELETE query result
742    Delete { rows_affected: usize },
743    /// CREATE TABLE query result
744    CreateTable,
745    /// DROP TABLE query result
746    DropTable,
747    /// Transaction BEGIN result
748    Begin,
749    /// Transaction COMMIT result
750    Commit,
751    /// Transaction ROLLBACK result
752    Rollback,
753    /// CREATE INDEX result
754    CreateIndex,
755    /// DROP INDEX result
756    DropIndex,
757    /// CREATE EXTENSION result
758    CreateExtension,
759    /// DROP EXTENSION result
760    DropExtension,
761}
762
763impl<'a> ResultSet<'a> {
764    // No methods needed - columns() is provided by QueryResult in database.rs
765}
766
767impl TableSchema {
768    // Storage metadata is now embedded in columns, no separate computation needed
769}
770
771/// SQL query processor with native row format support
772pub struct QueryProcessor<'a> {
773    transaction: Transaction<'a>,
774    table_schemas: HashMap<String, Rc<TableSchema>>,
775    storage_format: StorageFormat,
776    transaction_active: bool,
777    extensions: Option<&'a crate::extension::ExtensionRegistry>,
778}
779
780impl<'a> QueryProcessor<'a> {
781    /// Create a new query processor with transaction and Rc schemas (optimized)
782    pub fn new_with_rc_schemas(
783        transaction: Transaction<'a>,
784        table_schemas: HashMap<String, Rc<TableSchema>>,
785    ) -> Self {
786        Self {
787            transaction,
788            table_schemas,
789            storage_format: StorageFormat::new(), // Always use native format
790            transaction_active: false,
791            extensions: None,
792        }
793    }
794
795    /// Create a new query processor with transaction, schemas, and extension support
796    pub fn new_with_extensions(
797        transaction: Transaction<'a>,
798        table_schemas: HashMap<String, Rc<TableSchema>>,
799        extensions: &'a crate::extension::ExtensionRegistry,
800    ) -> Self {
801        Self {
802            transaction,
803            table_schemas,
804            storage_format: StorageFormat::new(),
805            transaction_active: false,
806            extensions: Some(extensions),
807        }
808    }
809
810    /// Get mutable reference to the transaction
811    pub fn transaction_mut(&mut self) -> &mut Transaction<'a> {
812        &mut self.transaction
813    }
814
815    /// Get table schema by name
816    fn get_table_schema(&self, table_name: &str) -> Result<Rc<TableSchema>> {
817        self.table_schemas
818            .get(table_name)
819            .cloned()
820            .ok_or_else(|| Error::TableNotFound(table_name.to_string()))
821    }
822
823    /// Validate row data against table schema
824    fn validate_row_data(
825        &self,
826        table_name: &str,
827        row_data: &HashMap<String, SqlValue>,
828    ) -> Result<()> {
829        let schema = self.get_table_schema(table_name)?;
830
831        // Check that all provided columns exist
832        for column_name in row_data.keys() {
833            if !schema.has_column(column_name) {
834                let available_columns = schema.get_column_names().join(", ");
835                return Err(Error::ColumnNotFound(format!(
836                    "Column '{column_name}' does not exist in table '{table_name}'. Available columns: {available_columns}"
837                )));
838            }
839        }
840
841        // Check that all required columns are provided
842        for col in &schema.columns {
843            if schema.is_column_required(&col.name) {
844                match row_data.get(&col.name) {
845                    None => {
846                        let col_name = &col.name;
847                        return Err(Error::SqlError(format!(
848                            "Required column '{col_name}' is missing for table '{table_name}'"
849                        )));
850                    }
851                    Some(SqlValue::Null) => {
852                        let col_name = &col.name;
853                        return Err(Error::SqlError(format!(
854                            "Column '{col_name}' in table '{table_name}' does not allow NULL values"
855                        )));
856                    }
857                    Some(_) => {}
858                }
859            }
860        }
861
862        Ok(())
863    }
864
865    /// Execute CREATE TABLE statement
866    pub fn execute_create_table(&mut self, create: CreateTableStatement) -> Result<ResultSet<'_>> {
867        // Validate that we don't have composite primary keys
868        let pk_count = create
869            .columns
870            .iter()
871            .filter(|col| col.constraints.contains(&ColumnConstraint::PrimaryKey))
872            .count();
873
874        if pk_count > 1 {
875            let table_name = &create.table;
876            return Err(Error::SqlError(format!(
877                "Table '{table_name}' has composite primary key, but TegDB only supports single-column primary keys"
878            )));
879        }
880
881        if pk_count == 0 {
882            let table_name = &create.table;
883            return Err(Error::SqlError(format!(
884                "Table '{table_name}' must have exactly one primary key column"
885            )));
886        }
887
888        // Convert to internal schema format
889        let columns: Vec<ColumnInfo> = create
890            .columns
891            .iter()
892            .map(|col| ColumnInfo {
893                name: col.name.clone(),
894                data_type: col.data_type.clone(),
895                constraints: col.constraints.clone(),
896                storage_offset: 0,    // Placeholder, will be set later
897                storage_size: 0,      // Placeholder, will be set later
898                storage_type_code: 0, // Placeholder, will be set later
899            })
900            .collect();
901
902        let mut schema = TableSchema {
903            name: create.table.clone(),
904            columns,
905            indexes: vec![], // Initialize indexes as empty
906        };
907        // Compute storage metadata and persist schema via central serializer
908        let _ = crate::catalog::Catalog::compute_table_metadata(&mut schema);
909        let schema_key = crate::catalog::Catalog::get_schema_storage_key(&create.table);
910        let schema_data = crate::catalog::Catalog::serialize_schema_to_bytes(&schema);
911        self.transaction.set(schema_key.as_bytes(), schema_data)?;
912
913        // Add to in-memory schemas and validation cache
914        let schema_rc = Rc::new(schema.clone());
915        self.table_schemas.insert(create.table.clone(), schema_rc);
916
917        Ok(ResultSet::CreateTable)
918    }
919
920    /// Execute DROP TABLE statement
921    pub fn execute_drop_table(&mut self, drop: DropTableStatement) -> Result<ResultSet<'_>> {
922        // Check if table exists
923        let table_existed = self.table_schemas.contains_key(&drop.table);
924
925        if !drop.if_exists && !table_existed {
926            let table_name = &drop.table;
927            let available_tables = self
928                .table_schemas
929                .keys()
930                .cloned()
931                .collect::<Vec<_>>()
932                .join(", ");
933            return Err(Error::TableNotFound(format!(
934                "Table '{table_name}' does not exist. Available tables: {available_tables}"
935            )));
936        }
937
938        if table_existed {
939            // Delete schema metadata
940            let schema_key = crate::catalog::Catalog::get_schema_storage_key(&drop.table);
941            self.transaction.delete(schema_key.as_bytes())?;
942
943            // Delete all table data using canonical key range helpers
944            let start_key = PrimaryKey::table_prefix(&drop.table);
945            let end_key = PrimaryKey::table_end_marker(&drop.table);
946
947            let keys_to_delete: Vec<_> = self
948                .transaction
949                .scan(start_key..end_key)?
950                .map(|(key, _)| key)
951                .collect();
952
953            for key in keys_to_delete {
954                self.transaction.delete(&key)?;
955            }
956
957            // Remove from local schema cache
958            self.table_schemas.remove(&drop.table);
959        }
960
961        Ok(ResultSet::DropTable)
962    }
963
964    /// Execute CREATE INDEX statement
965    pub fn execute_create_index(
966        &mut self,
967        create: crate::parser::CreateIndexStatement,
968    ) -> Result<ResultSet<'_>> {
969        // Check if table exists
970        if !self.table_schemas.contains_key(&create.table_name) {
971            let table_name = &create.table_name;
972            let available_tables = self
973                .table_schemas
974                .keys()
975                .cloned()
976                .collect::<Vec<_>>()
977                .join(", ");
978            return Err(Error::TableNotFound(format!(
979                "Table '{table_name}' does not exist. Available tables: {available_tables}"
980            )));
981        }
982
983        // Check if column exists in the table
984        let schema = self.get_table_schema(&create.table_name)?;
985        if !schema.has_column(&create.column_name) {
986            let column_name = &create.column_name;
987            let table_name = &create.table_name;
988            let available_columns = schema.get_column_names().join(", ");
989            return Err(Error::ColumnNotFound(format!(
990                "Column '{column_name}' does not exist in table '{table_name}'. Available columns: {available_columns}"
991            )));
992        }
993
994        // Check if index already exists
995        if schema
996            .indexes
997            .iter()
998            .any(|idx| idx.name == create.index_name)
999        {
1000            let index_name = &create.index_name;
1001            return Err(Error::SqlError(format!(
1002                "Index '{index_name}' already exists"
1003            )));
1004        }
1005
1006        let column_info = schema
1007            .get_column(&create.column_name)
1008            .ok_or_else(|| Error::ColumnNotFound(create.column_name.clone()))?;
1009
1010        let requested_index_type = create.index_type.unwrap_or({
1011            if matches!(column_info.data_type, DataType::Vector(_)) {
1012                IndexType::HNSW
1013            } else {
1014                IndexType::BTree
1015            }
1016        });
1017
1018        // Enforce compatibility between column data type, uniqueness, and index type
1019        match (&column_info.data_type, requested_index_type) {
1020            (DataType::Vector(_), IndexType::BTree) => {
1021                return Err(Error::Other(
1022                    "BTree indexes are not supported on VECTOR columns".to_string(),
1023                ));
1024            }
1025            (DataType::Vector(_), _) => {
1026                if create.unique {
1027                    return Err(Error::Other(
1028                        "Unique constraints are not supported on vector indexes".to_string(),
1029                    ));
1030                }
1031            }
1032            (_, IndexType::HNSW | IndexType::IVF | IndexType::LSH) => {
1033                return Err(Error::Other(format!(
1034                    "Index type '{requested_index_type:?}' requires a VECTOR column"
1035                )));
1036            }
1037            _ => {}
1038        }
1039
1040        // Create index info
1041        let index = crate::catalog::IndexInfo {
1042            name: create.index_name.clone(),
1043            table_name: create.table_name.clone(),
1044            column_name: create.column_name.clone(),
1045            unique: create.unique,
1046            index_type: requested_index_type,
1047        };
1048
1049        // Store index metadata
1050        let index_key = crate::catalog::Catalog::get_index_storage_key(&create.index_name);
1051        let index_data = crate::catalog::Catalog::serialize_index_to_bytes(&index);
1052        self.transaction.set(index_key.as_bytes(), index_data)?;
1053
1054        // Add to in-memory schema
1055        let mut schema = schema.as_ref().clone();
1056        schema.indexes.push(index.clone());
1057        self.table_schemas
1058            .insert(create.table_name.clone(), Rc::new(schema));
1059
1060        // Populate the index with existing data (only needed for BTree indexes currently)
1061        if matches!(requested_index_type, IndexType::BTree) {
1062            self.populate_index_with_existing_data(&create.table_name, &index)?;
1063        }
1064
1065        Ok(ResultSet::CreateIndex)
1066    }
1067
1068    /// Execute DROP INDEX statement
1069    pub fn execute_drop_index(
1070        &mut self,
1071        drop: crate::parser::DropIndexStatement,
1072    ) -> Result<ResultSet<'_>> {
1073        // Find the index in any table
1074        let mut found = false;
1075        for (table_name, schema_rc) in &self.table_schemas {
1076            let schema = schema_rc.as_ref();
1077            if schema.indexes.iter().any(|idx| idx.name == drop.index_name) {
1078                found = true;
1079
1080                // Remove index metadata from storage
1081                let index_key = crate::catalog::Catalog::get_index_storage_key(&drop.index_name);
1082                self.transaction.delete(index_key.as_bytes())?;
1083
1084                // Remove from in-memory schema
1085                let mut new_schema = schema.clone();
1086                if let Some(pos) = new_schema
1087                    .indexes
1088                    .iter()
1089                    .position(|idx| idx.name == drop.index_name)
1090                {
1091                    let index_info = new_schema.indexes.remove(pos);
1092
1093                    if matches!(index_info.index_type, IndexType::BTree) {
1094                        let (range_start, range_end) =
1095                            crate::catalog::index_full_range(table_name, &index_info.name);
1096                        let keys: Vec<Vec<u8>> = self
1097                            .transaction
1098                            .scan(range_start..range_end)?
1099                            .map(|(key, _)| key)
1100                            .collect();
1101                        for key in keys {
1102                            self.transaction.delete(&key)?;
1103                        }
1104                    }
1105                }
1106                self.table_schemas
1107                    .insert(table_name.clone(), Rc::new(new_schema));
1108                break;
1109            }
1110        }
1111
1112        if !found && !drop.if_exists {
1113            let index_name = &drop.index_name;
1114            return Err(Error::Other(format!("Index '{index_name}' does not exist")));
1115        }
1116
1117        Ok(ResultSet::DropIndex)
1118    }
1119
1120    /// Begin transaction
1121    pub fn begin_transaction(&mut self) -> Result<ResultSet<'_>> {
1122        if self.transaction_active {
1123            return Err(Error::Other(
1124                "Transaction already active. Nested transactions are not supported.".to_string(),
1125            ));
1126        }
1127
1128        self.transaction_active = true;
1129        Ok(ResultSet::Begin)
1130    }
1131
1132    /// Commit transaction
1133    pub fn commit_transaction(&mut self) -> Result<ResultSet<'_>> {
1134        if !self.transaction_active {
1135            return Err(Error::Other("No active transaction to commit".to_string()));
1136        }
1137
1138        self.transaction_active = false;
1139        Ok(ResultSet::Commit)
1140    }
1141
1142    /// Rollback transaction
1143    pub fn rollback_transaction(&mut self) -> Result<ResultSet<'_>> {
1144        if !self.transaction_active {
1145            return Err(Error::Other(
1146                "No active transaction to rollback".to_string(),
1147            ));
1148        }
1149
1150        self.transaction_active = false;
1151        Ok(ResultSet::Rollback)
1152    }
1153
1154    /// Execute a query execution plan
1155    pub fn execute_plan(&mut self, plan: crate::planner::ExecutionPlan) -> Result<ResultSet<'_>> {
1156        use crate::planner::ExecutionPlan;
1157
1158        match plan {
1159            // For SELECT operations, use streaming execution and collect results
1160            ExecutionPlan::PrimaryKeyLookup { .. }
1161            | ExecutionPlan::TableRangeScan { .. }
1162            | ExecutionPlan::TableScan { .. }
1163            | ExecutionPlan::IndexScan { .. }
1164            | ExecutionPlan::VectorSearch { .. } => self.execute_select_plan_streaming(plan),
1165            ExecutionPlan::Sort {
1166                input_plan,
1167                order_by_items,
1168                schema,
1169                query_schema,
1170                limit,
1171            } => {
1172                // For ORDER BY, we need to get the full row data to sort by columns not in SELECT
1173                // We need to extract the full rows from the input plan, not just the selected columns
1174                let full_rows = match &*input_plan {
1175                    ExecutionPlan::TableScan { table, filter, .. } => {
1176                        let start_key = PrimaryKey::table_prefix(table);
1177                        let end_key = PrimaryKey::table_end_marker(table);
1178                        let scan_iter = self.transaction.scan(start_key..end_key)?;
1179                        let table_schema = self.get_table_schema(table)?;
1180
1181                        let mut rows = Vec::new();
1182                        for (_, value) in scan_iter {
1183                            // Apply filter if present
1184                            let matches = if let Some(ref filter_condition) = filter {
1185                                match self.storage_format.matches_condition_with_metadata(
1186                                    &value,
1187                                    &table_schema,
1188                                    filter_condition,
1189                                ) {
1190                                    Ok(matches) => matches,
1191                                    Err(_) => continue, // Skip rows that don't match filter
1192                                }
1193                            } else {
1194                                true // No filter, so it matches
1195                            };
1196
1197                            if matches {
1198                                // Get the full row data
1199                                let row_values =
1200                                    self.storage_format.get_columns_by_indices_with_metadata(
1201                                        &value,
1202                                        &table_schema,
1203                                        &(0..table_schema.columns.len()).collect::<Vec<_>>(),
1204                                    )?;
1205                                rows.push(row_values);
1206                            }
1207                        }
1208                        rows
1209                    }
1210                    ExecutionPlan::VectorSearch { table, .. } => {
1211                        // For VectorSearch, we need to get the full rows to sort properly
1212                        let start_key = PrimaryKey::table_prefix(table);
1213                        let end_key = PrimaryKey::table_end_marker(table);
1214                        let scan_iter = self.transaction.scan(start_key..end_key)?;
1215                        let table_schema = self.get_table_schema(table)?;
1216
1217                        let mut rows = Vec::new();
1218                        for (_, value) in scan_iter {
1219                            // Get the full row data
1220                            let row_values =
1221                                self.storage_format.get_columns_by_indices_with_metadata(
1222                                    &value,
1223                                    &table_schema,
1224                                    &(0..table_schema.columns.len()).collect::<Vec<_>>(),
1225                                )?;
1226                            rows.push(row_values);
1227                        }
1228                        rows
1229                    }
1230                    _ => {
1231                        // For other plan types, fall back to materialized execution
1232                        self.execute_plan_materialized(*input_plan.clone())?
1233                    }
1234                };
1235
1236                // Create a mapping from full row to selected columns
1237                let mut row_mapping: Vec<(Vec<SqlValue>, Vec<SqlValue>)> = Vec::new();
1238                for full_row in full_rows {
1239                    // Extract selected columns from full row
1240                    let mut selected_values = Vec::new();
1241                    for col_name in &query_schema.column_names {
1242                        if let Some(col_idx) =
1243                            schema.columns.iter().position(|c| c.name == *col_name)
1244                        {
1245                            if col_idx < full_row.len() {
1246                                selected_values.push(full_row[col_idx].clone());
1247                            }
1248                        }
1249                    }
1250                    row_mapping.push((full_row, selected_values));
1251                }
1252
1253                // Sort the full rows based on order_by_items
1254                row_mapping.sort_by(|(a_full, _), (b_full, _)| {
1255                    for item in &order_by_items {
1256                        if let Expression::Column(column_name) = &item.expression {
1257                            if let Some(col_idx) =
1258                                schema.columns.iter().position(|c| c.name == *column_name)
1259                            {
1260                                if col_idx < a_full.len() && col_idx < b_full.len() {
1261                                    let cmp = match (&a_full[col_idx], &b_full[col_idx]) {
1262                                        (SqlValue::Integer(a), SqlValue::Integer(b)) => a.cmp(b),
1263                                        (SqlValue::Real(a), SqlValue::Real(b)) => {
1264                                            a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
1265                                        }
1266                                        (SqlValue::Text(a), SqlValue::Text(b)) => a.cmp(b),
1267                                        (SqlValue::Vector(a), SqlValue::Vector(b)) => a
1268                                            .iter()
1269                                            .zip(b.iter())
1270                                            .map(|(x, y)| {
1271                                                x.partial_cmp(y)
1272                                                    .unwrap_or(std::cmp::Ordering::Equal)
1273                                            })
1274                                            .find(|&ord| ord != std::cmp::Ordering::Equal)
1275                                            .unwrap_or_else(|| a.len().cmp(&b.len())),
1276                                        (SqlValue::Null, SqlValue::Null) => {
1277                                            std::cmp::Ordering::Equal
1278                                        }
1279                                        (SqlValue::Null, _) => std::cmp::Ordering::Less,
1280                                        (_, SqlValue::Null) => std::cmp::Ordering::Greater,
1281                                        _ => std::cmp::Ordering::Equal,
1282                                    };
1283
1284                                    if cmp != std::cmp::Ordering::Equal {
1285                                        return match item.direction {
1286                                            OrderDirection::Asc => cmp,
1287                                            OrderDirection::Desc => cmp.reverse(),
1288                                        };
1289                                    }
1290                                }
1291                            }
1292                        }
1293                    }
1294                    std::cmp::Ordering::Equal
1295                });
1296
1297                // Extract the sorted selected columns
1298                let mut sorted_rows: Vec<Vec<SqlValue>> = row_mapping
1299                    .into_iter()
1300                    .map(|(_, selected)| selected)
1301                    .collect();
1302
1303                // Apply LIMIT if specified
1304                if let Some(limit) = limit {
1305                    sorted_rows.truncate(limit as usize);
1306                }
1307
1308                // Create a SelectRowIterator with sorted results
1309                let mut sorted_iter = SelectRowIterator::new(
1310                    Box::new(std::iter::empty::<(Vec<u8>, std::rc::Rc<[u8]>)>()),
1311                    schema,
1312                    query_schema.clone(),
1313                    None,
1314                    None,
1315                )
1316                .with_extensions(self.extensions);
1317                sorted_iter.sorted_results = Some(sorted_rows.into_iter());
1318
1319                Ok(ResultSet::Select {
1320                    columns: query_schema.column_names.clone(),
1321                    rows: Box::new(sorted_iter),
1322                })
1323            }
1324            // Non-SELECT operations remain the same
1325            ExecutionPlan::Insert {
1326                table,
1327                rows,
1328                conflict_resolution: _,
1329            } => self.execute_insert_plan(&table, &rows),
1330            ExecutionPlan::Update {
1331                table,
1332                assignments,
1333                scan_plan,
1334            } => self.execute_update_plan(&table, &assignments, *scan_plan),
1335            ExecutionPlan::Delete { table, scan_plan } => {
1336                self.execute_delete_plan(&table, *scan_plan)
1337            }
1338            ExecutionPlan::CreateTable { table, schema } => {
1339                self.execute_create_table_plan(&table, &schema)
1340            }
1341            ExecutionPlan::DropTable { table, if_exists } => {
1342                self.execute_drop_table_plan(&table, if_exists)
1343            }
1344            ExecutionPlan::CreateIndex {
1345                index_name,
1346                table_name,
1347                column_name,
1348                unique,
1349            } => {
1350                let create_stmt = crate::parser::CreateIndexStatement {
1351                    index_name,
1352                    table_name,
1353                    column_name,
1354                    unique,
1355                    index_type: None, // Default to BTree for now
1356                };
1357                self.execute_create_index(create_stmt)
1358            }
1359            ExecutionPlan::DropIndex {
1360                index_name,
1361                if_exists,
1362            } => {
1363                let drop_stmt = crate::parser::DropIndexStatement {
1364                    index_name,
1365                    if_exists,
1366                };
1367                self.execute_drop_index(drop_stmt)
1368            }
1369            ExecutionPlan::CreateExtension { .. } | ExecutionPlan::DropExtension { .. } => {
1370                // Extension DDL must be handled by Database with access to ExtensionRegistry and Catalog
1371                Err(Error::Other(
1372                    "Extension DDL operations must be handled by Database layer".to_string(),
1373                ))
1374            }
1375            ExecutionPlan::Begin => self.begin_transaction(),
1376            ExecutionPlan::Commit => self.commit_transaction(),
1377            ExecutionPlan::Rollback => self.rollback_transaction(),
1378        }
1379    }
1380
1381    /// Execute CREATE EXTENSION plan
1382    /// This method is called from Database which has access to ExtensionRegistry and Catalog
1383    pub fn execute_create_extension_plan(
1384        &mut self,
1385        name: &str,
1386        library_path: Option<&str>,
1387        extensions: &mut crate::extension::ExtensionRegistry,
1388        catalog: &mut crate::catalog::Catalog,
1389        extension_factory: &crate::extension::ExtensionFactory,
1390    ) -> Result<ResultSet<'_>> {
1391        // Check if extension already exists
1392        if extensions.has_extension(name) {
1393            return Err(Error::Other(format!("Extension '{}' already exists", name)));
1394        }
1395
1396        // Load extension
1397        let extension = if let Some(path) = library_path {
1398            extension_factory.load_from_path(std::path::Path::new(path))?
1399        } else {
1400            extension_factory
1401                .load_from_name(name)
1402                .map_err(|e| Error::Other(e.to_string()))?
1403        };
1404
1405        // Register extension
1406        extensions
1407            .register(extension)
1408            .map_err(|e| Error::Other(e.to_string()))?;
1409
1410        // Store in catalog via transaction
1411        let ext_key = crate::catalog::Catalog::get_extension_storage_key(name);
1412        let value = library_path
1413            .map(|p| p.as_bytes().to_vec())
1414            .unwrap_or_else(|| b"builtin".to_vec());
1415        self.transaction.set(ext_key.as_bytes(), value)?;
1416
1417        // Also update catalog in-memory tracking (for future use)
1418        catalog.add_extension(name.to_string(), library_path.map(|s| s.to_string()));
1419
1420        Ok(ResultSet::CreateExtension)
1421    }
1422
1423    /// Execute DROP EXTENSION plan
1424    /// This method is called from Database which has access to ExtensionRegistry and Catalog
1425    pub fn execute_drop_extension_plan(
1426        &mut self,
1427        name: &str,
1428        extensions: &mut crate::extension::ExtensionRegistry,
1429        catalog: &mut crate::catalog::Catalog,
1430    ) -> Result<ResultSet<'_>> {
1431        // Check if extension exists
1432        if !extensions.has_extension(name) {
1433            return Err(Error::Other(format!("Extension '{}' does not exist", name)));
1434        }
1435
1436        // Unregister extension
1437        extensions
1438            .unregister(name)
1439            .map_err(|e| Error::Other(e.to_string()))?;
1440
1441        // Remove from catalog via transaction
1442        let ext_key = crate::catalog::Catalog::get_extension_storage_key(name);
1443        self.transaction.delete(ext_key.as_bytes())?;
1444
1445        // Also update catalog in-memory tracking (for future use)
1446        catalog.remove_extension(name);
1447
1448        Ok(ResultSet::DropExtension)
1449    }
1450
1451    /// Check if the selected columns contain aggregate functions
1452    fn has_aggregate_functions(&self, selected_columns: &[crate::parser::Expression]) -> bool {
1453        use crate::parser::Expression;
1454        selected_columns
1455            .iter()
1456            .any(|expr| matches!(expr, Expression::AggregateFunction { .. }))
1457    }
1458
1459    /// Execute aggregate query by processing all rows and computing aggregates
1460    fn execute_aggregate_query(
1461        &mut self,
1462        plan: crate::planner::ExecutionPlan,
1463        query_schema: QuerySchema,
1464    ) -> Result<ResultSet<'_>> {
1465        use crate::planner::ExecutionPlan;
1466
1467        let mut row_maps: Vec<HashMap<String, SqlValue>> = Vec::new();
1468
1469        match plan {
1470            ExecutionPlan::PrimaryKeyLookup {
1471                table,
1472                pk_value,
1473                additional_filter,
1474                ..
1475            } => {
1476                let schema = self.get_table_schema(&table)?;
1477                let key = self.build_primary_key_from_value(&table, &pk_value);
1478                if let Some(value) = self.transaction.get(&key.to_storage_bytes()) {
1479                    if self.row_matches_condition(
1480                        &schema,
1481                        value.as_ref(),
1482                        additional_filter.as_ref(),
1483                    )? {
1484                        row_maps.push(
1485                            self.storage_format
1486                                .deserialize_row_full(value.as_ref(), &schema)?,
1487                        );
1488                    }
1489                }
1490            }
1491            ExecutionPlan::TableRangeScan {
1492                table,
1493                pk_range,
1494                additional_filter,
1495                ..
1496            } => {
1497                let schema = self.get_table_schema(&table)?;
1498                let (start_key, end_key) = self.build_pk_range_keys(&table, &pk_range, &schema)?;
1499                for (_, value) in self.transaction.scan(start_key..end_key)? {
1500                    if self.row_matches_condition(
1501                        &schema,
1502                        value.as_ref(),
1503                        additional_filter.as_ref(),
1504                    )? {
1505                        row_maps.push(
1506                            self.storage_format
1507                                .deserialize_row_full(value.as_ref(), &schema)?,
1508                        );
1509                    }
1510                }
1511            }
1512            ExecutionPlan::TableScan { table, filter, .. } => {
1513                let schema = self.get_table_schema(&table)?;
1514                let start_key = PrimaryKey::table_prefix(&table);
1515                let end_key = PrimaryKey::table_end_marker(&table);
1516                for (_, value) in self.transaction.scan(start_key..end_key)? {
1517                    if self.row_matches_condition(&schema, value.as_ref(), filter.as_ref())? {
1518                        row_maps.push(
1519                            self.storage_format
1520                                .deserialize_row_full(value.as_ref(), &schema)?,
1521                        );
1522                    }
1523                }
1524            }
1525            ExecutionPlan::IndexScan {
1526                table,
1527                index,
1528                column_value,
1529                additional_filter,
1530                ..
1531            } => {
1532                let schema = self.get_table_schema(&table)?;
1533                let (index_start, index_end) =
1534                    crate::catalog::index_prefix_range(&table, &index, &column_value);
1535
1536                for (key, _value) in self.transaction.scan(index_start..index_end)? {
1537                    if let Some((_table, _index, _col_val, pk_str)) =
1538                        crate::catalog::decode_index_key(&key)
1539                    {
1540                        let pk_value = if let Ok(pk_int) = pk_str.parse::<i64>() {
1541                            SqlValue::Integer(pk_int)
1542                        } else {
1543                            SqlValue::Text(pk_str)
1544                        };
1545                        let pk_key = self.build_primary_key_from_value(&table, &pk_value);
1546                        if let Some(value) = self.transaction.get(&pk_key.to_storage_bytes()) {
1547                            if self.row_matches_condition(
1548                                &schema,
1549                                value.as_ref(),
1550                                additional_filter.as_ref(),
1551                            )? {
1552                                row_maps.push(
1553                                    self.storage_format
1554                                        .deserialize_row_full(value.as_ref(), &schema)?,
1555                                );
1556                            }
1557                        }
1558                    }
1559                }
1560            }
1561            other => {
1562                return Err(Error::Other(format!(
1563                    "Aggregate execution not supported for plan: {other:?}"
1564                )));
1565            }
1566        }
1567
1568        let aggregate_results = self.build_aggregate_row(&query_schema, &row_maps)?;
1569
1570        let empty_iter = Box::new(std::iter::empty::<(Vec<u8>, std::rc::Rc<[u8]>)>());
1571        let mut aggregate_iter = SelectRowIterator::new(
1572            empty_iter,
1573            std::rc::Rc::new(TableSchema {
1574                name: "aggregate_result".to_string(),
1575                columns: vec![],
1576                indexes: vec![],
1577            }),
1578            query_schema.clone(),
1579            None,
1580            None,
1581        )
1582        .with_extensions(self.extensions);
1583        aggregate_iter.aggregate_result = Some(aggregate_results);
1584
1585        Ok(ResultSet::Select {
1586            columns: query_schema.column_names.clone(),
1587            rows: Box::new(aggregate_iter),
1588        })
1589    }
1590
1591    fn build_aggregate_row(
1592        &self,
1593        query_schema: &QuerySchema,
1594        rows: &[HashMap<String, SqlValue>],
1595    ) -> Result<Vec<SqlValue>> {
1596        use crate::parser::Expression;
1597
1598        if let Some(expressions) = &query_schema.expressions {
1599            let mut results = Vec::with_capacity(expressions.len());
1600            for expr in expressions {
1601                match expr {
1602                    Expression::AggregateFunction { name, arg } => {
1603                        results.push(self.compute_aggregate(name, arg, rows)?);
1604                    }
1605                    _ => {
1606                        let value = if let Some(first_row) = rows.first() {
1607                            // Special case: "*" column should not be evaluated in aggregate context
1608                            if matches!(expr, Expression::Column(name) if name == "*") {
1609                                SqlValue::Null // "*" is not a real column
1610                            } else {
1611                                expr.evaluate(first_row).map_err(|e| {
1612                                    Error::Other(format!("Expression evaluation error: {e}"))
1613                                })?
1614                            }
1615                        } else {
1616                            let empty_context: HashMap<String, SqlValue> = HashMap::new();
1617                            match expr.evaluate(&empty_context) {
1618                                Ok(v) => v,
1619                                Err(_) => SqlValue::Null,
1620                            }
1621                        };
1622                        results.push(value);
1623                    }
1624                }
1625            }
1626            Ok(results)
1627        } else {
1628            Ok(vec![SqlValue::Integer(rows.len() as i64)])
1629        }
1630    }
1631
1632    /// Compute aggregate function result across fully materialized rows
1633    fn compute_aggregate(
1634        &self,
1635        func_name: &str,
1636        arg: &crate::parser::Expression,
1637        rows: &[HashMap<String, SqlValue>],
1638    ) -> Result<crate::parser::SqlValue> {
1639        use crate::parser::Expression;
1640
1641        if matches!(arg, Expression::Column(col) if col == "*")
1642            && func_name.eq_ignore_ascii_case("COUNT")
1643        {
1644            return Ok(SqlValue::Integer(rows.len() as i64));
1645        }
1646
1647        let mut values: Vec<SqlValue> = Vec::with_capacity(rows.len());
1648        for row in rows {
1649            let value = match arg {
1650                Expression::Column(col_name) => {
1651                    row.get(col_name).cloned().unwrap_or(SqlValue::Null)
1652                }
1653                _ => match arg.evaluate(row) {
1654                    Ok(v) => v,
1655                    Err(_) => SqlValue::Null,
1656                },
1657            };
1658            values.push(value);
1659        }
1660
1661        match func_name.to_uppercase().as_str() {
1662            "COUNT" => {
1663                let count = values
1664                    .iter()
1665                    .filter(|v| !matches!(v, SqlValue::Null))
1666                    .count();
1667                Ok(SqlValue::Integer(count as i64))
1668            }
1669            "SUM" => {
1670                let mut has_value = false;
1671                let mut sum_f64: f64 = 0.0;
1672
1673                for value in values.iter() {
1674                    match value {
1675                        SqlValue::Integer(i) => {
1676                            sum_f64 += *i as f64;
1677                            has_value = true;
1678                        }
1679                        SqlValue::Real(r) => {
1680                            sum_f64 += *r;
1681                            has_value = true;
1682                        }
1683                        _ => {}
1684                    }
1685                }
1686
1687                if !has_value {
1688                    Ok(SqlValue::Null)
1689                } else {
1690                    // Always return Real for SUM to match SQL standard behavior
1691                    Ok(SqlValue::Real(sum_f64))
1692                }
1693            }
1694            "AVG" => {
1695                let mut count = 0;
1696                let mut sum = 0.0;
1697                for value in values.iter() {
1698                    match value {
1699                        SqlValue::Integer(i) => {
1700                            sum += *i as f64;
1701                            count += 1;
1702                        }
1703                        SqlValue::Real(r) => {
1704                            sum += *r;
1705                            count += 1;
1706                        }
1707                        _ => {}
1708                    }
1709                }
1710                if count == 0 {
1711                    Ok(SqlValue::Null)
1712                } else {
1713                    Ok(SqlValue::Real(sum / count as f64))
1714                }
1715            }
1716            "MAX" => self.extremum(&values, std::cmp::Ordering::Greater),
1717            "MIN" => self.extremum(&values, std::cmp::Ordering::Less),
1718            _ => Err(Error::Other(format!(
1719                "Unsupported aggregate function: {func_name}"
1720            ))),
1721        }
1722    }
1723
1724    fn row_matches_condition(
1725        &self,
1726        schema: &TableSchema,
1727        row: &[u8],
1728        condition: Option<&crate::parser::Condition>,
1729    ) -> Result<bool> {
1730        if let Some(cond) = condition {
1731            self.storage_format
1732                .matches_condition_with_metadata(row, schema, cond)
1733                .map_err(|e| Error::Other(format!("Failed to evaluate condition: {e}")))
1734        } else {
1735            Ok(true)
1736        }
1737    }
1738
1739    fn extremum(&self, values: &[SqlValue], target_order: std::cmp::Ordering) -> Result<SqlValue> {
1740        let mut best: Option<SqlValue> = None;
1741        for value in values {
1742            if matches!(value, SqlValue::Null) {
1743                continue;
1744            }
1745
1746            match &best {
1747                Some(current) => {
1748                    if let Some(ordering) = Self::compare_sql_values(value, current) {
1749                        if ordering == target_order {
1750                            best = Some(value.clone());
1751                        }
1752                    }
1753                }
1754                None => {
1755                    best = Some(value.clone());
1756                }
1757            }
1758        }
1759
1760        Ok(best.unwrap_or(SqlValue::Null))
1761    }
1762
1763    fn compare_sql_values(left: &SqlValue, right: &SqlValue) -> Option<std::cmp::Ordering> {
1764        use SqlValue::*;
1765        match (left, right) {
1766            (Integer(a), Integer(b)) => Some(a.cmp(b)),
1767            (Real(a), Real(b)) => a.partial_cmp(b),
1768            (Integer(a), Real(b)) => (*a as f64).partial_cmp(b),
1769            (Real(a), Integer(b)) => a.partial_cmp(&(*b as f64)),
1770            (Text(a), Text(b)) => Some(a.cmp(b)),
1771            _ => None,
1772        }
1773    }
1774
1775    /// Execute SELECT plans using streaming and collect results
1776    /// This eliminates duplicate code by using a single streaming implementation
1777    fn execute_select_plan_streaming(
1778        &mut self,
1779        plan: crate::planner::ExecutionPlan,
1780    ) -> Result<ResultSet<'_>> {
1781        use crate::planner::ExecutionPlan;
1782
1783        // Clone the plan for aggregate function detection
1784        let plan_clone = plan.clone();
1785
1786        match plan {
1787            ExecutionPlan::PrimaryKeyLookup {
1788                table,
1789                pk_value,
1790                selected_columns,
1791                additional_filter,
1792            } => {
1793                let schema = self.get_table_schema(&table)?;
1794                let query_schema = QuerySchema::new_with_expressions(&selected_columns, &schema);
1795
1796                // Check if this is an aggregate query
1797                if self.has_aggregate_functions(&selected_columns) {
1798                    return self.execute_aggregate_query(plan_clone.clone(), query_schema);
1799                }
1800
1801                let key = self.build_primary_key_from_value(&table, &pk_value);
1802
1803                // Create an iterator that returns at most one row if the key exists and matches
1804                let key_bytes = key.to_storage_bytes();
1805                let scan_iter = if let Some(value) = self.transaction.get(&key_bytes) {
1806                    // Create a single-item iterator if the key exists
1807                    let single_result = vec![(key_bytes, value)];
1808                    Box::new(single_result.into_iter())
1809                        as Box<dyn Iterator<Item = (Vec<u8>, std::rc::Rc<[u8]>)>>
1810                } else {
1811                    // Create an empty iterator if the key doesn't exist
1812                    Box::new(std::iter::empty())
1813                        as Box<dyn Iterator<Item = (Vec<u8>, std::rc::Rc<[u8]>)>>
1814                };
1815
1816                let row_iter = SelectRowIterator::new(
1817                    scan_iter,
1818                    schema.clone(),
1819                    query_schema.clone(),
1820                    additional_filter,
1821                    Some(1), // PK lookup returns at most 1 row
1822                )
1823                .with_extensions(self.extensions);
1824
1825                Ok(ResultSet::Select {
1826                    columns: query_schema.column_names.clone(),
1827                    rows: Box::new(row_iter),
1828                })
1829            }
1830            ExecutionPlan::TableRangeScan {
1831                table,
1832                selected_columns,
1833                pk_range,
1834                additional_filter,
1835                limit,
1836            } => {
1837                let schema = self.get_table_schema(&table)?;
1838                let query_schema = QuerySchema::new_with_expressions(&selected_columns, &schema);
1839
1840                // Check if this is an aggregate query
1841                if self.has_aggregate_functions(&selected_columns) {
1842                    return self.execute_aggregate_query(plan_clone.clone(), query_schema);
1843                }
1844
1845                // Build range scan keys based on PK range
1846                let (start_key, end_key) = self.build_pk_range_keys(&table, &pk_range, &schema)?;
1847
1848                // Create streaming iterator for range scan
1849                let scan_iter = self.transaction.scan(start_key..end_key)?;
1850                let row_iter = SelectRowIterator::new(
1851                    scan_iter,
1852                    schema.clone(),
1853                    query_schema.clone(),
1854                    additional_filter,
1855                    limit,
1856                )
1857                .with_extensions(self.extensions);
1858
1859                Ok(ResultSet::Select {
1860                    columns: query_schema.column_names.clone(),
1861                    rows: Box::new(row_iter),
1862                })
1863            }
1864            ExecutionPlan::IndexScan {
1865                table,
1866                index,
1867                column_value,
1868                selected_columns,
1869                additional_filter,
1870            } => {
1871                let schema = self.get_table_schema(&table)?;
1872                let query_schema = QuerySchema::new_with_expressions(&selected_columns, &schema);
1873
1874                // Check if this is an aggregate query
1875                if self.has_aggregate_functions(&selected_columns) {
1876                    return self.execute_aggregate_query(plan_clone.clone(), query_schema);
1877                }
1878
1879                // For now, use the existing non-streaming index scan implementation
1880                // TODO: Implement proper streaming index scan iterator
1881                let (index_start, index_end) =
1882                    crate::catalog::index_prefix_range(&table, &index, &column_value);
1883
1884                let mut row_maps = Vec::new();
1885                for (key, _value) in self.transaction.scan(index_start..index_end)? {
1886                    if let Some((_table, _index, _col_val, pk_str)) =
1887                        crate::catalog::decode_index_key(&key)
1888                    {
1889                        let pk_value = if let Ok(pk_int) = pk_str.parse::<i64>() {
1890                            SqlValue::Integer(pk_int)
1891                        } else {
1892                            SqlValue::Text(pk_str)
1893                        };
1894                        let pk_key = self.build_primary_key_from_value(&table, &pk_value);
1895                        if let Some(value) = self.transaction.get(&pk_key.to_storage_bytes()) {
1896                            if self.row_matches_condition(
1897                                &schema,
1898                                value.as_ref(),
1899                                additional_filter.as_ref(),
1900                            )? {
1901                                row_maps.push(
1902                                    self.storage_format
1903                                        .deserialize_row_full(value.as_ref(), &schema)?,
1904                                );
1905                            }
1906                        }
1907                    }
1908                }
1909
1910                // Convert to streaming iterator
1911                let row_values: Vec<Vec<SqlValue>> = row_maps
1912                    .into_iter()
1913                    .map(|row_map| {
1914                        query_schema
1915                            .column_names
1916                            .iter()
1917                            .map(|col_name| {
1918                                row_map.get(col_name).cloned().unwrap_or(SqlValue::Null)
1919                            })
1920                            .collect()
1921                    })
1922                    .collect();
1923
1924                // Create a simple iterator that yields the collected rows
1925                let row_iter = SelectRowIterator::new(
1926                    Box::new(std::iter::empty()) as ScanIterator,
1927                    schema.clone(),
1928                    query_schema.clone(),
1929                    None,
1930                    None,
1931                )
1932                .with_extensions(self.extensions);
1933
1934                // Override the iterator's behavior by setting sorted_results
1935                let mut result_iter = row_iter;
1936                result_iter.sorted_results = Some(row_values.into_iter());
1937
1938                Ok(ResultSet::Select {
1939                    columns: query_schema.column_names.clone(),
1940                    rows: Box::new(result_iter),
1941                })
1942            }
1943            ExecutionPlan::TableScan {
1944                table,
1945                selected_columns,
1946                filter,
1947                limit,
1948                ..
1949            } => {
1950                let schema = self.get_table_schema(&table)?;
1951                let query_schema = QuerySchema::new_with_expressions(&selected_columns, &schema);
1952
1953                // Check if this is an aggregate query
1954                if self.has_aggregate_functions(&selected_columns) {
1955                    return self.execute_aggregate_query(plan_clone.clone(), query_schema);
1956                }
1957
1958                let start_key = PrimaryKey::table_prefix(&table);
1959                let end_key = PrimaryKey::table_end_marker(&table);
1960                // Create streaming iterator for table scan
1961                let scan_iter = self.transaction.scan(start_key..end_key)?;
1962                let row_iter = SelectRowIterator::new(
1963                    scan_iter,
1964                    schema.clone(),
1965                    query_schema.clone(),
1966                    filter,
1967                    limit,
1968                )
1969                .with_extensions(self.extensions);
1970
1971                Ok(ResultSet::Select {
1972                    columns: query_schema.column_names.clone(),
1973                    rows: Box::new(row_iter),
1974                })
1975            }
1976            ExecutionPlan::VectorSearch { .. } => {
1977                // Handle VectorSearch execution plan
1978                let ExecutionPlan::VectorSearch {
1979                    table,
1980                    selected_columns,
1981                    additional_filter,
1982                    ..
1983                } = plan
1984                else {
1985                    unreachable!()
1986                };
1987
1988                let schema = self.get_table_schema(&table)?;
1989                let query_schema = QuerySchema::new_with_expressions(&selected_columns, &schema);
1990
1991                // Check if this is an aggregate query
1992                if self.has_aggregate_functions(&selected_columns) {
1993                    return self.execute_aggregate_query(plan_clone.clone(), query_schema);
1994                }
1995
1996                // Fall back to table scan for now
1997                let start_key = PrimaryKey::table_prefix(&table);
1998                let end_key = PrimaryKey::table_end_marker(&table);
1999                let scan_iter = self.transaction.scan(start_key..end_key)?;
2000                let row_iter = SelectRowIterator::new(
2001                    scan_iter,
2002                    schema.clone(),
2003                    query_schema.clone(),
2004                    additional_filter,
2005                    None,
2006                )
2007                .with_extensions(self.extensions);
2008
2009                Ok(ResultSet::Select {
2010                    columns: query_schema.column_names.clone(),
2011                    rows: Box::new(row_iter),
2012                })
2013            }
2014            _ => Err(Error::Other("Expected SELECT execution plan".to_string())),
2015        }
2016    }
2017
2018    /// Execute insert plan
2019    fn execute_insert_plan(
2020        &mut self,
2021        table: &str,
2022        rows: &[HashMap<String, SqlValue>],
2023    ) -> Result<ResultSet<'_>> {
2024        let schema = self.get_table_schema(table)?;
2025        let mut rows_affected = 0;
2026
2027        for row_data in rows {
2028            // Validate row data
2029            self.validate_row_data(table, row_data)?;
2030
2031            // Build primary key
2032            let key = self.build_primary_key_from_value(
2033                table,
2034                row_data
2035                    .get(schema.get_primary_key_column().unwrap())
2036                    .unwrap(),
2037            );
2038            // Check for primary key conflicts
2039            if self.transaction.get(&key.to_storage_bytes()).is_some() {
2040                let pk_col = schema.get_primary_key_column().unwrap_or("<pk>");
2041                let pk_val = row_data.get(pk_col).cloned().unwrap_or(SqlValue::Null);
2042                return Err(Error::Other(format!(
2043                    "Primary key constraint violation on table '{table}': key '{pk_col}' has duplicate value {pk_val:?}"
2044                )));
2045            }
2046
2047            // Serialize and store row
2048            let serialized = self.storage_format.serialize_row(row_data, &schema)?;
2049            self.transaction.set(&key.to_storage_bytes(), serialized)?;
2050
2051            // Create index entries for this row
2052            self.create_index_entries(table, &schema, row_data)?;
2053
2054            rows_affected += 1;
2055        }
2056
2057        Ok(ResultSet::Insert { rows_affected })
2058    }
2059
2060    /// Execute update plan
2061    fn execute_update_plan(
2062        &mut self,
2063        table: &str,
2064        assignments: &[crate::planner::Assignment],
2065        scan_plan: crate::planner::ExecutionPlan,
2066    ) -> Result<ResultSet<'_>> {
2067        let schema = self.get_table_schema(table)?;
2068        let mut rows_affected = 0;
2069
2070        // We need to collect the keys first because the scan iterator will borrow the transaction,
2071        // and we can't borrow it mutably inside the loop to perform the update.
2072        let keys_to_update = {
2073            // Extract columns before consuming the plan
2074            let selected_columns = match &scan_plan {
2075                crate::planner::ExecutionPlan::PrimaryKeyLookup {
2076                    selected_columns, ..
2077                } => selected_columns.clone(),
2078                crate::planner::ExecutionPlan::TableRangeScan {
2079                    selected_columns, ..
2080                } => selected_columns.clone(),
2081                crate::planner::ExecutionPlan::TableScan {
2082                    selected_columns, ..
2083                } => selected_columns.clone(),
2084                _ => return Err(Error::Other("Unsupported scan plan for update".to_string())),
2085            };
2086
2087            // Extract column names from expressions
2088            let mut column_names = Vec::new();
2089            for expr in &selected_columns {
2090                match expr {
2091                    crate::parser::Expression::Column(name) => {
2092                        column_names.push(name.clone());
2093                    }
2094                    _ => {
2095                        return Err(Error::Other(
2096                            "Update operations only support column references".to_string(),
2097                        ));
2098                    }
2099                }
2100            }
2101
2102            // Get the plan results and materialize immediately to avoid lifetime conflicts
2103            let materialized_rows = self.execute_plan_materialized(scan_plan)?;
2104
2105            // Pre-allocate with exact capacity to avoid reallocations
2106            let mut keys = Vec::with_capacity(materialized_rows.len());
2107            for row_values in materialized_rows {
2108                let mut row_data = HashMap::with_capacity(column_names.len());
2109                for (i, col_name) in column_names.iter().enumerate() {
2110                    if let Some(value) = row_values.get(i) {
2111                        row_data.insert(col_name.clone(), value.clone());
2112                    }
2113                }
2114                let pk_column = schema.get_primary_key_column().unwrap();
2115                let key =
2116                    self.build_primary_key_from_value(table, row_data.get(pk_column).unwrap());
2117                keys.push(key);
2118            }
2119            keys
2120        };
2121
2122        for key in keys_to_update {
2123            if let Some(value) = self.transaction.get(&key.to_storage_bytes()) {
2124                if let Ok(old_row_data) = self.storage_format.deserialize_row_full(&value, &schema)
2125                {
2126                    self.remove_index_entries(table, &schema, &old_row_data)?;
2127                    let mut row_data = old_row_data.clone();
2128
2129                    // Apply assignments
2130                    for assignment in assignments {
2131                        let new_value = assignment.value.evaluate(&row_data).map_err(|e| {
2132                            crate::Error::Other(format!("Expression evaluation error: {e}"))
2133                        })?;
2134                        row_data.insert(assignment.column.clone(), new_value);
2135                    }
2136
2137                    // Validate updated row
2138                    // Check if primary key was changed and if new key conflicts with existing data
2139                    let pk_column = schema.get_primary_key_column().unwrap();
2140                    let new_key =
2141                        self.build_primary_key_from_value(table, row_data.get(pk_column).unwrap());
2142                    let new_key_bytes = new_key.to_storage_bytes();
2143                    let key_bytes = key.to_storage_bytes();
2144                    if new_key_bytes != key_bytes && self.transaction.get(&new_key_bytes).is_some()
2145                    {
2146                        let pk_col = schema.get_primary_key_column().unwrap_or("<pk>");
2147                        let pk_val = row_data.get(pk_col).cloned().unwrap_or(SqlValue::Null);
2148                        return Err(Error::Other(format!(
2149                            "Primary key constraint violation on table '{table}': key '{pk_col}' has duplicate value {pk_val:?}"
2150                        )));
2151                    }
2152
2153                    // Validate other constraints (NOT NULL, etc.) but skip primary key validation
2154                    // since we already handled it above
2155                    self.validate_row_data(table, &row_data)?;
2156
2157                    // Serialize and store the updated row
2158                    let serialized = self.storage_format.serialize_row(&row_data, &schema)?;
2159
2160                    // If primary key changed, we need to delete the old row and insert the new one
2161                    if new_key_bytes != key_bytes {
2162                        self.transaction.delete(&key_bytes)?;
2163                        self.transaction.set(&new_key_bytes, serialized)?;
2164                    } else {
2165                        self.transaction.set(&key_bytes, serialized)?;
2166                    }
2167
2168                    self.create_index_entries(table, &schema, &row_data)?;
2169
2170                    rows_affected += 1;
2171                }
2172            }
2173        }
2174
2175        Ok(ResultSet::Update { rows_affected })
2176    }
2177
2178    /// Execute delete plan
2179    fn execute_delete_plan(
2180        &mut self,
2181        table: &str,
2182        scan_plan: crate::planner::ExecutionPlan,
2183    ) -> Result<ResultSet<'_>> {
2184        let schema = self.get_table_schema(table)?;
2185
2186        // This approach avoids collecting all full rows in memory first.
2187        // It scans, collects keys, and then deletes.
2188        let keys_to_delete = self.execute_scan_and_collect_keys(&scan_plan, &schema)?;
2189        let rows_affected = keys_to_delete.len();
2190
2191        for key_bytes in &keys_to_delete {
2192            if let Some(value) = self.transaction.get(key_bytes) {
2193                let row_data = self.storage_format.deserialize_row_full(&value, &schema)?;
2194                self.remove_index_entries(table, &schema, &row_data)?;
2195            }
2196            self.transaction.delete(key_bytes)?;
2197        }
2198
2199        Ok(ResultSet::Delete { rows_affected })
2200    }
2201
2202    /// Execute create table plan
2203    fn execute_create_table_plan(
2204        &mut self,
2205        table: &str,
2206        schema: &TableSchema,
2207    ) -> Result<ResultSet<'_>> {
2208        // Convert to CreateTableStatement format
2209        use crate::parser::{ColumnDefinition, CreateTableStatement};
2210
2211        let create_stmt = CreateTableStatement {
2212            table: table.to_string(),
2213            columns: schema
2214                .columns
2215                .iter()
2216                .map(|col| ColumnDefinition {
2217                    name: col.name.clone(),
2218                    data_type: col.data_type.clone(),
2219                    constraints: col.constraints.clone(),
2220                })
2221                .collect(),
2222        };
2223
2224        self.execute_create_table(create_stmt)
2225    }
2226
2227    /// Execute drop table plan
2228    fn execute_drop_table_plan(&mut self, table: &str, if_exists: bool) -> Result<ResultSet<'_>> {
2229        use crate::parser::DropTableStatement;
2230
2231        let drop_stmt = DropTableStatement {
2232            table: table.to_string(),
2233            if_exists,
2234        };
2235
2236        self.execute_drop_table(drop_stmt)
2237    }
2238
2239    /// Helper function to execute a scan plan and collect the primary keys of the resulting rows.
2240    /// This is more memory-efficient than collecting the full rows.
2241    fn execute_scan_and_collect_keys(
2242        &mut self,
2243        scan_plan: &crate::planner::ExecutionPlan,
2244        schema: &TableSchema,
2245    ) -> Result<Vec<Vec<u8>>> {
2246        use crate::planner::ExecutionPlan;
2247        // Pre-allocate with reasonable capacity to avoid reallocations
2248        let mut keys = Vec::with_capacity(100);
2249
2250        match scan_plan {
2251            ExecutionPlan::PrimaryKeyLookup {
2252                table,
2253                pk_value,
2254                additional_filter,
2255                ..
2256            } => {
2257                let key = self.build_primary_key_from_value(table, pk_value);
2258                if let Some(value) = self.transaction.get(&key.to_storage_bytes()) {
2259                    let matches = if let Some(filter) = additional_filter {
2260                        self.storage_format
2261                            .matches_condition(&value, schema, filter)
2262                            .unwrap_or(false)
2263                    } else {
2264                        true
2265                    };
2266
2267                    if matches {
2268                        keys.push(key.to_storage_bytes());
2269                    }
2270                }
2271            }
2272            ExecutionPlan::TableRangeScan {
2273                table,
2274                pk_range,
2275                additional_filter,
2276                limit,
2277                ..
2278            } => {
2279                let (start_key, end_key) = self.build_pk_range_keys(table, pk_range, schema)?;
2280                let mut count = 0;
2281
2282                let scan_iter = self.transaction.scan(start_key..end_key)?;
2283
2284                for (key, value_rc) in scan_iter {
2285                    if let Some(limit) = limit {
2286                        if count >= *limit {
2287                            break;
2288                        }
2289                    }
2290
2291                    let matches = if let Some(filter_cond) = additional_filter {
2292                        // Use pre-computed metadata from schema
2293                        self.storage_format
2294                            .matches_condition_with_metadata(&value_rc, schema, filter_cond)
2295                            .unwrap_or(false)
2296                    } else {
2297                        true
2298                    };
2299
2300                    if matches {
2301                        keys.push(key);
2302                        count += 1;
2303                    }
2304                }
2305            }
2306            ExecutionPlan::TableScan {
2307                table,
2308                filter,
2309                limit,
2310                ..
2311            } => {
2312                let start_key = PrimaryKey::table_prefix(table);
2313                let end_key = PrimaryKey::table_end_marker(table);
2314                let mut count = 0;
2315
2316                let scan_iter = self.transaction.scan(start_key..end_key)?;
2317
2318                for (key, value_rc) in scan_iter {
2319                    if let Some(limit) = limit {
2320                        if count >= *limit {
2321                            break;
2322                        }
2323                    }
2324
2325                    let matches = if let Some(filter_cond) = filter {
2326                        // Use pre-computed metadata from schema
2327                        self.storage_format
2328                            .matches_condition_with_metadata(&value_rc, schema, filter_cond)
2329                            .unwrap_or(false)
2330                    } else {
2331                        true
2332                    };
2333
2334                    if matches {
2335                        keys.push(key);
2336                        count += 1;
2337                    }
2338                }
2339            }
2340            ExecutionPlan::VectorSearch {
2341                table,
2342                additional_filter,
2343                ..
2344            } => {
2345                let start_key = PrimaryKey::table_prefix(table);
2346                let end_key = PrimaryKey::table_end_marker(table);
2347                let scan_iter = self.transaction.scan(start_key..end_key)?;
2348
2349                for (key, value_rc) in scan_iter {
2350                    let matches = if let Some(filter_cond) = additional_filter {
2351                        // Use pre-computed metadata from schema
2352                        self.storage_format
2353                            .matches_condition_with_metadata(&value_rc, schema, filter_cond)
2354                            .unwrap_or(false)
2355                    } else {
2356                        true
2357                    };
2358
2359                    if matches {
2360                        keys.push(key);
2361                    }
2362                }
2363            }
2364            _ => {
2365                return Err(crate::Error::Other(
2366                    "Unsupported scan plan for key collection".to_string(),
2367                ))
2368            }
2369        }
2370        Ok(keys)
2371    }
2372
2373    /// Build primary key string for a row
2374    /// Note: TegDB only supports single-column primary keys
2375    fn build_primary_key_from_value(&self, table_name: &str, pk_value: &SqlValue) -> PrimaryKey {
2376        let native_key = NativeKey::from_sql_value(pk_value).unwrap();
2377        PrimaryKey::new(table_name.to_string(), native_key)
2378    }
2379
2380    /// Execute a plan and immediately materialize SELECT results for internal use
2381    /// This is used by UPDATE/DELETE operations that need to collect keys
2382    fn execute_plan_materialized(
2383        &mut self,
2384        plan: crate::planner::ExecutionPlan,
2385    ) -> Result<Vec<Vec<SqlValue>>> {
2386        let result = self.execute_plan(plan)?;
2387        match result {
2388            ResultSet::Select { rows, .. } => rows.collect_rows(),
2389            _ => Err(Error::Other(
2390                "Expected SELECT result for materialization".to_string(),
2391            )),
2392        }
2393    }
2394
2395    /// Build primary key range scan keys based on PK range conditions
2396    fn build_pk_range_keys(
2397        &self,
2398        table: &str,
2399        pk_range: &crate::planner::PkRange,
2400        schema: &TableSchema,
2401    ) -> Result<(Vec<u8>, Vec<u8>)> {
2402        // For now, we'll implement a simple range scan that works with single-column PKs
2403        // This can be enhanced later to support composite PKs
2404
2405        let pk_columns: Vec<_> = schema
2406            .columns
2407            .iter()
2408            .filter(|col| col.constraints.contains(&ColumnConstraint::PrimaryKey))
2409            .collect();
2410
2411        if pk_columns.len() != 1 {
2412            return Err(Error::Other(
2413                "Range scan currently only supports single-column primary keys".to_string(),
2414            ));
2415        }
2416
2417        // Build start key
2418        let start_key = if let Some(start_bound) = &pk_range.start_bound {
2419            let value = &start_bound.value;
2420            let native_key = NativeKey::from_sql_value(value).unwrap();
2421            let key = PrimaryKey::range_start(table, &native_key, start_bound.inclusive);
2422            key.to_storage_bytes()
2423        } else {
2424            PrimaryKey::table_prefix(table)
2425        };
2426
2427        // Build end key
2428        let end_key = if let Some(end_bound) = &pk_range.end_bound {
2429            let value = &end_bound.value;
2430            let native_key = NativeKey::from_sql_value(value).unwrap();
2431            let key = PrimaryKey::range_end(table, &native_key, end_bound.inclusive);
2432            key.to_storage_bytes()
2433        } else {
2434            PrimaryKey::table_end_marker(table)
2435        };
2436
2437        // Ensure start_key <= end_key for BTreeMap range scan
2438        if start_key > end_key {
2439            return Err(Error::Other(
2440                "Invalid range: start key is greater than end key".to_string(),
2441            ));
2442        }
2443
2444        Ok((start_key, end_key))
2445    }
2446
2447    /// Execute a query plan using a previously computed `QuerySchema`.
2448    pub fn execute_plan_with_query_schema(
2449        &mut self,
2450        plan: crate::planner::ExecutionPlan,
2451        query_schema: &QuerySchema,
2452    ) -> Result<ResultSet<'_>> {
2453        use crate::planner::ExecutionPlan;
2454        match plan {
2455            ExecutionPlan::PrimaryKeyLookup {
2456                table,
2457                pk_value,
2458                selected_columns: _,
2459                additional_filter,
2460            } => {
2461                let schema = self.get_table_schema(&table)?;
2462                let key = self.build_primary_key_from_value(&table, &pk_value);
2463                let key_bytes = key.to_storage_bytes();
2464                let scan_iter = if let Some(value) = self.transaction.get(&key_bytes) {
2465                    let single_result = vec![(key_bytes, value)];
2466                    Box::new(single_result.into_iter())
2467                        as Box<dyn Iterator<Item = (Vec<u8>, std::rc::Rc<[u8]>)>>
2468                } else {
2469                    Box::new(std::iter::empty())
2470                        as Box<dyn Iterator<Item = (Vec<u8>, std::rc::Rc<[u8]>)>>
2471                };
2472                let row_iter = SelectRowIterator::new(
2473                    scan_iter,
2474                    schema.clone(),
2475                    query_schema.clone(),
2476                    additional_filter,
2477                    Some(1),
2478                )
2479                .with_extensions(self.extensions);
2480                Ok(ResultSet::Select {
2481                    columns: query_schema.column_names.clone(),
2482                    rows: Box::new(row_iter),
2483                })
2484            }
2485            ExecutionPlan::TableRangeScan {
2486                table,
2487                selected_columns: _,
2488                pk_range,
2489                additional_filter,
2490                limit,
2491            } => {
2492                let schema = self.get_table_schema(&table)?;
2493                let (start_key, end_key) = self.build_pk_range_keys(&table, &pk_range, &schema)?;
2494                let scan_iter = self.transaction.scan(start_key..end_key)?;
2495                let row_iter = SelectRowIterator::new(
2496                    scan_iter,
2497                    schema.clone(),
2498                    query_schema.clone(),
2499                    additional_filter,
2500                    limit,
2501                )
2502                .with_extensions(self.extensions);
2503                Ok(ResultSet::Select {
2504                    columns: query_schema.column_names.clone(),
2505                    rows: Box::new(row_iter),
2506                })
2507            }
2508            ExecutionPlan::TableScan {
2509                table,
2510                selected_columns: _,
2511                filter,
2512                limit,
2513            } => {
2514                let schema = self.get_table_schema(&table)?;
2515                let start_key = PrimaryKey::table_prefix(&table);
2516                let end_key = PrimaryKey::table_end_marker(&table);
2517                let scan_iter = self.transaction.scan(start_key..end_key)?;
2518                let row_iter = SelectRowIterator::new(
2519                    scan_iter,
2520                    schema.clone(),
2521                    query_schema.clone(),
2522                    filter,
2523                    limit,
2524                )
2525                .with_extensions(self.extensions);
2526                Ok(ResultSet::Select {
2527                    columns: query_schema.column_names.clone(),
2528                    rows: Box::new(row_iter),
2529                })
2530            }
2531            ExecutionPlan::VectorSearch {
2532                table,
2533                index: _index,
2534                query_vector: _query_vector,
2535                similarity_function: _similarity_function,
2536                k,
2537                selected_columns,
2538                additional_filter,
2539            } => {
2540                let schema = self.get_table_schema(&table)?;
2541                let query_schema = QuerySchema::new_with_expressions(&selected_columns, &schema);
2542
2543                // Check if this is an aggregate query
2544                if self.has_aggregate_functions(&selected_columns) {
2545                    let plan_for_aggregate = ExecutionPlan::VectorSearch {
2546                        table,
2547                        index: _index,
2548                        query_vector: _query_vector,
2549                        similarity_function: _similarity_function,
2550                        k,
2551                        selected_columns,
2552                        additional_filter: additional_filter.clone(),
2553                    };
2554                    return self.execute_aggregate_query(plan_for_aggregate, query_schema);
2555                }
2556
2557                // For now, fall back to table scan with vector similarity computation
2558                // TODO: Implement proper vector index usage
2559                let start_key = PrimaryKey::table_prefix(&table);
2560                let end_key = PrimaryKey::table_end_marker(&table);
2561                let scan_iter = self.transaction.scan(start_key..end_key)?;
2562
2563                // For now, use a table scan with vector similarity computation
2564                // TODO: Implement proper vector index usage
2565                let row_iter = SelectRowIterator::new(
2566                    scan_iter,
2567                    schema.clone(),
2568                    query_schema.clone(),
2569                    additional_filter,
2570                    Some(k as u64),
2571                )
2572                .with_extensions(self.extensions);
2573
2574                Ok(ResultSet::Select {
2575                    columns: query_schema.column_names.clone(),
2576                    rows: Box::new(row_iter),
2577                })
2578            }
2579            _ => self.execute_plan(plan),
2580        }
2581    }
2582
2583    fn create_index_entries(
2584        &mut self,
2585        table: &str,
2586        schema: &TableSchema,
2587        row_data: &HashMap<String, SqlValue>,
2588    ) -> Result<()> {
2589        for index in &schema.indexes {
2590            if !matches!(index.index_type, IndexType::BTree) {
2591                // Vector and other specialized indexes maintain their own structures elsewhere.
2592                continue;
2593            }
2594            if let Some(column_value) = row_data.get(&index.column_name) {
2595                let pk_column = schema.get_primary_key_column().unwrap();
2596                let pk_value = row_data.get(pk_column).unwrap();
2597                let index_key =
2598                    crate::catalog::encode_index_key(table, &index.name, column_value, pk_value);
2599
2600                if index.unique {
2601                    let (range_start, range_end) =
2602                        crate::catalog::index_prefix_range(table, &index.name, column_value);
2603                    for (existing_key, _) in self
2604                        .transaction
2605                        .scan(range_start.clone()..range_end.clone())?
2606                    {
2607                        if existing_key != index_key {
2608                            return Err(Error::Other(format!(
2609                                "Unique constraint violation on index '{name}' (column '{col}'): duplicate value {val:?}",
2610                                name = index.name,
2611                                col = index.column_name,
2612                                val = column_value
2613                            )));
2614                        }
2615                    }
2616                }
2617
2618                self.transaction.set(&index_key, b"1".to_vec())?;
2619            }
2620        }
2621        Ok(())
2622    }
2623
2624    fn remove_index_entries(
2625        &mut self,
2626        table: &str,
2627        schema: &TableSchema,
2628        row_data: &HashMap<String, SqlValue>,
2629    ) -> Result<()> {
2630        for index in &schema.indexes {
2631            if !matches!(index.index_type, IndexType::BTree) {
2632                continue;
2633            }
2634            if let Some(column_value) = row_data.get(&index.column_name) {
2635                let pk_column = schema.get_primary_key_column().unwrap();
2636                if let Some(pk_value) = row_data.get(pk_column) {
2637                    let index_key = crate::catalog::encode_index_key(
2638                        table,
2639                        &index.name,
2640                        column_value,
2641                        pk_value,
2642                    );
2643                    self.transaction.delete(&index_key)?;
2644                }
2645            }
2646        }
2647        Ok(())
2648    }
2649
2650    /// Populate an index with existing data from the table
2651    fn populate_index_with_existing_data(
2652        &mut self,
2653        table_name: &str,
2654        index: &crate::catalog::IndexInfo,
2655    ) -> Result<()> {
2656        if !matches!(index.index_type, IndexType::BTree) {
2657            // Specialized indexes maintain their own structures; nothing to do for the BTree store.
2658            return Ok(());
2659        }
2660
2661        let schema = self.get_table_schema(table_name)?;
2662
2663        // Scan all existing rows in the table
2664        let start_key = PrimaryKey::table_prefix(table_name);
2665        let end_key = PrimaryKey::table_end_marker(table_name);
2666        let scan_iter = self.transaction.scan(start_key..end_key)?;
2667
2668        // Collect all rows first to avoid borrow checker issues
2669        let mut rows_to_index = Vec::new();
2670        for (_, value_rc) in scan_iter {
2671            // Deserialize the row data
2672            let row_data = self
2673                .storage_format
2674                .deserialize_row_full(&value_rc, &schema)?;
2675            rows_to_index.push(row_data);
2676        }
2677
2678        // Now create index entries for all rows
2679        for row_data in rows_to_index {
2680            if let Some(column_value) = row_data.get(&index.column_name) {
2681                let pk_column = schema.get_primary_key_column().unwrap();
2682                let pk_value = row_data.get(pk_column).unwrap();
2683                let index_key = crate::catalog::encode_index_key(
2684                    table_name,
2685                    &index.name,
2686                    column_value,
2687                    pk_value,
2688                );
2689
2690                if index.unique {
2691                    let (range_start, range_end) =
2692                        crate::catalog::index_prefix_range(table_name, &index.name, column_value);
2693                    for (existing_key, _) in self
2694                        .transaction
2695                        .scan(range_start.clone()..range_end.clone())?
2696                    {
2697                        if existing_key != index_key {
2698                            return Err(Error::Other(format!(
2699                                "Unique constraint violation on index '{name}' (column '{col}'): duplicate value {val:?}",
2700                                name = index.name,
2701                                col = index.column_name,
2702                                val = column_value
2703                            )));
2704                        }
2705                    }
2706                }
2707
2708                self.transaction.set(&index_key, b"1".to_vec())?;
2709            }
2710        }
2711
2712        Ok(())
2713    }
2714}