no-mistakes-postgres-sql 0.109.129

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use super::{ident_key, key::KeyProof, relation_part_key, Audit, Candidate};
use sqlparser::ast::{Query, SetExpr};

impl Audit {
    pub(super) fn collect_scalar_tables(&mut self, query: &Query) {
        let body = query.body.as_ref();
        if !self.queries.last().is_some_and(|frame| frame.scalar)
            || !matches!(body, SetExpr::Table(_) | SetExpr::SetOperation { .. })
        {
            return;
        }
        let mut pending = vec![body];
        while let Some(body) = pending.pop() {
            match body {
                SetExpr::SetOperation { left, right, .. } => {
                    pending.push(right);
                    pending.push(left);
                }
                SetExpr::Table(table) => {
                    let Some(name) = &table.table_name else {
                        continue;
                    };
                    let relation = ident_key(name);
                    let relation = if let Some(schema) = &table.schema_name {
                        format!(
                            "{}.{}",
                            relation_part_key(&ident_key(schema)),
                            relation_part_key(&relation)
                        )
                    } else {
                        if self
                            .queries
                            .iter()
                            .rev()
                            .any(|frame| frame.cte_names.contains(&relation))
                        {
                            continue;
                        }
                        relation_part_key(&relation)
                    };
                    let at = name.span.start;
                    self.candidates.push(Candidate::unembedded(relation, at));
                }
                _ => {}
            }
        }
    }
}

impl Candidate {
    pub(super) fn unembedded(relation: String, at: sqlparser::tokenizer::Location) -> Self {
        Self {
            relation,
            key_proof: KeyProof::None,
            correlated_bare_id: false,
            column_aliases: Vec::new(),
            embedded: false,
            other_use: false,
            unqualified_columns: Vec::new(),
            unresolved_column_ownership: false,
            row_arguments: Vec::new(),
            bare_row_reads: Vec::new(),
            correlated_columns: Vec::new(),
            natural_join_peers: Vec::new(),
            line: at.line.max(1) as usize,
            column: at.column.max(1) as usize,
        }
    }
}