no-mistakes-postgres-engine 0.109.131

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use crate::embedded::helpers::sentinel;
use sqlparser::dialect::PostgreSqlDialect;
use sqlparser::tokenizer::{Token, Tokenizer};

pub(super) fn strip_relation_identifier(c: &mut String) {
    let start = if c.ends_with('"') {
        quoted_identifier_start(c)
    } else {
        let ident_len = c
            .bytes()
            .rev()
            .take_while(|b| b.is_ascii_alphanumeric() || *b == b'_')
            .count();
        (ident_len > 0).then(|| c.len() - ident_len)
    };
    if let Some(start) = start.filter(|&start| sentinel::in_relation_slot(c, start)) {
        c.truncate(start);
    }
}

fn quoted_identifier_start(sql: &str) -> Option<usize> {
    let tokens = Tokenizer::new(&PostgreSqlDialect {}, sql)
        .tokenize_with_location()
        .ok()?;
    let token = tokens.last()?;
    if !matches!(&token.token, Token::Word(word) if word.quote_style == Some('"')) {
        return None;
    }
    let start = token.span.start;
    let tail = sql.splitn(start.line as usize, '\n').last()?;
    let (column, _) = tail
        .char_indices()
        .nth(start.column.checked_sub(1)? as usize)?;
    Some(sql.len() - tail.len() + column)
}