no-mistakes-postgres-sql 0.109.130

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use super::{assignment, boundary, declaration, labels::unlabeled, word, BodyState};
use sqlparser::ast::Expr;
use sqlparser::tokenizer::{Token, TokenWithSpan};
use std::ops::Range;

mod commands;
use commands::{
    append_parts, cursor_arguments, execute_start, execute_values, open_values, raise_values,
    RangeList,
};

pub(super) fn lock_values(tokens: &[TokenWithSpan], state: &mut BodyState) -> Vec<Expr> {
    let normalized = super::ranges::normalize(tokens);
    let located: Vec<_> = normalized
        .iter()
        .filter(|token| !matches!(token.token, Token::Whitespace(_)))
        .collect();
    let bare: Vec<_> = located.iter().map(|token| &token.token).collect();
    let mut ranges = Vec::new();
    value_ranges(&bare, 0, &mut ranges, state);
    ranges
        .into_iter()
        .filter_map(|range| parse_value(&located[range]))
        .collect()
}

fn parse_value(located: &[&TokenWithSpan]) -> Option<Expr> {
    assignment::parse_value(located.iter().map(|token| (*token).clone()).collect())
}

fn value_ranges(code: &[&Token], origin: usize, ranges: &mut RangeList, state: &mut BodyState) {
    let body = unlabeled(code);
    let offset = origin + code.len() - body.len();
    let Some((first, tail)) = body.split_first() else {
        return;
    };
    let value = if word(first, "DECLARE") && tail.first().is_some_and(|token| word(token, "BEGIN"))
    {
        value_ranges(tail, offset + 1, ranges, state);
        None
    } else if word(first, "DECLARE") {
        state.declarations = true;
        declaration_value(tail).map(|at| at + 1)
    } else if word(first, "BEGIN") {
        state.declarations = false;
        value_ranges(tail, offset + 1, ranges, state);
        None
    } else if word(first, "END") {
        state.declarations = false;
        None
    } else if state.declarations {
        declaration_value(body)
    } else if let Some(at) = assignment::target_end(body) {
        if body[..at]
            .iter()
            .any(|token| matches!(token, Token::LBracket))
        {
            ranges.push(offset..offset + at);
        }
        Some(at + 1)
    } else if ["ELSE", "LOOP", "EXCEPTION"]
        .iter()
        .any(|name| word(first, name))
    {
        value_ranges(tail, offset + 1, ranges, state);
        None
    } else if word(first, "CASE") {
        if let Some(at) = boundary(body, "WHEN") {
            if at > 1 {
                ranges.push(offset + 1..offset + at);
            }
            value_ranges(&body[at..], offset + at, ranges, state);
        }
        None
    } else if ["IF", "ELSIF", "ELSEIF", "WHEN"]
        .iter()
        .any(|name| word(first, name))
    {
        control_ranges(body, offset, "THEN", ranges, state);
        None
    } else if ["FOR", "WHILE", "FOREACH"]
        .iter()
        .any(|name| word(first, name))
    {
        control_ranges(body, offset, "LOOP", ranges, state);
        None
    } else if word(first, "EXIT") || word(first, "CONTINUE") {
        boundary(body, "WHEN").map(|at| at + 1)
    } else if word(first, "RAISE") {
        raise_values(body, offset, ranges);
        None
    } else if word(first, "ASSERT") {
        append_parts(tail, offset + 1, ranges, Some);
        None
    } else if word(first, "OPEN") {
        open_values(body, offset, ranges);
        None
    } else if let Some(start) = execute_start(body) {
        execute_values(&body[start..], offset + start, ranges);
        None
    } else if word(first, "FETCH") || word(first, "MOVE") {
        let multiple = word(first, "MOVE");
        let source = if multiple {
            Some(tail)
        } else {
            super::commands::fetch_into(tail).map(|into| &tail[..into])
        };
        if let Some((start, count)) =
            source.and_then(|source| super::commands::cursor_count(source, multiple))
        {
            let start = offset + 1 + start;
            ranges.push(start..start + count.len());
        }
        None
    } else {
        None
    };
    if let Some(at) = value {
        ranges.push(offset + at..offset + body.len());
    }
}

fn control_ranges(
    body: &[&Token],
    offset: usize,
    boundary_word: &str,
    ranges: &mut RangeList,
    state: &mut BodyState,
) {
    if let Some(at) = boundary(body, boundary_word) {
        if word(body[0], "WHEN") {
            append_parts(&body[1..at], offset + 1, ranges, Some);
        } else if ["WHILE", "IF", "ELSIF", "ELSEIF"]
            .iter()
            .any(|name| word(body[0], name))
        {
            ranges.push(offset + 1..offset + at);
        } else if word(body[0], "FOR") {
            ranges.extend(integer_bounds(&body[..at], offset));
            if let Some(start) = boundary(&body[..at], "IN").map(|at| at + 1) {
                let source = &body[start..at];
                if source.first().is_some_and(|token| word(token, "EXECUTE")) {
                    execute_values(source, offset + start, ranges);
                } else if matches!(source, [Token::LParen, .., Token::RParen]) {
                    ranges.push(offset + start..offset + at);
                } else {
                    cursor_arguments(source, offset + start, ranges);
                }
            }
        } else if word(body[0], "FOREACH") {
            if let Some(start) = super::commands::foreach_array_start(&body[..at]) {
                ranges.push(offset + start..offset + at);
            }
        }
        value_ranges(&body[at + 1..], offset + at + 1, ranges, state);
    }
}

fn integer_bounds(header: &[&Token], offset: usize) -> Vec<Range<usize>> {
    let Some(mut start) = boundary(header, "IN").map(|at| at + 1) else {
        return Vec::new();
    };
    if header
        .get(start)
        .is_some_and(|token| word(token, "REVERSE"))
    {
        start += 1;
    }
    let Some(range) = header[start..]
        .iter()
        .position(|token| super::ranges::marker(token))
    else {
        return Vec::new();
    };
    let lower_end = start + range;
    let upper_start = lower_end + 1;
    let step = boundary(header, "BY");
    let upper_end = step.unwrap_or(header.len());
    if upper_start >= upper_end {
        return Vec::new();
    }
    let mut ranges = vec![
        offset + start..offset + lower_end,
        offset + upper_start..offset + upper_end,
    ];
    if let Some(step) = step {
        ranges.push(offset + step + 1..offset + header.len());
    }
    ranges
}

fn declaration_value(body: &[&Token]) -> Option<usize> {
    declaration::matches(body).then_some(())?;
    Some(declaration::initializer(body.get(1..)?)? + 2)
}