no-mistakes-postgres-sql 0.109.129

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
//! Preserve E-mode quote continuations through the one source tokenizer pass.
use sqlparser::tokenizer::{Location, Token, TokenWithSpan};
use std::collections::HashMap;

mod cursor;
use cursor::Cursor;

pub(super) struct Prepared {
    pub sql: String,
    raw_literals: HashMap<Location, Token>,
}

impl Prepared {
    pub fn restore(self, tokens: &mut [TokenWithSpan]) {
        for token in tokens {
            if let Some(raw) = self.raw_literals.get(&token.span.start) {
                token.token = raw.clone();
            }
        }
    }
}

pub(super) fn prepare(sql: &str, raw_initial_escape: bool) -> Prepared {
    let mut cursor = Cursor {
        sql,
        at: 0,
        location: Location { line: 1, column: 1 },
    };
    let mut output = sql.as_bytes().to_vec();
    let mut raw_literals = HashMap::new();
    while let Some(character) = cursor.peek() {
        if cursor.starts("--") {
            cursor.line_comment();
        } else if cursor.starts("/*") {
            cursor.block_comment();
        } else if character == '$' && !cursor.identifier_before() && cursor.dollar_body() {
            // Dollar bodies are decoded and prepared only by their own boundary.
        } else if character == '"' || character == '\'' {
            cursor.quoted(character, false, false, &mut output);
        } else if matches!(character, 'e' | 'E')
            && cursor.sql.as_bytes().get(cursor.at + 1) == Some(&b'\'')
            && !cursor.identifier_before()
        {
            let location = cursor.location;
            cursor.next();
            let start = cursor.at + 1;
            let Some(end) = cursor.quoted('\'', true, raw_initial_escape, &mut output) else {
                continue;
            };
            if raw_initial_escape {
                raw_literals.insert(
                    location,
                    Token::EscapedStringLiteral(plain_value(&sql[start..end])),
                );
            }
            loop {
                let mut newline = false;
                while cursor
                    .peek()
                    .is_some_and(|character| character.is_ascii_whitespace())
                    || cursor.starts("--")
                {
                    if cursor.starts("--") {
                        newline |= cursor.line_comment();
                    } else {
                        newline |= cursor.next() == Some('\n');
                    }
                }
                if !newline || cursor.peek() != Some('\'') {
                    break;
                }
                let location = cursor.location;
                let start = cursor.at + 1;
                let Some(end) = cursor.quoted('\'', true, true, &mut output) else {
                    break;
                };
                raw_literals.insert(
                    location,
                    Token::SingleQuotedString(plain_value(&sql[start..end])),
                );
            }
        } else {
            cursor.next();
        }
    }
    Prepared {
        // Only ASCII escape bytes are replaced, so UTF-8 and all locations survive.
        sql: String::from_utf8(output).unwrap(),
        raw_literals,
    }
}

/// Collapse doubled quotes while retaining escapes for the existing E decoder.
fn plain_value(value: &str) -> String {
    let mut output = String::new();
    let mut characters = value.chars().peekable();
    while let Some(character) = characters.next() {
        output.push(character);
        if character == '\\' {
            // Closed E-mode strings cannot end in an incomplete escape.
            output.push(characters.next().unwrap());
        } else if character == '\'' && characters.peek() == Some(&'\'') {
            characters.next();
        }
    }
    output
}