wasm-dbms-sql 0.10.1

SQL front-end (parser, planner, executor) for the wasm-dbms DBMS engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Lexical analysis: turns SQL text into a list of positioned tokens.

#[cfg(test)]
mod tests;

use wasm_dbms_api::prelude::SqlError;

/// 1-based source position of a token.
///
/// Columns count characters, not bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Position {
    pub(crate) line: usize,
    pub(crate) col: usize,
}

impl Position {
    /// Builds a [`SqlError::Parse`] located at this position.
    pub(crate) fn error(self, msg: impl Into<String>) -> SqlError {
        SqlError::Parse {
            line: self.line,
            col: self.col,
            msg: msg.into(),
        }
    }
}

macro_rules! keywords {
    ($($variant:ident => $text:literal),+ $(,)?) => {
        /// Reserved words of the SQL dialect.
        ///
        /// A reserved word can only be used as a table or column name when it
        /// is written between double quotes.
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub(crate) enum Keyword {
            $($variant),+
        }

        impl Keyword {
            /// Every reserved word, in declaration order.
            pub(crate) const ALL: &'static [Keyword] = &[$(Keyword::$variant),+];

            /// Returns the canonical upper-case spelling of the keyword.
            pub(crate) fn as_str(self) -> &'static str {
                match self {
                    $(Keyword::$variant => $text),+
                }
            }

            /// Returns the keyword spelled `word`, ignoring ASCII case.
            pub(crate) fn from_word(word: &str) -> Option<Self> {
                Self::ALL
                    .iter()
                    .copied()
                    .find(|keyword| keyword.as_str().eq_ignore_ascii_case(word))
            }
        }
    };
}

keywords! {
    And => "AND",
    As => "AS",
    Asc => "ASC",
    Begin => "BEGIN",
    By => "BY",
    Cascade => "CASCADE",
    Commit => "COMMIT",
    Cross => "CROSS",
    Delete => "DELETE",
    Desc => "DESC",
    Distinct => "DISTINCT",
    Except => "EXCEPT",
    False => "FALSE",
    From => "FROM",
    Full => "FULL",
    Group => "GROUP",
    Having => "HAVING",
    In => "IN",
    Inner => "INNER",
    Insert => "INSERT",
    Intersect => "INTERSECT",
    Into => "INTO",
    Is => "IS",
    Join => "JOIN",
    Left => "LEFT",
    Like => "LIKE",
    Limit => "LIMIT",
    Natural => "NATURAL",
    Not => "NOT",
    Null => "NULL",
    Offset => "OFFSET",
    On => "ON",
    Or => "OR",
    Order => "ORDER",
    Outer => "OUTER",
    Restrict => "RESTRICT",
    Right => "RIGHT",
    Rollback => "ROLLBACK",
    Select => "SELECT",
    Set => "SET",
    Transaction => "TRANSACTION",
    True => "TRUE",
    Union => "UNION",
    Update => "UPDATE",
    Using => "USING",
    Values => "VALUES",
    Where => "WHERE",
}

/// A lexical unit of a SQL statement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Token {
    /// A reserved word.
    Keyword(Keyword),
    /// A table, column, alias, or function name; quoted or not.
    Identifier(String),
    /// An unsigned integer literal.
    Integer(u64),
    /// An unsigned decimal literal, kept as written (`digits.digits`).
    Float(String),
    /// The content of a single-quoted string literal, with `''` unescaped.
    String(String),
    /// The `?` parameter placeholder.
    Placeholder,
    Comma,
    Dot,
    LeftParen,
    RightParen,
    Star,
    Semicolon,
    Minus,
    Eq,
    NotEq,
    Lt,
    LtEq,
    Gt,
    GtEq,
    /// End of the statement text.
    Eof,
}

