Skip to main content

utopia_query/classifier/
sql.rs

1//! The SQL classification shared by the SQL wire protocols.
2
3use super::Classifier;
4use crate::Type;
5
6/// Classifies SQL text by its leading keyword: the logic shared by the SQL
7/// wire protocol classifiers ([`super::MySql`], [`super::PostgreSql`]),
8/// which implement [`Classifier::classify`] for their packet format and
9/// hand the SQL text to [`Sql::classify_sql`].
10///
11/// Handles leading whitespace, `--` and `/* */` comments, quoted literals and
12/// identifiers (`'..'`, `".."`, `` `..` ``, `$tag$..$tag$`), mixed case,
13/// `COPY ... TO` (read) against `COPY ... FROM` (write), and CTEs
14/// (`WITH ... SELECT` reads, `WITH ... INSERT` writes).
15///
16/// PHP: `Utopia\Query\Classifier\SQL`.
17pub trait Sql: Classifier {
18    /// The classification of the SQL text `query`.
19    ///
20    /// PHP: `SQL::classifySQL()`.
21    fn classify_sql(&self, query: &[u8]) -> Type {
22        classify_sql(query)
23    }
24
25    /// The first keyword of `query`, uppercased (ASCII), after whitespace,
26    /// comments and quoted literals; empty when there is none.
27    ///
28    /// PHP: `SQL::extractKeyword()`.
29    fn extract_keyword(&self, query: &[u8]) -> Vec<u8> {
30        query[keyword_span(query)].to_ascii_uppercase()
31    }
32}
33
34/// What a leading keyword means.
35enum Keyword {
36    Type(Type),
37    Copy,
38    With,
39    Other,
40}
41
42/// The longest keyword looked up (`SAVEPOINT`).
43const LONGEST: usize = 9;
44
45/// Looks `word` up case-insensitively (PHP uppercases it, then looks it up).
46fn keyword(word: &[u8]) -> Keyword {
47    if word.len() > LONGEST {
48        return Keyword::Other;
49    }
50    let mut buf = [0u8; LONGEST];
51    let upper = &mut buf[..word.len()];
52    upper.copy_from_slice(word);
53    upper.make_ascii_uppercase();
54    match &*upper {
55        b"SELECT" | b"SHOW" | b"DESCRIBE" | b"DESC" | b"EXPLAIN" | b"TABLE" | b"VALUES" => Keyword::Type(Type::Read),
56        b"INSERT" | b"UPDATE" | b"DELETE" | b"CREATE" | b"DROP" | b"ALTER" | b"TRUNCATE" | b"GRANT" | b"REVOKE"
57        | b"LOCK" | b"CALL" | b"DO" => Keyword::Type(Type::Write),
58        b"BEGIN" | b"START" => Keyword::Type(Type::TransactionBegin),
59        b"COMMIT" | b"ROLLBACK" => Keyword::Type(Type::TransactionEnd),
60        b"SAVEPOINT" | b"RELEASE" | b"SET" => Keyword::Type(Type::Transaction),
61        b"COPY" => Keyword::Copy,
62        b"WITH" => Keyword::With,
63        _ => Keyword::Other,
64    }
65}
66
67fn classify_sql(query: &[u8]) -> Type {
68    let span = keyword_span(query);
69    if span.is_empty() {
70        return Type::Unknown;
71    }
72    match keyword(&query[span]) {
73        Keyword::Type(t) => t,
74        Keyword::Copy => classify_copy(query),
75        Keyword::With => classify_cte(query),
76        Keyword::Other => Type::Unknown,
77    }
78}
79
80/// The byte range of the first keyword (empty when there is none).
81fn keyword_span(query: &[u8]) -> std::ops::Range<usize> {
82    let len = query.len();
83    let start = skip_insignificant(query, 0, len);
84    let mut pos = start;
85    while pos < len && !matches!(query[pos], b' ' | b'\t' | b'\n' | b'\r' | b'(' | b';') {
86        pos += 1;
87    }
88    start..pos
89}
90
91/// Advances past whitespace, comments and quoted literals or identifiers.
92fn skip_insignificant(query: &[u8], mut pos: usize, len: usize) -> usize {
93    while pos < len {
94        match query[pos] {
95            b' ' | b'\t' | b'\n' | b'\r' | b'\x0c' => pos += 1,
96            b'$' => match skip_dollar_quoted(query, pos, len) {
97                Some(next) => pos = next,
98                None => break,
99            },
100            _ => {
101                let next = skip_literal_or_comment(query, pos, len);
102                if next == pos {
103                    break;
104                }
105                pos = next;
106            }
107        }
108    }
109    pos
110}
111
112fn skip_line_comment(query: &[u8], mut pos: usize, len: usize) -> usize {
113    while pos < len && query[pos] != b'\n' {
114        pos += 1;
115    }
116    if pos < len { pos + 1 } else { pos }
117}
118
119fn skip_block_comment(query: &[u8], mut pos: usize, len: usize) -> usize {
120    while pos + 1 < len {
121        if query[pos] == b'*' && query[pos + 1] == b'/' {
122            return pos + 2;
123        }
124        pos += 1;
125    }
126    len
127}
128
129fn skip_single_quoted(query: &[u8], mut pos: usize, len: usize) -> usize {
130    while pos < len {
131        match query[pos] {
132            b'\\' if pos + 1 < len => pos += 2,
133            b'\'' if pos + 1 < len && query[pos + 1] == b'\'' => pos += 2,
134            b'\'' => return pos + 1,
135            _ => pos += 1,
136        }
137    }
138    len
139}
140
141/// Skips an identifier quoted by `quote`, where a doubled quote escapes it.
142fn skip_quoted(query: &[u8], mut pos: usize, len: usize, quote: u8) -> usize {
143    while pos < len {
144        if query[pos] == quote {
145            if pos + 1 < len && query[pos + 1] == quote {
146                pos += 2;
147                continue;
148            }
149            return pos + 1;
150        }
151        pos += 1;
152    }
153    len
154}
155
156/// Skips a dollar-quoted string (`$tag$...$tag$`) starting at `pos`; `None`
157/// when the `$` does not open one.
158fn skip_dollar_quoted(query: &[u8], pos: usize, len: usize) -> Option<usize> {
159    let mut tag_end = pos + 1;
160    while tag_end < len {
161        let c = query[tag_end];
162        if c == b'$' {
163            break;
164        }
165        if !(c.is_ascii_alphanumeric() || c == b'_') {
166            return None;
167        }
168        tag_end += 1;
169    }
170    if tag_end >= len {
171        return None;
172    }
173    let tag = &query[pos..=tag_end];
174    let body = &query[tag_end + 1..];
175    Some(match body.windows(tag.len()).position(|w| w == tag) {
176        Some(at) => tag_end + 1 + at + tag.len(),
177        None => len,
178    })
179}
180
181/// Skips the literal or comment at `pos`; `pos` when there is none.
182fn skip_literal_or_comment(query: &[u8], pos: usize, len: usize) -> usize {
183    if pos >= len {
184        return pos;
185    }
186    match query[pos] {
187        b'-' if pos + 1 < len && query[pos + 1] == b'-' => skip_line_comment(query, pos + 2, len),
188        b'/' if pos + 1 < len && query[pos + 1] == b'*' => skip_block_comment(query, pos + 2, len),
189        b'\'' => skip_single_quoted(query, pos + 1, len),
190        b'"' => skip_quoted(query, pos + 1, len, b'"'),
191        b'`' => skip_quoted(query, pos + 1, len, b'`'),
192        b'$' => skip_dollar_quoted(query, pos, len).unwrap_or(pos),
193        _ => pos,
194    }
195}
196
197/// The first offset of `needle` in `haystack`, ASCII case-insensitively
198/// (PHP's `stripos`).
199fn find_ignore_case(haystack: &[u8], needle: &[u8]) -> Option<usize> {
200    haystack.windows(needle.len()).position(|w| w.eq_ignore_ascii_case(needle))
201}
202
203/// `COPY ... TO` exports (a read), `COPY ... FROM` imports (a write); a
204/// write when unsure.
205fn classify_copy(query: &[u8]) -> Type {
206    let to = find_ignore_case(query, b" TO ");
207    let from = find_ignore_case(query, b" FROM ");
208    match (to, from) {
209        (Some(_), None) => Type::Read,
210        (Some(to), Some(from)) if to < from => Type::Read,
211        _ => Type::Write,
212    }
213}
214
215/// A CTE is classified by the first read or write keyword at parenthesis
216/// depth 0 after the first CTE block; a read when there is none.
217fn classify_cte(query: &[u8]) -> Type {
218    let len = query.len();
219    let mut pos = 0;
220    let mut depth: i64 = 0;
221    let mut seen_paren = false;
222    while pos < len {
223        let skipped = skip_literal_or_comment(query, pos, len);
224        if skipped != pos {
225            pos = skipped;
226            continue;
227        }
228        let c = query[pos];
229        if c == b'(' {
230            depth += 1;
231            seen_paren = true;
232            pos += 1;
233            continue;
234        }
235        if c == b')' {
236            depth -= 1;
237            pos += 1;
238            continue;
239        }
240        if depth == 0 && seen_paren && c.is_ascii_alphabetic() {
241            let start = pos;
242            while pos < len && (query[pos].is_ascii_alphanumeric() || query[pos] == b'_') {
243                pos += 1;
244            }
245            if let Keyword::Type(t @ (Type::Read | Type::Write)) = keyword(&query[start..pos]) {
246                return t;
247            }
248            continue;
249        }
250        pos += 1;
251    }
252    Type::Read
253}