no-mistakes-postgres-sql 0.109.130

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use super::{DynamicSql, Token, TokenWithSpan};
use std::collections::HashMap;

pub(super) type Variables = HashMap<String, Option<DynamicSql>>;

pub(super) fn variable_key(token: &TokenWithSpan) -> Option<String> {
    let Token::Word(word) = &token.token else {
        return None;
    };
    Some(if word.quote_style.is_some() {
        word.value.clone()
    } else {
        word.value.to_ascii_lowercase()
    })
}

/// PL/pgSQL block-local variable bindings: a nested `DECLARE` shadows an outer
/// name only until its block's `END`, then the outer binding is restored.
#[derive(Default)]
pub(super) struct Blocks {
    frames: Vec<Frame>,
    declaring: bool,
}

#[derive(Default)]
struct Frame {
    label: Option<String>,
    outer: HashMap<String, Option<Option<DynamicSql>>>,
}

impl Blocks {
    pub(super) fn enter(&mut self, code: &[&TokenWithSpan], variables: &mut Variables) {
        // A statement chunk starts with `;`-free keyword chains such as `BEGIN DECLARE x ...`.
        let mut at = 0;
        let mut label = None;
        while let Some(token) = code.get(at) {
            if matches!(token.token, super::Token::ShiftLeft) {
                let width = code[at..]
                    .iter()
                    .position(|token| matches!(token.token, super::Token::ShiftRight))
                    .map_or(1, |end| end + 1);
                if width == 3 {
                    label = variable_key(code[at + 1]);
                }
                at += width;
                continue;
            }
            if keyword(token, "DECLARE") {
                self.open(label.take());
                self.declaring = true;
            } else if keyword(token, "BEGIN") {
                if self.declaring {
                    self.declaring = false;
                } else {
                    self.open(label.take());
                }
            } else {
                break;
            }
            at += 1;
        }
        let rest = &code[at..];
        let Some(first) = rest.first() else { return };
        if self.declaring {
            self.declare(rest, variables);
        } else if keyword(first, "END")
            && !rest.get(1).is_some_and(|next| {
                ["IF", "LOOP", "CASE"]
                    .into_iter()
                    .any(|kind| keyword(next, kind))
            })
        {
            self.close(variables);
        }
    }

    pub(super) fn assign(
        &mut self,
        qualifier: Option<&str>,
        name: String,
        value: Option<DynamicSql>,
        variables: &mut Variables,
    ) {
        let Some(qualifier) = qualifier else {
            variables.insert(name, value);
            return;
        };
        let owner = self.frames.iter().rposition(|frame| {
            frame.label.as_deref() == Some(qualifier) && frame.outer.contains_key(&name)
        });
        if let Some(owner) = owner {
            if let Some(shadowed) = self.frames[owner + 1..]
                .iter_mut()
                .find_map(|frame| frame.outer.get_mut(&name))
            {
                *shadowed = Some(value);
            } else {
                variables.insert(name, value);
            }
        } else if variables.remove(qualifier).is_none() {
            variables.remove(&name);
            for frame in &mut self.frames {
                if let Some(Some(value)) = frame.outer.get_mut(&name) {
                    *value = None;
                }
            }
        }
    }

    fn open(&mut self, label: Option<String>) {
        self.frames.push(Frame {
            label,
            ..Frame::default()
        });
    }

    fn declare(&mut self, code: &[&TokenWithSpan], variables: &mut Variables) {
        let Some(name) = code.first().and_then(|token| variable_key(token)) else {
            return;
        };
        if let Some(frame) = self.frames.last_mut() {
            frame
                .outer
                .entry(name.clone())
                .or_insert_with(|| variables.get(&name).cloned());
        }
        // An uninitialized declaration is NULL until assigned; an initializer overwrites this.
        variables.insert(name, None);
    }

    fn close(&mut self, variables: &mut Variables) {
        for (name, outer) in self.frames.pop().unwrap_or_default().outer {
            match outer {
                Some(value) => variables.insert(name, value),
                None => variables.remove(&name),
            };
        }
    }
}

fn keyword(token: &TokenWithSpan, expected: &str) -> bool {
    matches!(&token.token, super::Token::Word(word) if word.quote_style.is_none() && word.value.eq_ignore_ascii_case(expected))
}