impl Token {
    /// Describes the token for the `found ...` part of an error message.
    pub(crate) fn describe(&self) -> String {
        match self {
            Token::Keyword(keyword) => format!("keyword `{keyword}`", keyword = keyword.as_str()),
            Token::Identifier(name) => format!("identifier `{name}`"),
            Token::Integer(value) => format!("number `{value}`"),
            Token::Float(value) => format!("number `{value}`"),
            Token::String(_) => "string literal".to_string(),
            Token::Placeholder => "`?`".to_string(),
            Token::Comma => "`,`".to_string(),
            Token::Dot => "`.`".to_string(),
            Token::LeftParen => "`(`".to_string(),
            Token::RightParen => "`)`".to_string(),
            Token::Star => "`*`".to_string(),
            Token::Semicolon => "`;`".to_string(),
            Token::Minus => "`-`".to_string(),
            Token::Eq => "`=`".to_string(),
            Token::NotEq => "`!=`".to_string(),
            Token::Lt => "`<`".to_string(),
            Token::LtEq => "`<=`".to_string(),
            Token::Gt => "`>`".to_string(),
            Token::GtEq => "`>=`".to_string(),
            Token::Eof => "end of input".to_string(),
        }
    }
}

/// A [`Token`] together with the position of its first character.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Spanned {
    pub(crate) token: Token,
    pub(crate) position: Position,
}

/// Splits `sql` into tokens.
///
/// Whitespace and comments (`-- line` and `/* block */`) are dropped. The
/// returned list always ends with a [`Token::Eof`] positioned right after the
/// last character.
///
/// # Errors
///
/// Returns [`SqlError::Parse`] for an unterminated string, quoted identifier,
/// or block comment, an empty quoted identifier, a malformed or oversized
/// number, a backtick, a named or numbered placeholder, or any character that
/// is not part of the dialect.
pub(crate) fn tokenize(sql: &str) -> Result<Vec<Spanned>, SqlError> {
    let mut lexer = Lexer::new(sql);
    let mut tokens = Vec::new();
    loop {
        lexer.skip_trivia()?;
        let position = lexer.position;
        let token = lexer.next_token()?;
        let done = token == Token::Eof;
        tokens.push(Spanned { token, position });
        if done {
            return Ok(tokens);
        }
    }
}

/// Character cursor over the statement text.
struct Lexer {
    chars: Vec<char>,
    index: usize,
    position: Position,
}

impl Lexer {
    fn new(sql: &str) -> Self {
        Self {
            chars: sql.chars().collect(),
            index: 0,
            position: Position { line: 1, col: 1 },
        }
    }

    /// Returns the character `offset` places after the cursor.
    fn peek_at(&self, offset: usize) -> Option<char> {
        self.chars.get(self.index + offset).copied()
    }

    fn peek(&self) -> Option<char> {
        self.peek_at(0)
    }

    /// Consumes one character, keeping the line and column up to date.
    fn bump(&mut self) -> Option<char> {
        let c = self.peek()?;
        self.index += 1;
        if c == '\n' {
            self.position.line += 1;
            self.position.col = 1;
        } else {
            self.position.col += 1;
        }
        Some(c)
    }

    /// Consumes one character and returns `token`.
    fn single(&mut self, token: Token) -> Token {
        self.bump();
        token
    }

    /// Consumes two characters and returns `token`.
    fn double(&mut self, token: Token) -> Token {
        self.bump();
        self.bump();
        token
    }

    /// Skips whitespace, `-- line` comments, and `/* block */` comments.
    fn skip_trivia(&mut self) -> Result<(), SqlError> {
        loop {
            match (self.peek(), self.peek_at(1)) {
                (Some(c), _) if c.is_whitespace() => {
                    self.bump();
                }
                (Some('-'), Some('-')) => {
                    while self.peek().is_some_and(|c| c != '\n') {
                        self.bump();
                    }
                }
                (Some('/'), Some('*')) => self.skip_block_comment()?,
                _ => return Ok(()),
            }
        }
    }

