Skip to main content

no_mistakes_postgres_sql/conflict/
scope.rs

1//! Source facts the conflict-ordering rule needs to normalize `ORDER BY` keys: which select
2//! expressions are bound values, and which relations a bare column name can resolve to.
3use super::pinned::expr_is_constant;
4use super::single_row::projection_expr;
5use sqlparser::ast::{Query, SetExpr, TableFactor, TableWithJoins};
6use std::collections::BTreeSet;
7
8/// A relation in the source `FROM` clause; `columns` is `None` when its columns are unknown
9/// (a plain table, whose columns only the database knows).
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct SqlSourceRelation {
12    pub qualifier: Option<String>,
13    pub columns: Option<Vec<String>>,
14}
15
16/// Select-list expressions that are literals or bound parameters. Computed with the recovered
17/// placeholder positions, so a user identifier spelled like a placeholder is not included. A
18/// spelling shared with a non-constant projection is left out: the text cannot tell them apart.
19pub(super) fn constant_projections(query: &Query, binds: &[(u32, u32)]) -> BTreeSet<String> {
20    let SetExpr::Select(select) = query.body.as_ref() else {
21        return BTreeSet::new();
22    };
23    let (constant, varying): (Vec<_>, Vec<_>) = select
24        .projection
25        .iter()
26        .filter_map(projection_expr)
27        .partition(|expr| expr_is_constant(expr, binds));
28    let varying: BTreeSet<String> = varying.iter().map(ToString::to_string).collect();
29    constant
30        .iter()
31        .map(ToString::to_string)
32        .filter(|text| !varying.contains(text))
33        .collect()
34}
35
36/// Every relation of a plain `SELECT ... FROM`, or `None` when the scope cannot be listed
37/// (nested joins, set operations, pivots), in which case a bare name stays unresolved.
38pub(super) fn source_relations(query: &Query) -> Option<Vec<SqlSourceRelation>> {
39    let SetExpr::Select(select) = query.body.as_ref() else {
40        return None;
41    };
42    let mut relations = Vec::new();
43    for from in &select.from {
44        push_relations(from, &mut relations)?;
45    }
46    Some(relations)
47}
48
49fn push_relations(from: &TableWithJoins, relations: &mut Vec<SqlSourceRelation>) -> Option<()> {
50    relations.push(relation(&from.relation)?);
51    for join in &from.joins {
52        relations.push(relation(&join.relation)?);
53    }
54    Some(())
55}
56
57fn relation(factor: &TableFactor) -> Option<SqlSourceRelation> {
58    let (alias, name) = match factor {
59        TableFactor::Table { name, alias, .. } => {
60            (alias, name.0.last().map(|part| part.to_string()))
61        }
62        TableFactor::Derived { alias, .. }
63        | TableFactor::Function { alias, .. }
64        | TableFactor::TableFunction { alias, .. }
65        | TableFactor::UNNEST { alias, .. } => (alias, None),
66        _ => return None,
67    };
68    let qualifier = alias
69        .as_ref()
70        .map(|alias| alias.name.value.clone())
71        .or(name.map(|name| name.trim_matches('"').to_owned()))
72        .map(|name| name.to_ascii_lowercase());
73    let columns = alias
74        .as_ref()
75        .filter(|alias| !alias.columns.is_empty())
76        .map(|alias| {
77            alias
78                .columns
79                .iter()
80                .map(|column| column.name.value.to_ascii_lowercase())
81                .collect()
82        });
83    Some(SqlSourceRelation { qualifier, columns })
84}