no-mistakes-postgres-sql 0.109.131

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
mod count;

use self::count::count_boolean;
use crate::erased_visit::VisitErased;
use crate::idents::unwrap_expr;
use crate::statement_facts::{SqlQueryShape, SqlQueryShapeFact};
use sqlparser::ast::{
    Cte, CteAsMaterialized, Distinct, Expr, GroupByExpr, Query, SelectItem, SetExpr, Spanned,
    Statement, UnaryOperator, Visitor,
};
use sqlparser::tokenizer::{Location, Token, TokenWithSpan};
use std::ops::ControlFlow;

fn candidate_tokens(tokens: &[TokenWithSpan]) -> bool {
    tokens.iter().any(|token| {
        matches!(&token.token, Token::Word(word) if word.value.eq_ignore_ascii_case("materialized")
            || word.value.eq_ignore_ascii_case("count"))
    })
}

pub(super) fn collect(
    statements: &[Statement],
    sources: &super::StatementSources<'_>,
    tokens: &[TokenWithSpan],
) -> Vec<SqlQueryShapeFact> {
    let mut out = Vec::new();
    let source_has_shape = candidate_tokens(tokens);
    for (index, statement) in statements.iter().enumerate() {
        let recovered = sources
            .tokens
            .and_then(|items| items.get(index))
            .and_then(Option::as_ref);
        if !source_has_shape && !recovered.is_some_and(|tokens| candidate_tokens(tokens)) {
            continue;
        }
        let mut executed = Vec::new();
        crate::statements::walk_executed(statement, &mut executed);
        for statement in executed {
            let _ = statement.visit_erased(&mut Collector(&mut out));
        }
    }
    out
}

struct Collector<'a>(&'a mut Vec<SqlQueryShapeFact>);

impl Collector<'_> {
    fn push(&mut self, shape: SqlQueryShape, position: Location) {
        self.0.push(SqlQueryShapeFact {
            shape,
            line: position.line.max(1) as usize,
            column: position.column.max(1) as usize,
        });
    }
}

impl Visitor for Collector<'_> {
    type Break = ();

    fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
        if let Some(with) = &query.with {
            for cte in with
                .cte_tables
                .iter()
                .filter(|cte| constant_materialized(cte))
            {
                self.push(
                    SqlQueryShape::ConstantMaterializedCte,
                    cte.alias.name.span.start,
                );
            }
        }
        ControlFlow::Continue(())
    }

    fn pre_visit_expr(&mut self, expression: &Expr) -> ControlFlow<()> {
        if let Expr::Function(function) = expression {
            if count_boolean(function) {
                self.push(
                    SqlQueryShape::CountBooleanExpression,
                    function.name.span().start,
                );
            }
        }
        ControlFlow::Continue(())
    }
}

fn constant_materialized(cte: &Cte) -> bool {
    let query = &cte.query;
    let SetExpr::Select(select) = &*query.body else {
        return false;
    };
    cte.materialized == Some(CteAsMaterialized::Materialized)
        && query.with.is_none()
        && query.limit_clause.is_none()
        && query.fetch.is_none()
        && query.locks.is_empty()
        && query.order_by.is_none()
        && select.into.is_none()
        && select.from.is_empty()
        && select.selection.is_none()
        && select.having.is_none()
        && select.named_window.is_empty()
        && match &select.distinct {
            Some(Distinct::On(expressions)) => expressions.iter().all(constant),
            _ => true,
        }
        && matches!(&select.group_by, GroupByExpr::Expressions(items, modifiers)
            if items.is_empty() && modifiers.is_empty())
        && !select.projection.is_empty()
        && select.projection.iter().all(|item| match item {
            SelectItem::UnnamedExpr(expr) | SelectItem::ExprWithAlias { expr, .. } => {
                constant(expr)
            }
            _ => false,
        })
}

fn constant(expr: &Expr) -> bool {
    match unwrap_expr(expr) {
        Expr::Value(_) | Expr::TypedString(_) => true,
        Expr::Interval(interval) => constant(&interval.value),
        Expr::Cast { expr, .. }
        | Expr::UnaryOp {
            op: UnaryOperator::Plus | UnaryOperator::Minus,
            expr,
        } => constant(expr),
        _ => false,
    }
}