use super::shadow::Shadows;
use crate::fx::FxHashSet;
use crate::idents::{ident_key, object_name_key};
use sqlparser::ast::{
AccessExpr, Expr, FunctionArg, FunctionArgExpr, FunctionArguments, JoinConstraint,
JoinOperator, OrderByExpr, Query, Select, SelectItem, SelectItemQualifiedWildcardKind,
TableFactor, Visit, Visitor,
};
use std::ops::ControlFlow;
#[derive(Default)]
pub struct WholeRowUses {
all: bool,
names: FxHashSet<String>,
depth: usize,
field_roots: Vec<*const Expr>,
shadows: Shadows,
}
impl WholeRowUses {
pub fn for_derived(select: &Select, narrowed: bool, order: &[OrderByExpr]) -> Option<Self> {
fn has_derived(factor: &TableFactor) -> bool {
match factor {
TableFactor::Derived { .. } => true,
TableFactor::NestedJoin {
table_with_joins, ..
} => {
has_derived(&table_with_joins.relation)
|| table_with_joins
.joins
.iter()
.any(|join| has_derived(&join.relation))
}
_ => false,
}
}
select
.from
.iter()
.any(|table| {
has_derived(&table.relation)
|| table.joins.iter().any(|join| has_derived(&join.relation))
})
.then(|| Self::in_select(select, narrowed, order))
}
pub(super) fn in_select(select: &Select, narrowed: bool, order: &[OrderByExpr]) -> Self {
let mut uses = Self::default();
for item in super::visible_items(select, narrowed) {
uses.record_projection(item);
}
let _ = select.projection.visit(&mut uses);
let _ = select.distinct.visit(&mut uses);
let _ = select.selection.visit(&mut uses);
let _ = select.having.visit(&mut uses);
let _ = select.group_by.visit(&mut uses);
let _ = select.named_window.visit(&mut uses);
for expression in order {
let _ = expression.visit(&mut uses);
}
for table in &select.from {
uses.visit_factor(&table.relation);
for join in &table.joins {
uses.visit_factor(&join.relation);
let _ = join.join_operator.visit(&mut uses);
uses.all |= is_natural(&join.join_operator);
}
}
uses
}
pub fn narrows_derived(&self, factor: &TableFactor) -> bool {
matches!(factor, TableFactor::Derived { alias, .. }
if self.narrows(alias.as_ref().map(|alias| ident_key(&alias.name)).as_deref()))
}
pub(super) fn narrows(&self, name: Option<&str>) -> bool {
!self.all && name.is_none_or(|name| !self.names.contains(name))
}
fn visit_factor(&mut self, factor: &TableFactor) {
match factor {
TableFactor::Derived { lateral: false, .. } => {}
TableFactor::NestedJoin {
table_with_joins, ..
} => {
self.visit_factor(&table_with_joins.relation);
for join in &table_with_joins.joins {
self.visit_factor(&join.relation);
let _ = join.join_operator.visit(self);
}
}
other => {
let _ = other.visit(self);
}
}
}
fn record_projection(&mut self, item: &SelectItem) {
match item {
SelectItem::Wildcard(_) if self.depth == 0 => self.all = true,
SelectItem::QualifiedWildcard(SelectItemQualifiedWildcardKind::ObjectName(name), _) => {
self.note(object_name_key(name));
}
_ => {}
}
}
fn note(&mut self, name: String) {
if !self.shadows.hides(&name) {
self.names.insert(name);
}
}
}
fn is_natural(op: &JoinOperator) -> bool {
use JoinOperator::*;
matches!(
op,
Join(JoinConstraint::Natural)
| Inner(JoinConstraint::Natural)
| Left(JoinConstraint::Natural)
| LeftOuter(JoinConstraint::Natural)
| Right(JoinConstraint::Natural)
| RightOuter(JoinConstraint::Natural)
| FullOuter(JoinConstraint::Natural)
)
}
impl Visitor for WholeRowUses {
type Break = ();
fn pre_visit_query(&mut self, _: &Query) -> ControlFlow<()> {
self.depth += 1;
ControlFlow::Continue(())
}
fn post_visit_query(&mut self, _: &Query) -> ControlFlow<()> {
self.depth -= 1;
ControlFlow::Continue(())
}
fn pre_visit_select(&mut self, select: &Select) -> ControlFlow<()> {
self.shadows.enter_select(&select.from);
for item in &select.projection {
self.record_projection(item);
}
ControlFlow::Continue(())
}
fn post_visit_select(&mut self, _: &Select) -> ControlFlow<()> {
self.shadows.leave_select();
ControlFlow::Continue(())
}
fn pre_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<()> {
self.shadows.enter_factor(factor);
ControlFlow::Continue(())
}
fn post_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<()> {
self.shadows.leave_factor(factor);
ControlFlow::Continue(())
}
fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
match expr {
Expr::Identifier(name) => {
if !self.field_roots.contains(&(expr as *const Expr)) {
self.note(ident_key(name));
}
}
Expr::CompoundFieldAccess { root, access_chain }
if matches!(access_chain.first(), Some(AccessExpr::Dot(_))) =>
{
let mut root = root.as_ref();
while let Expr::Nested(inner) = root {
root = inner;
}
self.field_roots.push(root);
}
Expr::QualifiedWildcard(name, _) => self.note(object_name_key(name)),
Expr::Wildcard(_) if self.depth == 0 => self.all = true,
Expr::Function(func) => {
if let FunctionArguments::List(args) = &func.args {
for arg in &args.args {
if let FunctionArgExpr::QualifiedWildcard(name) = match arg {
FunctionArg::Unnamed(arg)
| FunctionArg::Named { arg, .. }
| FunctionArg::ExprNamed { arg, .. } => arg,
} {
self.note(object_name_key(name));
}
}
}
}
_ => {}
}
ControlFlow::Continue(())
}
}