Skip to main content

no_mistakes_postgres_sql/
star_projection.rs

1use crate::erased_visit::VisitErased;
2use crate::fx::{FxHashMap, FxHashSet};
3use crate::idents::{ident_key, object_name_key};
4use sqlparser::ast::{
5    Distinct, OrderByExpr, OrderByKind, Query, Select, SelectItem, SetExpr, SetOperator,
6    SetQuantifier, TableFactor, TableWithJoins, Visitor,
7};
8use std::ops::ControlFlow;
9
10mod shadow;
11mod whole_row;
12pub use whole_row::WholeRowUses;
13
14pub fn query_order(query: &Query) -> &[OrderByExpr] {
15    match query.order_by.as_ref().map(|order| &order.kind) {
16        Some(OrderByKind::Expressions(exprs)) => exprs,
17        _ => &[],
18    }
19}
20
21#[derive(Default)]
22struct Uses {
23    references: usize,
24    narrowed: usize,
25}
26
27struct CteUses {
28    counts: FxHashMap<String, Uses>,
29    order_by: FxHashMap<*const Select, WholeRowUses>,
30}
31
32impl Visitor for CteUses {
33    type Break = ();
34
35    fn pre_visit_select(&mut self, select: &Select) -> ControlFlow<()> {
36        let mut whole_rows = None;
37        visit_unaliased_factors(&select.from, &mut |factor| {
38            let Some((name, alias)) = cte_reference(factor) else {
39                return;
40            };
41            if let Some(uses) = self.counts.get_mut(&name) {
42                let whole_rows = whole_rows.get_or_insert_with(|| {
43                    self.order_by
44                        .remove(&(select as *const Select))
45                        .unwrap_or_else(|| WholeRowUses::in_select(select, false, &[]))
46                });
47                if whole_rows.narrows(Some(&alias)) {
48                    uses.narrowed += 1;
49                }
50            }
51        });
52        ControlFlow::Continue(())
53    }
54
55    fn pre_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<()> {
56        if let Some((name, _)) = cte_reference(factor) {
57            if let Some(uses) = self.counts.get_mut(&name) {
58                uses.references += 1;
59            }
60        }
61        ControlFlow::Continue(())
62    }
63
64    fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
65        self.count_table_arms(&query.body);
66        if let SetExpr::Select(select) = query.body.as_ref() {
67            let order = query_order(query);
68            if !order.is_empty() {
69                self.order_by.insert(
70                    select.as_ref(),
71                    WholeRowUses::in_select(select, false, order),
72                );
73            }
74        }
75        ControlFlow::Continue(())
76    }
77}
78
79impl CteUses {
80    fn count_table_arms(&mut self, expr: &SetExpr) {
81        match expr {
82            SetExpr::Table(table) if table.schema_name.is_none() => {
83                if let Some(uses) = table
84                    .table_name
85                    .as_ref()
86                    .and_then(|name| self.counts.get_mut(&ident_key(name)))
87                {
88                    uses.references += 1;
89                }
90            }
91            SetExpr::SetOperation { left, right, .. } => {
92                self.count_table_arms(left);
93                self.count_table_arms(right);
94            }
95            _ => {}
96        }
97    }
98}
99
100fn visit_unaliased_factors(from: &[TableWithJoins], visit: &mut impl FnMut(&TableFactor)) {
101    for factor in from.iter().flat_map(|table| {
102        std::iter::once(&table.relation).chain(table.joins.iter().map(|join| &join.relation))
103    }) {
104        if let TableFactor::NestedJoin {
105            table_with_joins,
106            alias: None,
107        } = factor
108        {
109            visit_unaliased_factors(std::slice::from_ref(table_with_joins), visit);
110        } else {
111            visit(factor);
112        }
113    }
114}
115
116fn cte_reference(factor: &TableFactor) -> Option<(String, String)> {
117    let TableFactor::Table {
118        name,
119        alias,
120        args: None,
121        ..
122    } = factor
123    else {
124        return None;
125    };
126    if name.0.len() != 1 {
127        return None;
128    }
129    let name = object_name_key(name);
130    let alias = alias
131        .as_ref()
132        .map_or_else(|| name.clone(), |alias| ident_key(&alias.name));
133    Some((name, alias))
134}
135
136pub fn narrowed_ctes(query: &Query) -> FxHashSet<String> {
137    let Some(with) = query.with.as_ref().filter(|with| !with.recursive) else {
138        return FxHashSet::default();
139    };
140    let mut uses = CteUses {
141        counts: with
142            .cte_tables
143            .iter()
144            .map(|cte| (ident_key(&cte.alias.name), Uses::default()))
145            .collect(),
146        order_by: FxHashMap::default(),
147    };
148    let _ = query.visit_erased(&mut uses);
149    uses.counts
150        .into_iter()
151        .filter_map(|(name, uses)| {
152            (uses.references > 0 && uses.references == uses.narrowed).then_some(name)
153        })
154        .collect()
155}
156
157pub fn visible_items(select: &Select, narrowed: bool) -> impl Iterator<Item = &SelectItem> {
158    let narrowed = narrowed && !matches!(select.distinct, Some(Distinct::Distinct));
159    select.projection.iter().filter(move |item| {
160        !narrowed
161            || !matches!(
162                item,
163                SelectItem::Wildcard(_) | SelectItem::QualifiedWildcard(..)
164            )
165    })
166}
167
168pub fn keeps_narrowing(op: &SetOperator, quantifier: &SetQuantifier) -> bool {
169    matches!(
170        (op, quantifier),
171        (
172            SetOperator::Union,
173            SetQuantifier::All | SetQuantifier::AllByName
174        )
175    )
176}