no-mistakes-postgres-sql 0.109.131

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use super::super::super::super::value::is_placeholder_ident_at;
use crate::idents::ident_key;
use sqlparser::ast::{Expr, GroupByExpr, OrderByKind, Query, SelectItem, SetExpr};
use std::collections::BTreeSet;

/// Projection labels are known only when every expression has a syntactic output name.
/// Stars and unnamed complex expressions preserve PostgreSQL's unknown-column fallback.
pub(in super::super::super) fn projection_columns(query: &Query) -> Option<BTreeSet<String>> {
    set_columns(&query.body)
}

/// The alias list replaces only the first projection names; later names stay visible.
pub(super) fn partial_alias_columns(
    query: &Query,
    alias: &sqlparser::ast::TableAlias,
) -> Option<BTreeSet<String>> {
    let mut columns: BTreeSet<String> = alias
        .columns
        .iter()
        .map(|column| ident_key(&column.name))
        .collect();
    columns.extend(projection_suffix(&query.body, alias.columns.len())?);
    Some(columns)
}

fn projection_suffix(set: &SetExpr, hidden: usize) -> Option<BTreeSet<String>> {
    match set {
        SetExpr::Select(select) => {
            let prefix = select.projection.get(..hidden)?;
            if prefix.iter().any(|item| {
                matches!(
                    item,
                    SelectItem::Wildcard(_) | SelectItem::QualifiedWildcard(_, _)
                )
            }) {
                return None;
            }
            // The prefix lookup above proves this start index is in bounds.
            select.projection[hidden..].iter().map(label_name).collect()
        }
        SetExpr::Query(query) => projection_suffix(&query.body, hidden),
        SetExpr::SetOperation { left, .. } => projection_suffix(left, hidden),
        SetExpr::Values(values) => {
            // The SQL parser only constructs VALUES with at least one row.
            let width = values.rows[0].len();
            (width == hidden).then(BTreeSet::new)
        }
        _ => None,
    }
}

fn set_columns(set: &SetExpr) -> Option<BTreeSet<String>> {
    match set {
        SetExpr::Select(select) => select.projection.iter().map(label_name).collect(),
        SetExpr::Query(query) => projection_columns(query),
        SetExpr::SetOperation { left, .. } => set_columns(left),
        _ => None,
    }
}

/// A syntactic output label can name a grouping expression in the same SELECT arm.
pub(super) fn label_name(item: &SelectItem) -> Option<String> {
    match item {
        SelectItem::ExprWithAlias { alias, .. } => Some(ident_key(alias)),
        SelectItem::UnnamedExpr(Expr::Identifier(ident)) => Some(ident_key(ident)),
        SelectItem::UnnamedExpr(Expr::CompoundIdentifier(parts)) => parts.last().map(ident_key),
        _ => None,
    }
}

/// The names written alone as an `ORDER BY` or `GROUP BY` item: PostgreSQL reads each as an
/// output column's name before it reads it as a column of a relation.
pub(super) fn output_names(query: &Query, positions: Option<&[(u32, u32)]>) -> Vec<String> {
    let mut items: Vec<&Expr> = Vec::new();
    if let Some(order) = &query.order_by {
        if let OrderByKind::Expressions(expressions) = &order.kind {
            items.extend(expressions.iter().map(|expression| &expression.expr));
        }
    }
    if let SetExpr::Select(select) = &*query.body {
        if let GroupByExpr::Expressions(expressions, _) = &select.group_by {
            items.extend(expressions);
        }
    }
    items
        .into_iter()
        .filter_map(|item| match item {
            Expr::Identifier(ident) if !is_placeholder_ident_at(ident, positions) => {
                Some(ident_key(ident))
            }
            _ => None,
        })
        .collect()
}

#[cfg(all(test, any(nm_shard_all, nm_shard_1)))]
mod tests;