vibesql_executor/
select_into.rs

1//! SELECT INTO executor - SQL:1999 Feature E111
2//!
3//! Implements SELECT INTO statements which create a new table and insert query results.
4//! Feature E111 requires exactly one row to be returned.
5
6use vibesql_ast::{ColumnDef, CreateTableStmt, SelectItem, SelectStmt};
7use vibesql_storage::Database;
8use vibesql_types::DataType;
9
10use crate::{errors::ExecutorError, select::SelectExecutor};
11
12pub struct SelectIntoExecutor;
13
14impl SelectIntoExecutor {
15    /// Execute a SELECT INTO statement
16    ///
17    /// This creates a new table with the specified name and inserts the query results.
18    /// Per SQL:1999 Feature E111, exactly one row must be returned.
19    pub fn execute(
20        stmt: &SelectStmt,
21        target_table: &str,
22        database: &mut Database,
23    ) -> Result<String, ExecutorError> {
24        // Validate that this is a SELECT INTO
25        if stmt.into_table.is_none() {
26            return Err(ExecutorError::Other(
27                "execute_select_into called on non-SELECT INTO statement".to_string(),
28            ));
29        }
30
31        // Execute the SELECT query
32        let executor = SelectExecutor::new(database);
33        let rows = executor.execute(stmt)?;
34
35        // SQL:1999 Feature E111 requires exactly one row
36        if rows.is_empty() {
37            return Err(ExecutorError::UnsupportedFeature(
38                "SELECT INTO returned no rows (expected exactly 1 row for Feature E111)"
39                    .to_string(),
40            ));
41        }
42        if rows.len() > 1 {
43            return Err(ExecutorError::UnsupportedFeature(format!(
44                "SELECT INTO returned {} rows (expected exactly 1 row for Feature E111)",
45                rows.len()
46            )));
47        }
48
49        // Derive column definitions from the SELECT list and result row
50        let column_defs = Self::derive_column_definitions(&stmt.select_list, &rows[0], database)?;
51
52        // Create the target table
53        let create_stmt = CreateTableStmt {
54            table_name: target_table.to_string(),
55            columns: column_defs,
56            table_constraints: vec![],
57            table_options: vec![],
58        };
59
60        crate::CreateTableExecutor::execute(&create_stmt, database)?;
61
62        // Insert the row
63        database
64            .insert_row(target_table, rows[0].clone())
65            .map_err(|e| ExecutorError::StorageError(e.to_string()))?;
66
67        Ok(format!("SELECT INTO: Created table '{}' with 1 row", target_table))
68    }
69
70    /// Derive column definitions from SELECT list and result row
71    fn derive_column_definitions(
72        select_list: &[SelectItem],
73        result_row: &vibesql_storage::Row,
74        database: &Database,
75    ) -> Result<Vec<ColumnDef>, ExecutorError> {
76        let mut columns = Vec::new();
77
78        for (idx, item) in select_list.iter().enumerate() {
79            match item {
80                SelectItem::Wildcard { .. } => {
81                    return Err(ExecutorError::UnsupportedFeature(
82                        "SELECT * is not supported in SELECT INTO statements".to_string(),
83                    ));
84                }
85                SelectItem::QualifiedWildcard { .. } => {
86                    return Err(ExecutorError::UnsupportedFeature(
87                        "SELECT table.* is not supported in SELECT INTO statements".to_string(),
88                    ));
89                }
90                SelectItem::Expression { expr, alias } => {
91                    // Column name: use alias if present, otherwise derive from expression
92                    let column_name = if let Some(alias) = alias {
93                        alias.clone()
94                    } else {
95                        Self::derive_column_name(expr, database)?
96                    };
97
98                    // Infer data type from the result value
99                    let data_type = Self::infer_data_type(&result_row.values[idx]);
100
101                    columns.push(ColumnDef {
102                        name: column_name,
103                        data_type,
104                        nullable: true, // Allow NULL by default
105                        constraints: vec![],
106                        default_value: None,
107                        comment: None,
108                    });
109                }
110            }
111        }
112
113        Ok(columns)
114    }
115
116    /// Derive a column name from an expression
117    fn derive_column_name(
118        expr: &vibesql_ast::Expression,
119        _database: &Database,
120    ) -> Result<String, ExecutorError> {
121        match expr {
122            vibesql_ast::Expression::ColumnRef { column, .. } => Ok(column.clone()),
123            vibesql_ast::Expression::Literal(_) => Ok("column".to_string()),
124            vibesql_ast::Expression::BinaryOp { .. } => Ok("expr".to_string()),
125            vibesql_ast::Expression::UnaryOp { .. } => Ok("expr".to_string()),
126            vibesql_ast::Expression::Function { name, .. } => Ok(name.to_lowercase()),
127            _ => Ok("column".to_string()),
128        }
129    }
130
131    /// Infer SQL data type from a runtime value
132    fn infer_data_type(value: &vibesql_types::SqlValue) -> DataType {
133        match value {
134            vibesql_types::SqlValue::Null => DataType::Varchar { max_length: Some(255) }, /* Default for */
135            // NULL
136            vibesql_types::SqlValue::Integer(_) => DataType::Integer,
137            vibesql_types::SqlValue::Bigint(_) => DataType::Bigint,
138            vibesql_types::SqlValue::Unsigned(_) => DataType::Unsigned,
139            vibesql_types::SqlValue::Smallint(_) => DataType::Smallint,
140            vibesql_types::SqlValue::Numeric(_) => DataType::Numeric { precision: 38, scale: 0 },
141            vibesql_types::SqlValue::Float(_) => DataType::Float { precision: 53 },
142            vibesql_types::SqlValue::Real(_) => DataType::Real,
143            vibesql_types::SqlValue::Double(_) => DataType::DoublePrecision,
144            vibesql_types::SqlValue::Varchar(s) | vibesql_types::SqlValue::Character(s) => {
145                DataType::Varchar { max_length: Some(s.len().max(255)) }
146            }
147            vibesql_types::SqlValue::Boolean(_) => DataType::Boolean,
148            vibesql_types::SqlValue::Date(_) => DataType::Date,
149            vibesql_types::SqlValue::Time(_) => DataType::Time { with_timezone: false },
150            vibesql_types::SqlValue::Timestamp(_) => DataType::Timestamp { with_timezone: false },
151            vibesql_types::SqlValue::Interval(_) => DataType::Interval {
152                start_field: vibesql_types::IntervalField::Year,
153                end_field: Some(vibesql_types::IntervalField::Month),
154            },
155            vibesql_types::SqlValue::Vector(v) => DataType::Vector { dimensions: v.len() as u32 },
156        }
157    }
158}