Skip to main content

no_mistakes_postgres_sql/star_projection/
whole_row.rs

1use super::shadow::Shadows;
2use crate::idents::{ident_key, object_name_key};
3use crate::{erased_visit::VisitErased, fx::FxHashSet};
4use sqlparser::ast::{
5    AccessExpr, Expr, FunctionArg, FunctionArgExpr, FunctionArguments, JoinConstraint,
6    JoinOperator, OrderByExpr, Query, Select, SelectItem, SelectItemQualifiedWildcardKind,
7    TableFactor, Visitor,
8};
9use std::ops::ControlFlow;
10
11#[derive(Default)]
12pub struct WholeRowUses {
13    all: bool,
14    names: FxHashSet<String>,
15    depth: usize,
16    field_roots: Vec<*const Expr>,
17    shadows: Shadows,
18}
19
20impl WholeRowUses {
21    pub fn for_derived(select: &Select, narrowed: bool, order: &[OrderByExpr]) -> Option<Self> {
22        fn has_derived(factor: &TableFactor) -> bool {
23            match factor {
24                TableFactor::Derived { .. } => true,
25                TableFactor::NestedJoin {
26                    table_with_joins, ..
27                } => {
28                    has_derived(&table_with_joins.relation)
29                        || table_with_joins
30                            .joins
31                            .iter()
32                            .any(|join| has_derived(&join.relation))
33                }
34                _ => false,
35            }
36        }
37        select
38            .from
39            .iter()
40            .any(|table| {
41                has_derived(&table.relation)
42                    || table.joins.iter().any(|join| has_derived(&join.relation))
43            })
44            .then(|| Self::in_select(select, narrowed, order))
45    }
46
47    pub(super) fn in_select(select: &Select, narrowed: bool, order: &[OrderByExpr]) -> Self {
48        let mut uses = Self::default();
49        for item in super::visible_items(select, narrowed) {
50            uses.record_projection(item);
51        }
52        let _ = select.projection.visit_erased(&mut uses);
53        let _ = select.distinct.visit_erased(&mut uses);
54        let _ = select.selection.visit_erased(&mut uses);
55        let _ = select.having.visit_erased(&mut uses);
56        let _ = select.group_by.visit_erased(&mut uses);
57        let _ = select.named_window.visit_erased(&mut uses);
58        for expression in order {
59            let _ = expression.visit_erased(&mut uses);
60        }
61        for table in &select.from {
62            uses.visit_factor(&table.relation);
63            for join in &table.joins {
64                uses.visit_factor(&join.relation);
65                let _ = join.join_operator.visit_erased(&mut uses);
66                uses.all |= is_natural(&join.join_operator);
67            }
68        }
69        uses
70    }
71
72    pub fn narrows_derived(&self, factor: &TableFactor) -> bool {
73        matches!(factor, TableFactor::Derived { alias, .. }
74            if self.narrows(alias.as_ref().map(|alias| ident_key(&alias.name)).as_deref()))
75    }
76    pub(super) fn narrows(&self, name: Option<&str>) -> bool {
77        !self.all && name.is_none_or(|name| !self.names.contains(name))
78    }
79
80    fn visit_factor(&mut self, factor: &TableFactor) {
81        match factor {
82            TableFactor::Derived { lateral: false, .. } => {}
83            TableFactor::NestedJoin {
84                table_with_joins, ..
85            } => {
86                self.visit_factor(&table_with_joins.relation);
87                for join in &table_with_joins.joins {
88                    self.visit_factor(&join.relation);
89                    let _ = join.join_operator.visit_erased(self);
90                }
91            }
92            other => {
93                let _ = other.visit_erased(self);
94            }
95        }
96    }
97
98    fn record_projection(&mut self, item: &SelectItem) {
99        match item {
100            SelectItem::Wildcard(_) if self.depth == 0 => self.all = true,
101            SelectItem::QualifiedWildcard(SelectItemQualifiedWildcardKind::ObjectName(name), _) => {
102                self.note(object_name_key(name));
103            }
104            _ => {}
105        }
106    }
107
108    fn note(&mut self, name: String) {
109        if !self.shadows.hides(&name) {
110            self.names.insert(name);
111        }
112    }
113}
114
115fn is_natural(op: &JoinOperator) -> bool {
116    use JoinOperator::*;
117    matches!(
118        op,
119        Join(JoinConstraint::Natural)
120            | Inner(JoinConstraint::Natural)
121            | Left(JoinConstraint::Natural)
122            | LeftOuter(JoinConstraint::Natural)
123            | Right(JoinConstraint::Natural)
124            | RightOuter(JoinConstraint::Natural)
125            | FullOuter(JoinConstraint::Natural)
126    )
127}
128
129impl Visitor for WholeRowUses {
130    type Break = ();
131
132    fn pre_visit_query(&mut self, _: &Query) -> ControlFlow<()> {
133        self.depth += 1;
134        ControlFlow::Continue(())
135    }
136
137    fn post_visit_query(&mut self, _: &Query) -> ControlFlow<()> {
138        self.depth -= 1;
139        ControlFlow::Continue(())
140    }
141
142    fn pre_visit_select(&mut self, select: &Select) -> ControlFlow<()> {
143        self.shadows.enter_select(&select.from);
144        for item in &select.projection {
145            self.record_projection(item);
146        }
147        ControlFlow::Continue(())
148    }
149
150    fn post_visit_select(&mut self, _: &Select) -> ControlFlow<()> {
151        self.shadows.leave_select();
152        ControlFlow::Continue(())
153    }
154
155    fn pre_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<()> {
156        self.shadows.enter_factor(factor);
157        ControlFlow::Continue(())
158    }
159
160    fn post_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<()> {
161        self.shadows.leave_factor(factor);
162        ControlFlow::Continue(())
163    }
164
165    fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
166        match expr {
167            Expr::Identifier(name) => {
168                if !self.field_roots.contains(&(expr as *const Expr)) {
169                    self.note(ident_key(name));
170                }
171            }
172            Expr::CompoundFieldAccess { root, access_chain }
173                if matches!(access_chain.first(), Some(AccessExpr::Dot(_))) =>
174            {
175                let mut root = root.as_ref();
176                while let Expr::Nested(inner) = root {
177                    root = inner;
178                }
179                self.field_roots.push(root);
180            }
181            Expr::QualifiedWildcard(name, _) => self.note(object_name_key(name)),
182            Expr::Wildcard(_) if self.depth == 0 => self.all = true,
183            Expr::Function(func) => {
184                if let FunctionArguments::List(args) = &func.args {
185                    for arg in &args.args {
186                        if let FunctionArgExpr::QualifiedWildcard(name) = match arg {
187                            FunctionArg::Unnamed(arg)
188                            | FunctionArg::Named { arg, .. }
189                            | FunctionArg::ExprNamed { arg, .. } => arg,
190                        } {
191                            self.note(object_name_key(name));
192                        }
193                    }
194                }
195            }
196            _ => {}
197        }
198        ControlFlow::Continue(())
199    }
200}