no-mistakes-postgres-sql 0.109.129

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
//! Limit and key-walk facts for the bounded-iteration SQL shapes.
mod bind_identity;
mod conjuncts;
use crate::erased_visit::VisitErased;
use bind_identity::Int4Bindings;
mod page;
mod probes;
#[cfg(all(test, any(nm_shard_all, nm_shard_2)))]
mod tests;

use super::limit::{is_empty_page, limit_site_at, next_table_fetch, Tokens};
use super::{walk_executed, SqlLimitFact, SqlSweepFact};
use crate::idents::ident_key;
use sqlparser::ast::{Query, Statement, Visitor};
use std::collections::HashMap;
use std::ops::ControlFlow;

/// Every `LIMIT` / `FETCH FIRST` in the executed statements, and each limited single-table
/// query ordered by plain columns.
pub(super) fn collect(
    tokens: &Tokens<'_>,
    statements: &[Statement],
    recovered_placeholder_positions: &[(u32, u32)],
    embedded: bool,
    probes: Option<&mut std::collections::BTreeMap<(usize, usize), Vec<String>>>,
) -> (Vec<SqlLimitFact>, Vec<SqlSweepFact>) {
    let mut collector = Collector::new(tokens, recovered_placeholder_positions, embedded);
    collector.probes = probes;
    for statement in statements {
        let mut executed = Vec::new();
        walk_executed(statement, &mut executed);
        collector.int4_bindings = Int4Bindings::for_statement(statement);
        for statement in executed {
            let _ = statement.visit_erased(&mut collector);
        }
    }
    collector
        .limits
        .sort_by_key(|fact| (fact.line, fact.column));
    collector.sweeps.sort_by_key(|fact| fact.line);
    (collector.limits, collector.sweeps)
}

struct Collector<'a, 'sql> {
    probes: Option<&'a mut std::collections::BTreeMap<(usize, usize), Vec<String>>>,
    limits: Vec<SqlLimitFact>,
    sweeps: Vec<SqlSweepFact>,
    tokens: &'a Tokens<'sql>,
    /// The CTE names visible inside each open query: those of its enclosing queries, plus its own
    /// WITH clause for everything but the CTE bodies.
    scopes: Vec<Vec<String>>,
    /// The names a CTE body sees, set when its WITH clause is entered and keyed by the body.
    bodies: HashMap<*const Query, Vec<String>>,
    int4_bindings: Int4Bindings,
    recovered_placeholder_positions: &'a [(u32, u32)],
    embedded: bool,
    table_fetch_cursor: usize,
}

impl<'a, 'sql> Collector<'a, 'sql> {
    fn new(
        tokens: &'a Tokens<'sql>,
        recovered_placeholder_positions: &'a [(u32, u32)],
        embedded: bool,
    ) -> Self {
        Self {
            probes: None,
            limits: Vec::new(),
            sweeps: Vec::new(),
            tokens,
            scopes: Vec::new(),
            bodies: HashMap::new(),
            int4_bindings: Int4Bindings::default(),
            recovered_placeholder_positions,
            embedded,
            table_fetch_cursor: 0,
        }
    }

    /// Open `query`'s scope. A non-recursive CTE sees only the CTEs declared before it; a
    /// recursive WITH shows every sibling and the CTE itself.
    fn enter(&mut self, query: &Query) {
        let outer = self
            .bodies
            .remove(&(query as *const Query))
            .or_else(|| self.scopes.last().cloned())
            .unwrap_or_default();
        let mut visible = outer.clone();
        if let Some(with) = &query.with {
            let names: Vec<String> = with
                .cte_tables
                .iter()
                .map(|cte| ident_key(&cte.alias.name))
                .collect();
            for (index, cte) in with.cte_tables.iter().enumerate() {
                let earlier = if with.recursive {
                    &names[..]
                } else {
                    &names[..index]
                };
                let mut body = outer.clone();
                body.extend(earlier.iter().cloned());
                self.bodies.insert(&*cte.query as *const Query, body);
            }
            visible.extend(names);
        }
        self.scopes.push(visible);
    }
}

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

    fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<()> {
        self.enter(query);
        let table_fetch = next_table_fetch(query, self.tokens, &mut self.table_fetch_cursor);
        let site = limit_site_at(query, self.tokens, table_fetch);
        // Transparent casts/unary signs can preserve zero without being bare literals.
        let empty = is_empty_page(query);
        if let Some(site) = site {
            self.limits.push(SqlLimitFact {
                line: site.line,
                column: site.column,
                value: site.value,
            });
        }
        let positions = self
            .embedded
            .then_some(self.recovered_placeholder_positions);
        if let Some(probes) = &mut self.probes {
            probes::collect(
                query,
                self.scopes.last().map_or(&[][..], Vec::as_slice),
                positions,
                probes,
            );
        }
        if super::limit::is_limited_at(query, positions) && !empty {
            let visible = self.scopes.last().map_or(&[][..], Vec::as_slice);
            if let Some(sweep) = page::sweep(
                query,
                visible,
                &self.int4_bindings,
                self.recovered_placeholder_positions,
            ) {
                self.sweeps.push(sweep);
            }
        }
        ControlFlow::Continue(())
    }

    fn post_visit_query(&mut self, _: &Query) -> ControlFlow<()> {
        self.scopes.pop();
        ControlFlow::Continue(())
    }
}