no-mistakes-postgres-sql 0.109.131

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use crate::erased_visit::VisitErased;
use crate::types::{SqlComplexQuery, SqlQueryComplexity};
use sqlparser::ast::{
    CteAsMaterialized, Distinct, Query, SetExpr, SetOperator, Statement, TableFactor, Visitor,
};
use sqlparser::tokenizer::{Location, Token, TokenWithSpan, Whitespace};
use std::collections::BTreeSet;
use std::ops::ControlFlow;

#[derive(Default)]
struct Complexity(BTreeSet<SqlQueryComplexity>);

impl Visitor for Complexity {
    type Break = ();

    fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
        if let Some(with) = &query.with {
            if with.recursive {
                self.0.insert(SqlQueryComplexity::RecursiveCte);
            }
            if with
                .cte_tables
                .iter()
                .any(|cte| cte.materialized == Some(CteAsMaterialized::Materialized))
            {
                self.0.insert(SqlQueryComplexity::Materialized);
            }
        }
        self.set_expression(&query.body);
        ControlFlow::Continue(())
    }

    fn pre_visit_table_factor(&mut self, table_factor: &TableFactor) -> ControlFlow<()> {
        if matches!(
            table_factor,
            TableFactor::Derived { lateral: true, .. }
                | TableFactor::Function { lateral: true, .. }
        ) {
            self.0.insert(SqlQueryComplexity::Lateral);
        }
        ControlFlow::Continue(())
    }
}

impl Complexity {
    fn set_expression(&mut self, expression: &SetExpr) {
        match expression {
            SetExpr::Select(select)
                if matches!(select.distinct, Some(Distinct::Distinct | Distinct::On(_))) =>
            {
                self.0.insert(SqlQueryComplexity::Distinct);
            }
            SetExpr::SetOperation {
                op, left, right, ..
            } => {
                if *op == SetOperator::Union {
                    self.0.insert(SqlQueryComplexity::Union);
                }
                self.set_expression(left);
                self.set_expression(right);
            }
            _ => {}
        }
    }
}

pub fn collect(
    statements: &[Statement],
    tokens: &[&[TokenWithSpan]],
    locations: Option<&[Location]>,
    file_tokens: &[TokenWithSpan],
) -> Vec<SqlComplexQuery> {
    statements
        .iter()
        .enumerate()
        .filter_map(|(index, statement)| {
            let tokens = tokens.get(index).copied().unwrap_or_default();
            let location = locations
                .and_then(|locations| locations.get(index))
                .copied();
            let line = match location {
                Some(start) if start.line > 0 => start.line as usize,
                _ => crate::migration::locating::Locations::new(tokens)
                    .statement_line(statement, None),
            };
            extract(line, statement, file_tokens)
        })
        .collect()
}

fn extract(
    line: usize,
    statement: &Statement,
    tokens: &[TokenWithSpan],
) -> Option<SqlComplexQuery> {
    let mut visitor = Complexity::default();
    let _ = statement.visit_erased(&mut visitor);
    (!visitor.0.is_empty()).then(|| SqlComplexQuery {
        line,
        kinds: visitor.0,
        plan_scenario: plan_scenario(line, tokens),
    })
}

fn plan_scenario(line: usize, tokens: &[TokenWithSpan]) -> Option<String> {
    let previous = line.checked_sub(1)? as u64;
    let start = tokens.partition_point(|token| token.span.start.line < previous);
    let end = tokens.partition_point(|token| token.span.start.line <= previous);
    let mut scenario = None;
    for token in &tokens[start..end] {
        match &token.token {
            Token::Whitespace(Whitespace::SingleLineComment { comment, prefix })
                if prefix == "--" =>
            {
                let id = comment.trim().strip_prefix("plan-scenario:")?.trim();
                if !id.is_empty()
                    && id
                        .bytes()
                        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
                {
                    scenario = Some(id.to_string());
                }
            }
            Token::Whitespace(_) => {}
            _ => return None,
        }
    }
    scenario
}

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