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            if_not_exists: false,
55            table_name: target_table.to_string(),
56            columns: column_defs,
57            table_constraints: vec![],
58            table_options: vec![],
59        };
60
61        crate::CreateTableExecutor::execute(&create_stmt, database)?;
62
63        // Insert the row
64        database
65            .insert_row(target_table, rows[0].clone())
66            .map_err(|e| ExecutorError::StorageError(e.to_string()))?;
67
68        Ok(format!("SELECT INTO: Created table '{}' with 1 row", target_table))
69    }
70
71    /// Derive column definitions from SELECT list and result row
72    fn derive_column_definitions(
73        select_list: &[SelectItem],
74        result_row: &vibesql_storage::Row,
75        database: &Database,
76    ) -> Result<Vec<ColumnDef>, ExecutorError> {
77        let mut columns = Vec::new();
78
79        for (idx, item) in select_list.iter().enumerate() {
80            match item {
81                SelectItem::Wildcard { .. } => {
82                    return Err(ExecutorError::UnsupportedFeature(
83                        "SELECT * is not supported in SELECT INTO statements".to_string(),
84                    ));
85                }
86                SelectItem::QualifiedWildcard { .. } => {
87                    return Err(ExecutorError::UnsupportedFeature(
88                        "SELECT table.* is not supported in SELECT INTO statements".to_string(),
89                    ));
90                }
91                SelectItem::Expression { expr, alias } => {
92                    // Column name: use alias if present, otherwise derive from expression
93                    let column_name = if let Some(alias) = alias {
94                        alias.clone()
95                    } else {
96                        Self::derive_column_name(expr, database)?
97                    };
98
99                    // Infer data type from the result value
100                    let data_type = Self::infer_data_type(&result_row.values[idx]);
101
102                    columns.push(ColumnDef {
103                        name: column_name,
104                        data_type,
105                        nullable: true, // Allow NULL by default
106                        constraints: vec![],
107                        default_value: None,
108                        comment: None,
109                    });
110                }
111            }
112        }
113
114        Ok(columns)
115    }
116
117    /// Derive a column name from an expression
118    fn derive_column_name(
119        expr: &vibesql_ast::Expression,
120        _database: &Database,
121    ) -> Result<String, ExecutorError> {
122        match expr {
123            vibesql_ast::Expression::ColumnRef { column, .. } => Ok(column.clone()),
124            vibesql_ast::Expression::Literal(_) => Ok("column".to_string()),
125            vibesql_ast::Expression::BinaryOp { .. } => Ok("expr".to_string()),
126            vibesql_ast::Expression::UnaryOp { .. } => Ok("expr".to_string()),
127            vibesql_ast::Expression::Function { name, .. } => Ok(name.to_lowercase()),
128            _ => Ok("column".to_string()),
129        }
130    }
131
132    /// Infer SQL data type from a runtime value
133    fn infer_data_type(value: &vibesql_types::SqlValue) -> DataType {
134        match value {
135            vibesql_types::SqlValue::Null => DataType::Varchar { max_length: Some(255) }, /* Default for */
136            // NULL
137            vibesql_types::SqlValue::Integer(_) => DataType::Integer,
138            vibesql_types::SqlValue::Bigint(_) => DataType::Bigint,
139            vibesql_types::SqlValue::Unsigned(_) => DataType::Unsigned,
140            vibesql_types::SqlValue::Smallint(_) => DataType::Smallint,
141            vibesql_types::SqlValue::Numeric(_) => DataType::Numeric { precision: 38, scale: 0 },
142            vibesql_types::SqlValue::Float(_) => DataType::Float { precision: 53 },
143            vibesql_types::SqlValue::Real(_) => DataType::Real,
144            vibesql_types::SqlValue::Double(_) => DataType::DoublePrecision,
145            vibesql_types::SqlValue::Varchar(s) | vibesql_types::SqlValue::Character(s) => {
146                DataType::Varchar { max_length: Some(s.len().max(255)) }
147            }
148            vibesql_types::SqlValue::Boolean(_) => DataType::Boolean,
149            vibesql_types::SqlValue::Date(_) => DataType::Date,
150            vibesql_types::SqlValue::Time(_) => DataType::Time { with_timezone: false },
151            vibesql_types::SqlValue::Timestamp(_) => DataType::Timestamp { with_timezone: false },
152            vibesql_types::SqlValue::Interval(_) => DataType::Interval {
153                start_field: vibesql_types::IntervalField::Year,
154                end_field: Some(vibesql_types::IntervalField::Month),
155            },
156            vibesql_types::SqlValue::Vector(v) => DataType::Vector { dimensions: v.len() as u32 },
157        }
158    }
159}