use crate::idents::ident_key;
use sqlparser::ast::{SelectItem, SetExpr, TableFactor};
pub(super) fn columns(factor: &TableFactor) -> Option<Vec<String>> {
if let Some((width, alias)) = super::super::super::table::derived_values_shape(factor) {
return Some(
(0..width)
.map(|index| {
alias
.and_then(|alias| alias.columns.get(index))
.map_or_else(
|| format!("column{}", index + 1),
|column| ident_key(&column.name),
)
})
.collect(),
);
}
let TableFactor::Derived {
subquery, alias, ..
} = factor
else {
return None;
};
let mut body = subquery.body.as_ref();
loop {
match body {
SetExpr::Query(query) => body = query.body.as_ref(),
SetExpr::SetOperation { left, .. } => body = left,
_ => break,
}
}
let select = body.as_select()?;
select
.projection
.iter()
.enumerate()
.map(|(index, item)| {
if !matches!(
item,
SelectItem::ExprWithAlias { .. } | SelectItem::UnnamedExpr(_)
) {
return None;
}
alias
.as_ref()
.and_then(|alias| alias.columns.get(index))
.map(|column| ident_key(&column.name))
.or_else(|| super::super::query_frame::output_label(item))
.or_else(|| Some("?column?".to_owned()))
})
.collect()
}