no-mistakes-postgres-sql 0.109.131

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
mod bindings;
mod embedding;
mod facts;
pub(crate) use facts::collect;
mod join_scopes;
mod key;
pub(crate) use key::using_columns;
mod mutation;
mod query_frame;
mod refs;
mod scalar_table;
mod unmatched;

use crate::fx::FxHashSet;
use crate::idents::{ident_key, relation_part_key};
use crate::statement_facts::{
    SqlBareViewRowRead, SqlNaturalJoinPeers, SqlQualifiedViewKey, SqlSchemaQualifiedViewRead,
    SqlUsingViewRowRead, SqlViewValuesSortRead, SqlViewValuesWidth,
};
use bindings::{collect_bindings, Scope};
use sqlparser::ast::{Expr, Query, Select, Statement, TableFactor, Visitor};
use std::ops::ControlFlow;

impl super::query::cte_scope::CteResolver for Vec<QueryFrame> {
    fn resolve(&self, name: &str) -> Option<&super::query::cte_scope::CteEntry> {
        self.iter().rev().find_map(|frame| frame.ctes.entry(name))
    }
}

#[derive(Default)]
struct Audit {
    candidates: Vec<Candidate>,
    queries: Vec<QueryFrame>,
    selects: Vec<Scope>,
    active_predicates: Vec<join_scopes::ActivePredicate>,
    active_joins: Vec<join_scopes::ActiveJoin>,
    hidden_derived_inputs: Vec<join_scopes::HiddenDerivedInputs>,
    scalar_queries: FxHashSet<*const Query>,
    id_refs: FxHashSet<*const Expr>,
    projection_calls: FxHashSet<*const Expr>,
    row_refs: FxHashSet<*const Expr>,
    statement_scopes: Vec<bool>,
    unmatched: unmatched::Unmatched,
}

struct QueryFrame {
    ctes: super::query::cte_scope::CteScope,
    sort_names: FxHashSet<*const Expr>,
    set_output_only: bool,
    values_width: Option<std::sync::Arc<SqlViewValuesWidth>>,
    direct_select: Option<*const Select>,
    wrapped_body: Option<*const Query>,
    scalar: bool,
    scope_depth: usize,
    retained_scope: bool,
}

struct Candidate {
    relation: String,
    database_qualified_relation: Option<String>,
    key_proof: key::KeyProof,
    correlated_bare_id: bool,
    column_keys: Vec<SqlBareViewRowRead>,
    qualified_peer_keys: Vec<SqlQualifiedViewKey>,
    unaliased: Option<String>,
    column_aliases: Vec<String>,
    embedded: bool,
    other_use: bool,
    unqualified_columns: Vec<String>,
    unresolved_column_ownership: bool,
    schema_qualified_reads: Vec<SqlSchemaQualifiedViewRead>,
    schema_qualified_embeddings: Vec<SqlSchemaQualifiedViewRead>,
    row_arguments: Vec<SqlBareViewRowRead>,
    bare_row_reads: Vec<SqlBareViewRowRead>,
    using_row_reads: Vec<SqlUsingViewRowRead>,
    correlated_columns: Vec<SqlBareViewRowRead>,
    values_sort_reads: Vec<SqlViewValuesSortRead>,
    natural_join_peers: Vec<SqlNaturalJoinPeers>,
    line: usize,
    column: usize,
}

impl Visitor for Audit {
    type Break = ();

    fn pre_visit_statement(&mut self, statement: &Statement) -> ControlFlow<()> {
        self.enter_statement(statement);
        ControlFlow::Continue(())
    }

    fn post_visit_statement(&mut self, _: &Statement) -> ControlFlow<()> {
        self.leave_statement();
        ControlFlow::Continue(())
    }

    fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
        let scalar = self.scalar_queries.remove(&std::ptr::from_ref(query));
        if scalar {
            query_frame::mark_scalar_body(&query.body, &mut self.scalar_queries);
        }
        let outer = |name: &str| {
            self.queries
                .iter()
                .rev()
                .find_map(|frame| frame.ctes.entry(name))
                .and_then(|entry| entry.single_output.clone())
        };
        let frame = QueryFrame::new(query, scalar, &self.selects, Some(&outer));
        self.queries.push(frame);
        embedding::named_order_functions(query, &mut self.projection_calls);
        ControlFlow::Continue(())
    }

    fn post_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
        self.collect_scalar_tables(query);
        let query = std::ptr::from_ref(query);
        if self.queries.pop().is_some_and(|frame| frame.retained_scope) {
            if let Some(parent) = self
                .queries
                .last_mut()
                .filter(|parent| parent.wrapped_body == Some(query))
            {
                parent.retained_scope = true;
            } else {
                self.finish_select();
            }
        }
        if let Some(parent) = self.queries.last_mut() {
            parent.ctes.finish_child(query);
        }
        ControlFlow::Continue(())
    }

    fn pre_visit_select(&mut self, select: &Select) -> ControlFlow<()> {
        let scalar = self.queries.last().is_some_and(|query| query.scalar);
        let scope = collect_bindings(
            select,
            scalar,
            &self.queries,
            &self.selects,
            &mut self.candidates,
            &mut self.id_refs,
        );
        if self.selects.iter().rev().any(|scope| scope.inputs > 0) {
            for &index in &scope.candidates {
                let candidate = &mut self.candidates[index];
                candidate.correlated_bare_id = candidate.key_proof == key::KeyProof::Bare;
            }
        }
        for item in &select.projection {
            self.inspect_projection(item, &scope);
        }
        embedding::named_projection_functions(select, &mut self.projection_calls);
        self.selects.push(scope);
        ControlFlow::Continue(())
    }

    fn post_visit_select(&mut self, select: &Select) -> ControlFlow<()> {
        if let Some(query) = self.queries.last_mut().filter(|query| {
            query.direct_select == Some(std::ptr::from_ref(select))
                && query.scope_depth + 1 == self.selects.len()
        }) {
            query.retained_scope = true;
        } else {
            self.finish_select();
        }
        ControlFlow::Continue(())
    }

    fn pre_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<()> {
        self.enter_join(factor);
        self.row_refs.extend(
            crate::idents::table_factor_named_argument_labels(factor).map(std::ptr::from_ref),
        );
        ControlFlow::Continue(())
    }

    fn post_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<()> {
        self.leave_join(factor);
        ControlFlow::Continue(())
    }

    fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
        self.unmatched.enter(expr);
        self.enter_predicate(expr);
        self.inspect_expr(expr);
        ControlFlow::Continue(())
    }

    fn post_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
        self.leave_predicate(expr);
        self.unmatched.leave(expr);
        ControlFlow::Continue(())
    }
}