no-mistakes-postgres-sql 0.109.131

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use crate::idents::ident_key;
use sqlparser::ast::{ObjectName, Query, Select, SetExpr};

mod bindings;
pub(super) use bindings::Bindings;

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(super) struct Scope {
    pub(super) bindings: Vec<Bindings>,
    queries: Vec<QueryFrame>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct QueryFrame {
    names: Vec<String>,
    nonrecursive_children: Vec<usize>,
    visible: usize,
    tail_select: Option<usize>,
}

fn tail_select(body: &SetExpr) -> Option<usize> {
    match body {
        SetExpr::Select(select) => Some(std::ptr::from_ref(select.as_ref()).addr()),
        SetExpr::Query(query) => tail_select(&query.body),
        _ => None,
    }
}

impl Scope {
    pub(super) fn enter_query(&mut self, query: &Query) {
        if let Some(parent) = self.queries.last_mut() {
            let address = std::ptr::from_ref(query).addr();
            parent.visible = parent
                .nonrecursive_children
                .iter()
                .position(|child| *child == address)
                .unwrap_or(parent.names.len());
        }
        let mut names = Vec::new();
        let mut nonrecursive_children = Vec::new();
        if let Some(with) = &query.with {
            for cte in &with.cte_tables {
                names.push(ident_key(&cte.alias.name));
                if !with.recursive {
                    nonrecursive_children.push(std::ptr::from_ref(cte.query.as_ref()).addr());
                }
            }
        }
        let tail_select = tail_select(&query.body);
        self.bindings.push(Bindings::default());
        self.queries.push(QueryFrame {
            visible: names.len(),
            names,
            nonrecursive_children,
            tail_select,
        });
    }

    pub(super) fn leave_query(&mut self) {
        let frame = self.queries.pop();
        let bindings = self.bindings.pop();
        if let Some(parent) = self.queries.last_mut() {
            parent.visible = parent.names.len();
            if let (Some(frame), Some(bindings), Some(slot)) =
                (frame, bindings, self.bindings.last_mut())
            {
                if frame.tail_select.is_some() && frame.tail_select == parent.tail_select {
                    *slot = bindings;
                }
            }
        }
    }

    pub(super) fn leave_select(&mut self, select: &Select) {
        let Some(bindings) = self.bindings.pop() else {
            return;
        };
        if let Some(parent) = self.bindings.last_mut().filter(|_| {
            self.queries.last().and_then(|query| query.tail_select)
                == Some(std::ptr::from_ref(select).addr())
        }) {
            *parent = bindings;
        }
    }

    pub(super) fn has_cte(&self, name: &str) -> bool {
        self.queries
            .iter()
            .rev()
            .any(|frame| frame.names[..frame.visible].iter().any(|cte| cte == name))
    }

    pub(super) fn is_cte(&self, name: &ObjectName) -> bool {
        matches!(name.0.as_slice(), [part] if part.as_ident().is_some_and(|name| self.has_cte(&ident_key(name))))
    }

    pub(super) fn lookup(&self, name: &str) -> impl Iterator<Item = &String> {
        self.bindings
            .iter()
            .rev()
            .find_map(|bindings| bindings.names.get(name))
            .into_iter()
            .flatten()
    }
}