no-mistakes-postgres-sql 0.109.130

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use crate::fx::FxHashSet;
use crate::idents::{ident_key, unwrap_expr};
use crate::output_label::{
    leftmost_output, query_projection_labels_with_ctes, query_select_labels_with_ctes,
    select_projection_labels_with_ctes, OuterCteOutputs,
};
use crate::statements::keyed_lookups::grouping::grouping_keys;
use sqlparser::ast::{Distinct, Expr, GroupByExpr, OrderByKind, Query, Select};

pub(super) fn query_target_names<'a>(
    query: &'a Query,
    outer_ctes: Option<OuterCteOutputs<'a>>,
) -> impl Iterator<Item = *const Expr> + 'a {
    let order = query.order_by.as_ref().and_then(|order| {
        if let OrderByKind::Expressions(items) = &order.kind {
            Some(items)
        } else {
            None
        }
    });
    let labels = leftmost_output(&query.body).as_select().map(|select| {
        query_projection_labels_with_ctes(query, outer_ctes, None)
            .unwrap_or_else(|| query_select_labels_with_ctes(query, select, outer_ctes, None))
            .into_iter()
            .flatten()
            .collect()
    });
    standalone_names(order.into_iter().flatten().map(|item| &item.expr), labels)
}

pub(super) fn select_target_names<'a>(
    select: &'a Select,
    outer_ctes: Option<OuterCteOutputs<'a>>,
) -> impl Iterator<Item = *const Expr> + 'a {
    let distinct = match &select.distinct {
        Some(Distinct::On(items)) => items.as_slice(),
        _ => &[],
    };
    let grouping = match &select.group_by {
        GroupByExpr::Expressions(items, _) => grouping_keys(items),
        _ => Vec::new(),
    };
    let labels = select_projection_labels_with_ctes(select, outer_ctes, None)
        .into_iter()
        .flatten()
        .collect();
    standalone_names(distinct.iter().chain(grouping), Some(labels))
}

fn standalone_names<'a>(
    expressions: impl Iterator<Item = &'a Expr> + 'a,
    labels: Option<FxHashSet<String>>,
) -> impl Iterator<Item = *const Expr> + 'a {
    expressions
        .map(unwrap_expr)
        .filter(move |expr| {
            matches!(expr, Expr::Identifier(name) if labels.as_ref().is_none_or(|labels| labels.contains(&ident_key(name))))
        })
        .map(std::ptr::from_ref)
}