no-mistakes-postgres-engine 0.109.131

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use super::{function_body::BodyForm, model::CatalogFunction};
use std::borrow::Cow;

impl CatalogFunction {
    pub fn body_as_statements(&self) -> Option<Cow<'_, str>> {
        let body = self.body.as_deref()?;
        Some(if self.body_is_expression {
            Cow::Owned(format!("SELECT {body}"))
        } else {
            Cow::Borrowed(body)
        })
    }
}

pub(super) fn function_from_definition(key: &str, definition: &str) -> CatalogFunction {
    let (name, signature) = split_key(key);
    let (header, body, body_span, form) = match super::function_body::split_body(definition) {
        Some(((header, body, span), form)) => (header, Some(body), Some(span), Some(form)),
        None => (definition.to_string(), None, None, None),
    };
    let plain = strip_quotes_and_comments(&header);
    let modes = super::function_clauses::header_modes(definition, body_span);
    let routine_language = if matches!(form, Some(BodyForm::Atomic | BodyForm::Return)) {
        inline_language(super::function_outputs::after_parameter_list(&header))
            .or_else(|| body_span.and_then(|(_, end)| inline_language(&definition[end..])))
            .or_else(|| Some("sql".to_string()))
    } else {
        language(definition, body_span)
    };
    CatalogFunction {
        key: key.to_string(),
        name,
        signature,
        language: routine_language,
        returns_set: None,
        returns_trigger: returns_clause(&plain, "trigger"),
        returns_event_trigger: returns_clause(&plain, "event_trigger"),
        definition: definition.to_string(),
        body,
        body_is_expression: matches!(form, Some(BodyForm::Return)),
        null_input: modes.null_input,
        security: modes.security,
        parallel: modes.parallel,
        leakproof: modes.leakproof,
        volatility: modes.volatility,
        return_contract: modes.return_contract,
        planner: modes.planner,
        body_span,
    }
}

fn split_key(key: &str) -> (String, Option<String>) {
    let mut quoted = false;
    let mut chars = key.char_indices().peekable();
    while let Some((index, character)) = chars.next() {
        if character == '"' {
            if quoted && chars.peek().is_some_and(|(_, next)| *next == '"') {
                chars.next();
                continue;
            }
            quoted = !quoted;
            continue;
        }
        if character == '(' && !quoted {
            let name = key[..index].trim().to_string();
            let rest = key[index + 1..].trim();
            let signature = rest.strip_suffix(')').unwrap_or(rest).trim();
            return (name, Some(signature.to_string()));
        }
    }
    (key.trim().to_string(), None)
}

fn language(definition: &str, span: Option<(usize, usize)>) -> Option<String> {
    let bytes = definition.as_bytes();
    let mut index = 0;
    let mut depth = 0i32;
    while index < definition.len() {
        if let Some((start, end)) = span {
            if index >= start && index < end {
                index = end;
                continue;
            }
        }
        if let Some(end) = super::function_body::skip_noise(definition, index) {
            index = end;
            continue;
        }
        match bytes[index] {
            b'(' => depth += 1,
            b')' => depth -= 1,
            _ => {}
        }
        if depth == 0 && is_word_at(definition, index, "language") {
            let cursor = super::function_body::skip_as_gap(definition, index + "language".len());
            if let Some(name) = language_name(definition, cursor) {
                return Some(name);
            }
        }
        index += definition[index..].chars().next()?.len_utf8();
    }
    None
}

fn language_name(definition: &str, mut cursor: usize) -> Option<String> {
    let rest = definition.get(cursor..)?;
    if rest.starts_with('\'') || rest.starts_with('"') {
        let quote = rest.chars().next()?;
        let end = super::function_comment::quoted_end(definition, cursor, quote)?;
        let inner = &definition[cursor + quote.len_utf8()..end - quote.len_utf8()];
        return (!inner.is_empty()).then(|| {
            if quote == '"' {
                inner.to_string()
            } else {
                inner.to_ascii_lowercase()
            }
        });
    }
    let start = cursor;
    while definition.as_bytes().get(cursor).is_some_and(is_ident_byte) {
        cursor += 1;
    }
    (cursor > start).then(|| definition[start..cursor].to_ascii_lowercase())
}

fn inline_language(tail: &str) -> Option<String> {
    let after_keyword = no_mistakes_postgres_sql::source::inline_language_keyword(tail)?;
    language_name(tail, super::function_body::skip_as_gap(tail, after_keyword))
}

fn strip_quotes_and_comments(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut index = 0;
    while index < text.len() {
        if let Some(end) = super::function_body::skip_noise(text, index) {
            out.push(' ');
            index = end;
            continue;
        }
        let Some(character) = text[index..].chars().next() else {
            break;
        };
        out.push(character);
        index += character.len_utf8();
    }
    out
}

fn returns_clause(header: &str, word: &str) -> bool {
    let lower = header.to_ascii_lowercase();
    let mut rest = lower.as_str();
    while let Some(index) = rest.find("returns") {
        let before = index == 0 || !is_ident_byte(&rest.as_bytes()[index - 1]);
        let after = rest[index + "returns".len()..].trim_start();
        if before && word_starts(after, word) {
            return true;
        }
        rest = &rest[index + "returns".len()..];
    }
    false
}

fn word_starts(text: &str, word: &str) -> bool {
    let Some(rest) = text.get(..word.len()) else {
        return false;
    };
    if !rest.eq_ignore_ascii_case(word) {
        return false;
    }
    text.as_bytes()
        .get(word.len())
        .is_none_or(|byte| !is_ident_byte(byte))
}

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 = index == 0 || !is_ident_byte(&text.as_bytes()[index - 1]);
    let after = text.as_bytes().get(index + word.len());
    before_ok && after.is_none_or(|byte| !is_ident_byte(byte))
}

fn is_ident_byte(byte: &u8) -> bool {
    byte.is_ascii_alphanumeric() || *byte == b'_'
}