no-mistakes-postgres-engine 0.109.131

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use no_mistakes_postgres_sql::parse::operator_boundary::tokenize;
use sqlparser::dialect::{Dialect, PostgreSqlDialect};
use sqlparser::tokenizer::{Token, Whitespace};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallSqlPrefixEnd {
    TokenBoundary,
    IdentifierEnd,
    LineComment,
    Unclosed,
}

impl CallSqlPrefixEnd {
    pub fn from_sql(sql: &str) -> Self {
        let dialect = PostgreSqlDialect {};
        match tokenize(&dialect, sql) {
            Ok(tokens) => match tokens.last() {
                Some(Token::Whitespace(Whitespace::SingleLineComment { .. }))
                    if !sql.ends_with(['\r', '\n']) =>
                {
                    Self::LineComment
                }
                _ if sql.ends_with(|character| dialect.is_identifier_part(character)) => {
                    Self::IdentifierEnd
                }
                _ => Self::TokenBoundary,
            },
            Err(_) => Self::Unclosed,
        }
    }

    pub(crate) fn without_boundary(self) -> Self {
        match self {
            Self::TokenBoundary => Self::IdentifierEnd,
            _ => self,
        }
    }

    pub(crate) fn merge(self, other: Self) -> Self {
        match (self, other) {
            (left, right) if left == right => left,
            (Self::TokenBoundary, Self::IdentifierEnd)
            | (Self::IdentifierEnd, Self::TokenBoundary) => Self::IdentifierEnd,
            _ => Self::Unclosed,
        }
    }

    pub fn active_sql_start(self, sql: &str) -> Option<usize> {
        match self {
            Self::TokenBoundary => Some(0),
            Self::IdentifierEnd => (!sql
                .starts_with(|character| PostgreSqlDialect {}.is_identifier_part(character)))
            .then_some(0),
            Self::LineComment => sql.find(['\r', '\n']),
            Self::Unclosed => None,
        }
    }
}