no-mistakes-postgres-engine 0.109.131

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
#[derive(Clone, Copy)]
pub(super) enum BodyForm {
    Quoted,
    Atomic,
    Return,
}

type BodyParts = (String, String, (usize, usize));

pub(super) fn split_body(definition: &str) -> Option<(BodyParts, BodyForm)> {
    [
        (dollar_body(definition), BodyForm::Quoted),
        (atomic_body(definition), BodyForm::Atomic),
    ]
    .into_iter()
    .filter_map(|(parts, form)| parts.map(|parts| (parts, form)))
    .min_by_key(|((_, _, span), _)| span.0)
    .or_else(|| {
        super::function_quote::return_expression(definition).map(|parts| (parts, BodyForm::Return))
    })
}

pub(super) fn skip_dollar_body(definition: &str, index: usize) -> Option<usize> {
    let (tag, open_end) = super::function_quote::opening_dollar(definition, index)?;
    let close = format!("${tag}$");
    let relative = definition[open_end..].find(&close)?;
    Some(open_end + relative + close.len())
}

fn dollar_body(definition: &str) -> Option<(String, String, (usize, usize))> {
    let mut index = 0;
    while index < definition.len() {
        if let Some(next) = skip_noise(definition, index) {
            index = next;
            continue;
        }
        if is_word_at(definition, index, "as") {
            let cursor = skip_as_gap(definition, index + 2);
            if let Some((body, start, end)) =
                super::function_quote::body_after_as(definition, cursor)
            {
                return Some((definition[..index].to_string(), body, (start, end)));
            }
        }
        index += definition[index..].chars().next()?.len_utf8();
    }
    None
}

fn atomic_body(definition: &str) -> Option<(String, String, (usize, usize))> {
    let mut index = 0;
    while index < definition.len() {
        if let Some(next) = skip_noise(definition, index) {
            index = next;
            continue;
        }
        if is_word_at(definition, index, "begin") {
            let cursor = skip_as_gap(definition, index + "begin".len());
            if is_word_at(definition, cursor, "atomic") {
                let body_start = cursor + "atomic".len();
                let end = index
                    + no_mistakes_postgres_sql::source::catalog_atomic_close(&definition[index..])?;
                return Some((
                    definition[..index].to_string(),
                    definition[body_start..end].to_string(),
                    (body_start, end),
                ));
            }
        }
        index += definition[index..].chars().next()?.len_utf8();
    }
    None
}

pub(super) fn skip_as_gap(definition: &str, mut cursor: usize) -> usize {
    loop {
        while definition
            .as_bytes()
            .get(cursor)
            .is_some_and(u8::is_ascii_whitespace)
        {
            cursor += 1;
        }
        let Some(rest) = definition.get(cursor..) else {
            return cursor;
        };
        if rest.starts_with("--") {
            cursor += rest.find('\n').unwrap_or(rest.len());
            continue;
        }
        if rest.starts_with("/*") {
            cursor = super::function_comment::skip_block_comment(definition, cursor);
            continue;
        }
        return cursor;
    }
}

pub(super) fn skip_noise(definition: &str, index: usize) -> Option<usize> {
    let rest = &definition[index..];
    if rest.starts_with("--") {
        return Some(index + rest.find('\n').unwrap_or(rest.len()));
    }
    if rest.starts_with("/*") {
        return Some(super::function_comment::skip_block_comment(
            definition, index,
        ));
    }
    let quote = rest.chars().next()?;
    if quote == '\'' {
        if let Some(end) = super::function_comment::skip_escape_string(definition, index) {
            return Some(end);
        }
        return Some(super::function_comment::skip_quoted(
            definition, index, quote,
        ));
    }
    if quote == '"' {
        return Some(super::function_comment::skip_quoted(
            definition, index, quote,
        ));
    }
    if quote == '$' {
        return skip_dollar_body(definition, index);
    }
    None
}

pub(super) fn is_word_at(text: &str, index: usize, word: &str) -> bool {
    let Some(slice) = text.get(index..index + word.len()) else {
        return false;
    };
    if !slice.eq_ignore_ascii_case(word) {
        return false;
    }
    let before_ok = text[..index]
        .chars()
        .next_back()
        .is_none_or(|character| !is_ident_char(character));
    let after_ok = text[index + word.len()..]
        .chars()
        .next()
        .is_none_or(|character| !is_ident_char(character));
    before_ok && after_ok
}

fn is_ident_char(character: char) -> bool {
    character.is_alphanumeric() || character == '_'
}