|
| 1 | +//! The canonical token stream of SQL under SQLQuack's tokenizers. |
| 2 | +
|
| 3 | +use sqlclean::sql_tokens::main::is_unquoted_word::is_unquoted_word; |
| 4 | +use sqlclean::sql_tokens::main::name_positions::name_positions; |
| 5 | +use sqlquack_syntax::lossless::models::TokenKind; |
| 6 | +use sqlquack_syntax_postgres::scan::main::scan::scan; |
| 7 | +use sqlquack_syntax_postgres::scan::models::TokenKind as PostgresTokenKind; |
| 8 | + |
| 9 | +use crate::sql_tokens::_helpers::reserved_keywords::is_reserved_keyword; |
| 10 | +use crate::sql_tokens::constants::{ |
| 11 | + CALL_CLOSER, CALL_OPENER, COLUMN_LIST_RELATION_KEYWORDS, CTE_BODY_OPENERS, CTE_BODY_PREFIX, |
| 12 | + PLACEHOLDER_PREFIX, |
| 13 | +}; |
| 14 | +use crate::sql_tokens::models::{FingerprintTokenizer, SqlquackFingerprintDialect}; |
| 15 | + |
| 16 | +/// Significant token texts with reserved keywords and called names, except `__` placeholders, upper-cased. |
| 17 | +pub(crate) fn canonical_tokens( |
| 18 | + sql: &str, |
| 19 | + dialect: SqlquackFingerprintDialect, |
| 20 | +) -> Result<Vec<String>, String> { |
| 21 | + let raws: Vec<&str> = significant_texts(sql, dialect.tokenizer)?; |
| 22 | + let uppers: Vec<String> = raws.iter().map(|raw| raw.to_ascii_uppercase()).collect(); |
| 23 | + let names: Vec<bool> = name_positions(&uppers); |
| 24 | + let closers: Vec<Option<usize>> = matching_closers(&uppers); |
| 25 | + let mut texts: Vec<String> = Vec::with_capacity(raws.len()); |
| 26 | + for (index, raw) in raws.iter().enumerate() { |
| 27 | + let folds = !names[index] |
| 28 | + && is_unquoted_word(raw) |
| 29 | + && (is_reserved_keyword(dialect.keywords, &uppers[index]) |
| 30 | + || calls(raw, &uppers, &closers, index)); |
| 31 | + texts.push(if folds { |
| 32 | + uppers[index].clone() |
| 33 | + } else { |
| 34 | + (*raw).to_owned() |
| 35 | + }); |
| 36 | + } |
| 37 | + Ok(texts) |
| 38 | +} |
| 39 | + |
| 40 | +/// The text of each significant token of `sql`, in order. |
| 41 | +fn significant_texts(sql: &str, tokenizer: FingerprintTokenizer) -> Result<Vec<&str>, String> { |
| 42 | + match tokenizer { |
| 43 | + FingerprintTokenizer::Lossless(dialect) => Ok(sqlquack_syntax::tokenize(sql, dialect) |
| 44 | + .map_err(|error| format!("SQL tokenization failed: {error}"))? |
| 45 | + .iter() |
| 46 | + .filter(|token| matches!(token.kind, TokenKind::Significant(_))) |
| 47 | + .map(|token| token.text(sql)) |
| 48 | + .collect()), |
| 49 | + FingerprintTokenizer::PostgresScanner => scan(sql) |
| 50 | + .into_iter() |
| 51 | + .map(|token| match token.kind { |
| 52 | + PostgresTokenKind::Fault(_) => { |
| 53 | + Err(format!("SQL tokenization failed: {}", token.value)) |
| 54 | + } |
| 55 | + _ => sql |
| 56 | + .get(token.start..token.end) |
| 57 | + .ok_or_else(|| format!("SQL tokenization failed at byte {}", token.start)), |
| 58 | + }) |
| 59 | + .collect(), |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +/// The index of the `)` closing each `(`, by the index of the `(`. |
| 64 | +fn matching_closers(uppers: &[String]) -> Vec<Option<usize>> { |
| 65 | + let mut closers: Vec<Option<usize>> = vec![None; uppers.len()]; |
| 66 | + let mut open: Vec<usize> = Vec::new(); |
| 67 | + for (index, token) in uppers.iter().enumerate() { |
| 68 | + if token == CALL_OPENER { |
| 69 | + open.push(index); |
| 70 | + } else if token == CALL_CLOSER |
| 71 | + && let Some(opener) = open.pop() |
| 72 | + { |
| 73 | + closers[opener] = Some(index); |
| 74 | + } |
| 75 | + } |
| 76 | + closers |
| 77 | +} |
| 78 | + |
| 79 | +/// Whether the word at `index` is called: followed by `(` and neither a placeholder nor a relation. |
| 80 | +fn calls(raw: &str, uppers: &[String], closers: &[Option<usize>], index: usize) -> bool { |
| 81 | + if uppers.get(index + 1).is_none_or(|next| next != CALL_OPENER) |
| 82 | + || raw.starts_with(PLACEHOLDER_PREFIX) |
| 83 | + { |
| 84 | + return false; |
| 85 | + } |
| 86 | + let previous: Option<&str> = index.checked_sub(1).map(|before| uppers[before].as_str()); |
| 87 | + if previous.is_some_and(|word| COLUMN_LIST_RELATION_KEYWORDS.contains(&word)) { |
| 88 | + return false; |
| 89 | + } |
| 90 | + let Some(closer) = closers[index + 1] else { |
| 91 | + return true; |
| 92 | + }; |
| 93 | + !(uppers |
| 94 | + .get(closer + 1) |
| 95 | + .is_some_and(|next| next == CTE_BODY_PREFIX) |
| 96 | + && uppers |
| 97 | + .get(closer + 2) |
| 98 | + .is_some_and(|next| CTE_BODY_OPENERS.contains(&next.as_str()))) |
| 99 | +} |
0 commit comments