no-mistakes-postgres-sql 0.109.129

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use super::super::labels::identifier;
use super::{assignment, query, word, Token};

pub(super) fn cursor_reference_len<'a>(
    mut tokens: impl Iterator<Item = &'a Token>,
) -> Option<usize> {
    if !tokens.next().is_some_and(identifier) {
        return None;
    }
    let mut len = 1;
    while matches!(tokens.next(), Some(Token::Period)) {
        if !tokens.next().is_some_and(identifier) {
            return None;
        }
        len += 2;
    }
    Some(len)
}

pub(super) fn open(code: &[&Token]) -> bool {
    let Some(len) = cursor_reference_len(code.iter().copied()) else {
        return false;
    };
    let mut tail = &code[len..];
    if tail.is_empty() {
        return true;
    }
    if bound_cursor_args(code).is_some() {
        return true;
    }
    if tail.first().is_some_and(|token| word(token, "NO")) {
        if !tail.get(1).is_some_and(|token| word(token, "SCROLL")) {
            return false;
        }
        tail = &tail[1..];
    }
    if tail.first().is_some_and(|token| word(token, "SCROLL")) {
        tail = &tail[1..];
    }
    if tail.first().is_some_and(|token| word(token, "FOR")) {
        return query(&tail[1..]) || static_execute(&tail[1..]);
    }
    false
}

pub(in super::super) fn bound_cursor_args<'a>(
    code: &'a [&'a Token],
) -> Option<(usize, &'a [&'a Token])> {
    let len = cursor_reference_len(code.iter().copied())?;
    let [Token::LParen, args @ .., Token::RParen] = &code[len..] else {
        return None;
    };
    assignment::comma_parts(args)?
        .into_iter()
        .all(|arg| assignment::expression(cursor_arg_value(arg)))
        .then_some((len + 1, args))
}

pub(in super::super) fn cursor_arg_value<'a>(arg: &'a [&'a Token]) -> &'a [&'a Token] {
    match arg {
        [name, Token::Assignment | Token::RArrow, value @ ..] if identifier(name) => value,
        _ => arg,
    }
}

pub(super) fn static_execute(code: &[&Token]) -> bool {
    if !code.first().is_some_and(|token| word(token, "EXECUTE"))
        || !matches!(
            code.get(1),
            Some(
                Token::SingleQuotedString(_)
                    | Token::DollarQuotedString(_)
                    | Token::EscapedStringLiteral(_)
                    | Token::UnicodeStringLiteral(_)
            )
        )
    {
        return false;
    }
    code.len() == 2
        || code.get(2).is_some_and(|token| word(token, "USING"))
            && assignment::comma_parts(&code[3..])
                .is_some_and(|parts| parts.into_iter().all(assignment::expression))
}

pub(super) fn fetch(code: &[&Token]) -> bool {
    fetch_into(code).is_some()
}

pub(in super::super) fn fetch_into(code: &[&Token]) -> Option<usize> {
    code.iter().enumerate().rev().find_map(|(at, token)| {
        (word(token, "INTO")
            && cursor_source(&code[..at], false)
            && assignment::comma_parts(&code[at + 1..])
                .is_some_and(|parts| parts.into_iter().all(assignment::target)))
        .then_some(at)
    })
}

pub(super) fn cursor_move(code: &[&Token]) -> bool {
    cursor_source(code, true)
}

fn cursor_source(code: &[&Token], allow_multiple_rows: bool) -> bool {
    let Some((direction, separator)) = cursor_direction(code) else {
        return false;
    };
    (allow_multiple_rows || single_row_direction(direction))
        && (direction.is_empty()
            || separator
                && (fixed_direction(direction)
                    || count_expression(direction)
                        .is_some_and(|(_, count)| assignment::expression(count))))
}

fn single_row_direction(direction: &[&Token]) -> bool {
    match direction {
        [] => true,
        [first] => fixed_direction(direction) && !word(first, "ALL"),
        [first, ..] => word(first, "ABSOLUTE") || word(first, "RELATIVE"),
    }
}

fn fixed_direction(direction: &[&Token]) -> bool {
    match direction {
        [first] => [
            "NEXT", "PRIOR", "FIRST", "LAST", "ALL", "FORWARD", "BACKWARD",
        ]
        .iter()
        .any(|name| word(first, name)),
        [first, all] => (word(first, "FORWARD") || word(first, "BACKWARD")) && word(all, "ALL"),
        _ => false,
    }
}

fn cursor_direction<'a>(code: &'a [&'a Token]) -> Option<(&'a [&'a Token], bool)> {
    let len = cursor_reference_len(code.iter().rev().copied())?;
    let direction = &code[..code.len() - len];
    if direction
        .last()
        .is_some_and(|token| word(token, "FROM") || word(token, "IN"))
    {
        return Some((&direction[..direction.len() - 1], true));
    }
    if code.len() == 1
        && (fixed_direction(&code[..1]) || word(code[0], "ABSOLUTE") || word(code[0], "RELATIVE"))
    {
        return None;
    }
    Some((direction, false))
}

pub(in super::super) fn cursor_count<'a>(
    code: &'a [&'a Token],
    allow_multiple_rows: bool,
) -> Option<(usize, &'a [&'a Token])> {
    let (direction, separator) = cursor_direction(code)?;
    (separator
        && !fixed_direction(direction)
        && (allow_multiple_rows || single_row_direction(direction)))
    .then_some(())?;
    count_expression(direction)
}

fn count_expression<'a>(direction: &'a [&'a Token]) -> Option<(usize, &'a [&'a Token])> {
    let [first, count @ ..] = direction else {
        return None;
    };
    if ["ABSOLUTE", "RELATIVE", "FORWARD", "BACKWARD"]
        .iter()
        .any(|name| word(first, name))
    {
        return (!count.is_empty()).then_some((1, count));
    }
    (!["NEXT", "PRIOR", "FIRST", "LAST", "ALL", "TO"]
        .iter()
        .any(|name| word(first, name)))
    .then_some((0, direction))
}