1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
//! RETURNING clause projection for DML statements (SQLite 3.35.0+)
//!
//! SQLite semantics: RETURNING yields one result row per affected row.
//! UPDATE evaluates against the NEW row values (after SET assignments);
//! DELETE evaluates against the OLD row values (before deletion). For
//! statements on views routed through INSTEAD OF triggers, the view row
//! is returned once per trigger fire, regardless of what the trigger body
//! actually does.
//!
//! The projection itself is statement-agnostic: callers pass the rows to
//! evaluate against (NEW rows for UPDATE, OLD rows for DELETE).
use vibesql_ast::{Expression, SelectItem};
use vibesql_catalog::TableSchema;
use vibesql_storage::{Database, Row};
use crate::{errors::ExecutorError, evaluator::ExpressionEvaluator, select::SelectResult};
/// Project RETURNING select items against a set of rows.
///
/// `rows` must contain values in `schema` column order (one entry per
/// affected row / trigger fire). Returns a `SelectResult` whose columns are
/// derived from the RETURNING items (aliases win, then original source
/// text, then the expression's column name).
///
/// `cte_results` carries the enclosing statement's WITH-clause CTEs (if any)
/// so subqueries in RETURNING expressions can reference CTE names, matching
/// SQLite (issue #5359).
pub(crate) fn project_returning(
items: &[SelectItem],
schema: &TableSchema,
database: &Database,
table_alias: Option<&str>,
rows: &[&Row],
cte_results: Option<&std::collections::HashMap<String, crate::select::cte::CteResult>>,
) -> Result<SelectResult, ExecutorError> {
let mut evaluator = ExpressionEvaluator::with_database(schema, database);
if let Some(ctes) = cte_results {
evaluator = evaluator.with_cte_context(ctes);
}
if let Some(alias) = table_alias {
evaluator.set_table_alias(alias.to_string());
}
// Indices of columns expanded by `*` (hidden `__hidden__*` view columns
// are excluded, matching SQLite's hidden-column convention).
let visible_columns: Vec<usize> = schema
.columns
.iter()
.enumerate()
.filter(|(_, c)| !c.name.starts_with("__hidden__"))
.map(|(i, _)| i)
.collect();
// Derive result column names (computable even with zero updated rows).
let mut columns: Vec<String> = Vec::new();
for item in items {
match item {
SelectItem::Wildcard { .. } => {
columns.extend(visible_columns.iter().map(|&i| schema.columns[i].name.clone()));
}
SelectItem::QualifiedWildcard { qualifier, .. } => {
validate_wildcard_qualifier(qualifier, schema, table_alias)?;
columns.extend(visible_columns.iter().map(|&i| schema.columns[i].name.clone()));
}
SelectItem::Expression { expr, alias, source_text } => {
let name = if let Some(alias) = alias {
alias.clone()
} else if let Expression::ColumnRef(col_id) = expr {
col_id.column_canonical().to_string()
} else if let Some(text) = source_text {
text.clone()
} else {
format!("{:?}", expr)
};
columns.push(name);
}
}
}
// Evaluate each item against each row.
let mut result_rows: Vec<Row> = Vec::with_capacity(rows.len());
for row in rows {
// Clear the CSE cache so expression results from the previous row
// are not replayed for this one.
evaluator.clear_cse_cache();
let mut values = Vec::with_capacity(columns.len());
for item in items {
match item {
SelectItem::Wildcard { .. } | SelectItem::QualifiedWildcard { .. } => {
for &i in &visible_columns {
values.push(
row.values
.get(i)
.cloned()
.ok_or(ExecutorError::ColumnIndexOutOfBounds { index: i })?,
);
}
}
SelectItem::Expression { expr, .. } => {
values.push(evaluator.eval(expr, row)?);
}
}
}
result_rows.push(Row::new(values));
}
Ok(SelectResult { columns, rows: result_rows })
}
/// Validate that a qualified wildcard (`t.*`) refers to the target table.
fn validate_wildcard_qualifier(
qualifier: &str,
schema: &TableSchema,
table_alias: Option<&str>,
) -> Result<(), ExecutorError> {
let matches_table = qualifier.eq_ignore_ascii_case(&schema.name)
|| table_alias.is_some_and(|a| qualifier.eq_ignore_ascii_case(a));
if matches_table {
Ok(())
} else {
Err(ExecutorError::TableNotFound(qualifier.to_string()))
}
}