Skip to main content

sql_builder/
lexer.rs

1//! Lexical boundaries of SQL text under one backend's rules: where quoted
2//! text, comments, parameters and words begin and end. It is not a grammar.
3//!
4//! The builder finds the markers of SQL fragments with it, the engine reads
5//! raw statements with it, and TideORM inspects the SQL it runs with it.
6
7/// Whose lexical rules a scan follows.
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum Dialect {
10    /// SQL that may be meant for any backend: PostgreSQL's rules, plus
11    /// SQLite's `[..]` identifiers, and an unclosed dollar quote read as a
12    /// plain `$`.
13    Any,
14    /// MySQL and MariaDB: `#` comments, `--` only before whitespace,
15    /// backslash escapes in strings, block comments that do not nest.
16    MySql,
17    /// PostgreSQL: nested block comments, dollar quotes, `$n` parameters,
18    /// backslash escapes only in `E'..'` strings.
19    Postgres,
20    /// SQLite: `[..]` identifiers, block comments that do not nest, named
21    /// `$`/`:`/`@`/`#` parameters, no backslash escapes.
22    Sqlite,
23}
24
25/// What a [`Token`] is.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum Kind {
28    /// An unquoted word: a keyword or a name.
29    Word,
30    /// A quoted identifier (and, on MySQL, a double-quoted string).
31    Identifier,
32    /// A single-quoted or dollar-quoted string.
33    Literal,
34    /// A line or block comment.
35    Comment,
36    /// A run of whitespace.
37    Space,
38    /// Any other single character.
39    Symbol,
40    /// A `$n` parameter, or a SQLite named one.
41    Parameter,
42}
43
44/// One lexical unit of a statement.
45#[derive(Clone, Copy, Debug)]
46pub struct Token<'a> {
47    /// The token as written.
48    pub text: &'a str,
49    /// The byte offset of `text` in the scanned SQL.
50    pub start: usize,
51    /// What the token is.
52    pub kind: Kind,
53    /// Whether a quote, comment or dollar quote the token opens is closed;
54    /// an unclosed one runs to the end of the SQL.
55    pub terminated: bool,
56}
57
58impl Token<'_> {
59    /// Whether the token is one of `words`, in any case.
60    pub fn is_word(&self, words: &[&str]) -> bool {
61        self.kind == Kind::Word
62            && words
63                .iter()
64                .any(|word| self.text.eq_ignore_ascii_case(word))
65    }
66
67    /// Whether the token is one of `symbols`.
68    pub fn is_symbol(&self, symbols: &[&str]) -> bool {
69        self.kind == Kind::Symbol && symbols.contains(&self.text)
70    }
71
72    /// The name a quoted identifier or a single-quoted string spells, as SQL
73    /// names a column after it: without its quotes, each doubled closing
74    /// quote single. Any other token as written; `None` for a quoted one its
75    /// closing quote does not end.
76    pub fn unquoted(&self) -> Option<String> {
77        if self.kind != Kind::Identifier
78            && !(self.kind == Kind::Literal && self.text.starts_with('\''))
79        {
80            return Some(self.text.to_string());
81        }
82        let close = if self.text.starts_with('[') {
83            ']'
84        } else {
85            self.text.chars().next()?
86        };
87        let inner = self.text.strip_suffix(close)?.get(1..)?;
88        Some(inner.replace(&format!("{close}{close}"), &close.to_string()))
89    }
90}
91
92/// The tokens of `sql` under `dialect`'s rules, lexed only as far as the
93/// caller reads.
94pub fn tokens(sql: &str, dialect: Dialect) -> impl Iterator<Item = Token<'_>> {
95    let mut offset = 0;
96    std::iter::from_fn(move || {
97        let rest = &sql[offset..];
98        let first = rest.chars().next()?;
99        let (len, kind, terminated) = token_at(sql, offset, first, dialect);
100        let token = Token {
101            text: &rest[..len],
102            start: offset,
103            kind,
104            terminated,
105        };
106        offset += len;
107        Some(token)
108    })
109}
110
111/// The length, kind and termination of the token starting with `first` at
112/// `offset` in `sql`.
113fn token_at(sql: &str, offset: usize, first: char, dialect: Dialect) -> (usize, Kind, bool) {
114    let rest = &sql[offset..];
115    let whitespace = |c: char| c.is_whitespace() || (dialect == Dialect::Sqlite && c == '\u{feff}');
116    if whitespace(first) {
117        let len = rest.find(|c: char| !whitespace(c)).unwrap_or(rest.len());
118        return (len, Kind::Space, true);
119    }
120    let line_comment = match dialect {
121        Dialect::MySql => {
122            first == '#'
123                || (rest.starts_with("--")
124                    && rest
125                        .as_bytes()
126                        .get(2)
127                        .is_none_or(|byte| byte.is_ascii_whitespace() || byte.is_ascii_control()))
128        }
129        _ => rest.starts_with("--"),
130    };
131    if line_comment {
132        let len = rest.find(['\n', '\r']).unwrap_or(rest.len());
133        return (len, Kind::Comment, true);
134    }
135    if rest.starts_with("/*") {
136        let nested = matches!(dialect, Dialect::Any | Dialect::Postgres);
137        let (len, terminated) = block_comment(rest, nested);
138        return (len, Kind::Comment, terminated);
139    }
140    let brackets = matches!(dialect, Dialect::Any | Dialect::Sqlite);
141    if matches!(first, '\'' | '"' | '`') || (first == '[' && brackets) {
142        let kind = if first == '\'' {
143            Kind::Literal
144        } else {
145            Kind::Identifier
146        };
147        let mode = if backslash_escapes(sql, offset, first, dialect) {
148            EscapeMode::Backslash
149        } else {
150            EscapeMode::Doubled
151        };
152        let close = if first == '[' { ']' } else { first };
153        let (len, run) = quoted_end(
154            rest.char_indices().skip(1),
155            close,
156            mode,
157            rest.len(),
158            char::len_utf8,
159        );
160        return (len, kind, run == QuotedRun::Closed);
161    }
162    if dialect == Dialect::Sqlite && matches!(first, '$' | ':' | '@' | '#') {
163        return (sqlite_parameter_len(rest), Kind::Parameter, true);
164    }
165    if first == '$' && matches!(dialect, Dialect::Any | Dialect::Postgres) {
166        if let Some(open) = dollar_tag_len(rest) {
167            let delimiter = &rest[..open];
168            match rest[open..].find(delimiter) {
169                Some(close) => return (open + close + delimiter.len(), Kind::Literal, true),
170                None if dialect == Dialect::Postgres => return (rest.len(), Kind::Literal, false),
171                None => {}
172            }
173        }
174        let len = 1 + rest[1..].bytes().take_while(u8::is_ascii_digit).count();
175        let kind = if len > 1 {
176            Kind::Parameter
177        } else {
178            Kind::Symbol
179        };
180        return (len, kind, true);
181    }
182    if first == '_' || first.is_alphabetic() {
183        let len = rest
184            .find(|c: char| !identifier_char(c))
185            .unwrap_or(rest.len());
186        return (len, Kind::Word, true);
187    }
188    (first.len_utf8(), Kind::Symbol, true)
189}
190
191/// Whether a backslash escapes the next character inside the quote opening
192/// at `quote_index`: in MySQL's strings (not its backtick identifiers), and
193/// in a PostgreSQL `E'..'` string.
194fn backslash_escapes(sql: &str, quote_index: usize, quote: char, dialect: Dialect) -> bool {
195    match dialect {
196        Dialect::MySql => quote != '`',
197        Dialect::Sqlite => false,
198        Dialect::Any | Dialect::Postgres => {
199            quote == '\''
200                && quote_index > 0
201                && matches!(sql.as_bytes()[quote_index - 1], b'e' | b'E')
202                && !sql[..quote_index - 1]
203                    .chars()
204                    .next_back()
205                    .is_some_and(identifier_char)
206        }
207    }
208}
209
210/// SQLite named parameters can include Tcl-style namespaces and a
211/// parenthesized suffix. A semicolon in that suffix belongs to the
212/// parameter, not a statement.
213fn sqlite_parameter_len(sql: &str) -> usize {
214    let mut pos = 1;
215    let mut has_name = false;
216    while let Some(ch) = sql[pos..].chars().next() {
217        if identifier_char(ch) || !ch.is_ascii() {
218            has_name = true;
219            pos += ch.len_utf8();
220        } else if sql[pos..].starts_with("::") {
221            pos += 2;
222        } else {
223            if ch == '(' && has_name {
224                pos += 1;
225                for ch in sql[pos..].chars() {
226                    if ch.is_ascii_whitespace() {
227                        break;
228                    }
229                    pos += ch.len_utf8();
230                    if ch == ')' {
231                        break;
232                    }
233                }
234            }
235            break;
236        }
237    }
238    pos
239}
240
241/// Whether `c` can continue an unquoted identifier.
242pub fn identifier_char(c: char) -> bool {
243    c == '_' || c == '$' || c.is_alphanumeric()
244}
245
246/// The length of the block comment opening `sql`, and whether it is closed.
247fn block_comment(sql: &str, nested: bool) -> (usize, bool) {
248    let mut depth = 1;
249    let mut pos = 2;
250    while let Some(ch) = sql.get(pos..).and_then(|rest| rest.chars().next()) {
251        if nested && sql[pos..].starts_with("/*") {
252            depth += 1;
253            pos += 2;
254        } else if sql[pos..].starts_with("*/") {
255            depth -= 1;
256            pos += 2;
257            if depth == 0 {
258                return (pos, true);
259            }
260        } else {
261            pos += ch.len_utf8();
262        }
263    }
264    (pos, false)
265}
266
267/// The length of the block comment opening `sql`, to the end of `sql` when
268/// it is not closed.
269pub fn block_comment_len(sql: &str, nested: bool) -> usize {
270    block_comment(sql, nested).0
271}
272
273/// How a quoted run escapes its closing quote.
274#[derive(Clone, Copy, Debug, PartialEq, Eq)]
275pub enum EscapeMode {
276    /// Only by doubling it.
277    Doubled,
278    /// By doubling it or with a backslash.
279    Backslash,
280    /// By doubling it; a backslash before it is ambiguous between backends.
281    RejectAmbiguous,
282}
283
284/// How a quoted run ends.
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub enum QuotedRun {
287    /// At its closing quote.
288    Closed,
289    /// At the end of the input, without a closing quote.
290    Unterminated,
291    /// At a backslash before a quote, under [`EscapeMode::RejectAmbiguous`].
292    AmbiguousEscape,
293}
294
295/// Scan after an opening delimiter. Positions may be bytes or character indices;
296/// callers supply the corresponding width and end so validation stays allocation-free.
297pub fn quoted_end(
298    chars: impl Iterator<Item = (usize, char)>,
299    close: char,
300    mode: EscapeMode,
301    end: usize,
302    width: impl Fn(char) -> usize,
303) -> (usize, QuotedRun) {
304    let mut chars = chars.peekable();
305    while let Some((index, ch)) = chars.next() {
306        if ch == '\\' && mode != EscapeMode::Doubled {
307            if mode == EscapeMode::RejectAmbiguous {
308                if chars.peek().is_some_and(|(_, next)| *next == close) {
309                    return (index, QuotedRun::AmbiguousEscape);
310                }
311                if chars.peek().is_some_and(|(_, next)| *next == '\\') {
312                    chars.next();
313                }
314            } else {
315                chars.next();
316            }
317        } else if ch == close {
318            if chars.peek().is_some_and(|(_, next)| *next == close) {
319                chars.next();
320            } else {
321                return (index + width(ch), QuotedRun::Closed);
322            }
323        }
324    }
325    (end, QuotedRun::Unterminated)
326}
327
328/// The length of the quoted run `sql` opens with `delimiter` (`[` closes
329/// with `]`), to the end of `sql` when it is not closed.
330pub fn quoted_len(sql: &str, delimiter: char, backslash: bool) -> usize {
331    let close = if delimiter == '[' { ']' } else { delimiter };
332    let mode = if backslash {
333        EscapeMode::Backslash
334    } else {
335        EscapeMode::Doubled
336    };
337    quoted_end(
338        sql.char_indices().skip(1),
339        close,
340        mode,
341        sql.len(),
342        char::len_utf8,
343    )
344    .0
345}
346
347/// The length of the PostgreSQL dollar-quote delimiter opening `sql`, `$$` or
348/// `$tag$`, whose tag does not start with a digit.
349pub fn dollar_tag_len(sql: &str) -> Option<usize> {
350    let end = sql[1..].find('$')? + 1;
351    let tag = &sql[1..end];
352    (!tag.starts_with(|c: char| c.is_ascii_digit())
353        && tag.chars().all(|c| c == '_' || c.is_alphanumeric()))
354    .then_some(end + 1)
355}
356
357#[cfg(test)]
358#[path = "../tests/unit/lexer_tests.rs"]
359mod tests;