    fn skip_block_comment(&mut self) -> Result<(), SqlError> {
        let start = self.position;
        self.bump();
        self.bump();
        loop {
            match (self.peek(), self.peek_at(1)) {
                (Some('*'), Some('/')) => {
                    self.bump();
                    self.bump();
                    return Ok(());
                }
                (Some(_), _) => {
                    self.bump();
                }
                (None, _) => return Err(start.error("unterminated block comment")),
            }
        }
    }

    fn next_token(&mut self) -> Result<Token, SqlError> {
        let position = self.position;
        let Some(c) = self.peek() else {
            return Ok(Token::Eof);
        };
        let token = match (c, self.peek_at(1)) {
            (',', _) => self.single(Token::Comma),
            ('.', _) => self.single(Token::Dot),
            ('(', _) => self.single(Token::LeftParen),
            (')', _) => self.single(Token::RightParen),
            ('*', _) => self.single(Token::Star),
            (';', _) => self.single(Token::Semicolon),
            ('-', _) => self.single(Token::Minus),
            ('?', _) => self.single(Token::Placeholder),
            ('=', _) => self.single(Token::Eq),
            ('!', Some('=')) | ('<', Some('>')) => self.double(Token::NotEq),
            ('<', Some('=')) => self.double(Token::LtEq),
            ('<', _) => self.single(Token::Lt),
            ('>', Some('=')) => self.double(Token::GtEq),
            ('>', _) => self.single(Token::Gt),
            ('\'', _) => Token::String(self.quoted('\'', "unterminated string literal")?),
            ('"', _) => {
                let name = self.quoted('"', "unterminated quoted identifier")?;
                if name.is_empty() {
                    return Err(position.error("quoted identifier cannot be empty"));
                }
                Token::Identifier(name)
            }
            ('`', _) => {
                return Err(position
                    .error("backtick-quoted identifiers are not supported; use double quotes"));
            }
            (':' | '$' | '@', _) => {
                return Err(
                    position.error("named and numbered placeholders are not supported; use `?`")
                );
            }
            (c, _) if c.is_ascii_digit() => self.number()?,
            (c, _) if c.is_ascii_alphabetic() || c == '_' => self.word(),
            (c, _) => return Err(position.error(format!("unexpected character `{c}`"))),
        };
        Ok(token)
    }

    /// Reads a `quote`-delimited token, where a doubled quote stands for one quote.
    fn quoted(&mut self, quote: char, unterminated: &str) -> Result<String, SqlError> {
        let start = self.position;
        self.bump();
        let mut content = String::new();
        loop {
            match (self.bump(), self.peek()) {
                (Some(c), Some(next)) if c == quote && next == quote => {
                    self.bump();
                    content.push(quote);
                }
                (Some(c), _) if c == quote => return Ok(content),
                (Some(c), _) => content.push(c),
                (None, _) => return Err(start.error(unterminated)),
            }
        }
    }

    /// Reads an integer (`digits`) or decimal (`digits.digits`) literal.
    fn number(&mut self) -> Result<Token, SqlError> {
        let start = self.position;
        let mut text = self.digits();
        let is_float =
            self.peek() == Some('.') && self.peek_at(1).is_some_and(|c| c.is_ascii_digit());
        if is_float {
            self.bump();
            text.push('.');
            text.push_str(&self.digits());
        }
        if self
            .peek()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        {
            return Err(start.error("invalid numeric literal"));
        }
        if is_float {
            return Ok(Token::Float(text));
        }
        text.parse()
            .map(Token::Integer)
            .map_err(|_| start.error("integer literal is too large"))
    }

    fn digits(&mut self) -> String {
        let mut digits = String::new();
        while let Some(c) = self.peek().filter(char::is_ascii_digit) {
            self.bump();
            digits.push(c);
        }
        digits
    }

    /// Reads a keyword or an unquoted identifier.
    fn word(&mut self) -> Token {
        let mut word = String::new();
        while let Some(c) = self
            .peek()
            .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
        {
            self.bump();
            word.push(c);
        }
        match Keyword::from_word(&word) {
            Some(keyword) => Token::Keyword(keyword),
            None => Token::Identifier(word),
        }
    }
}