Skip to main content

vibesql_parser/
lib.rs

1//! SQL:1999 Parser crate.
2//!
3//! Provides tokenization and parsing of SQL statements into the shared AST.
4//!
5//! # Arena-allocated Parser
6//!
7//! For performance-critical code paths, the [`arena_parser`] module provides
8//! an arena-based parser that allocates AST nodes from a bump allocator.
9//!
10//! # Arena Fallback Parsing
11//!
12//! The [`parse_with_arena_fallback`] function provides optimized parsing by
13//! using arena allocation for supported statement types (SELECT) while falling
14//! back to standard heap allocation for other statements. This provides the
15//! best of both worlds: arena performance where it helps most (complex queries)
16//! and full feature support for all SQL statements.
17//!
18//! ```
19//! use vibesql_parser::parse_with_arena_fallback;
20//!
21//! let stmt = parse_with_arena_fallback("SELECT * FROM users").unwrap();
22//! // Uses arena parsing internally, converts to standard Statement
23//! ```
24
25pub mod arena_parser;
26
27mod keywords;
28mod lexer;
29mod parser;
30#[cfg(test)]
31mod tests;
32mod token;
33mod trigger_body;
34
35pub use keywords::Keyword;
36pub use lexer::{Lexer, LexerError, Span};
37pub use parser::{ParseError, Parser};
38pub use token::Token;
39pub use trigger_body::split_trigger_body_statements;
40use vibesql_ast::Statement;
41
42/// Returns `true` if `name` is a SQL keyword (case-insensitive).
43///
44/// Used by callers that emit SQL text (e.g. the persistence dump) to decide
45/// whether a bare identifier must be double-quoted to survive a round-trip. A
46/// keyword-named identifier such as `create` must be written as `"create"`;
47/// otherwise the reload re-lexes it as the keyword token and loses the original
48/// spelling/case (issue #5618).
49pub fn is_keyword(name: &str) -> bool {
50    // Re-lex the bare name: if it tokenizes to a single keyword token, the
51    // word is reserved/keyword and must be quoted to round-trip as an
52    // identifier. (A genuine identifier lexes to `Token::Identifier`.)
53    let mut lexer = Lexer::new(name);
54    match lexer.tokenize() {
55        Ok(tokens) => {
56            // tokenize() appends a trailing Eof token.
57            matches!(tokens.first(), Some(Token::Keyword { .. }))
58                && matches!(tokens.get(1), Some(Token::Eof) | None)
59        }
60        Err(_) => false,
61    }
62}
63
64/// Parse SQL using arena allocation where supported, falling back to standard parsing.
65///
66/// This function provides optimized parsing by:
67/// 1. Detecting the statement type from the first token
68/// 2. Using arena-allocated parsing for SELECT statements
69/// 3. Converting arena AST to standard heap-allocated AST
70/// 4. Falling back to standard parsing for unsupported statement types
71///
72/// # Performance
73///
74/// Arena parsing can provide 10-15% improvement for complex SELECT statements
75/// due to reduced allocation overhead and better cache locality. The conversion
76/// to standard AST types adds minimal overhead.
77///
78/// # Supported Statement Types
79///
80/// Currently uses arena parsing for:
81/// - SELECT statements (including CTEs, subqueries, joins)
82///
83/// Falls back to standard parsing for:
84/// - INSERT, UPDATE, DELETE (arena support planned for future)
85/// - DDL statements (CREATE, ALTER, DROP)
86/// - Transaction statements (BEGIN, COMMIT, ROLLBACK)
87/// - Other SQL statements
88///
89/// # Example
90///
91/// ```
92/// use vibesql_parser::parse_with_arena_fallback;
93///
94/// // Uses arena parsing
95/// let select = parse_with_arena_fallback("SELECT * FROM users WHERE id = 1").unwrap();
96///
97/// // Falls back to standard parsing
98/// let insert = parse_with_arena_fallback("INSERT INTO users VALUES (1, 'Alice')").unwrap();
99/// ```
100pub fn parse_with_arena_fallback(sql: &str) -> Result<Statement, ParseError> {
101    // Tokenize to detect statement type
102    let mut lexer = Lexer::new(sql);
103    let tokens = lexer.tokenize().map_err(|e| ParseError { message: e.to_string() })?;
104
105    // Check first token to determine statement type
106    if let Some(first_token) = tokens.first() {
107        if matches!(
108            first_token,
109            Token::Keyword { keyword: Keyword::Select, .. }
110                | Token::Keyword { keyword: Keyword::With, .. }
111        ) {
112            // Use arena parsing for SELECT statements (including WITH CTEs)
113            match arena_parser::parse_select_to_owned(sql) {
114                Ok(select_stmt) => {
115                    return Ok(Statement::Select(Box::new(select_stmt)));
116                }
117                Err(_) => {
118                    // Arena parsing failed, fall back to standard parser
119                    // This can happen with edge cases the arena parser doesn't support yet
120                }
121            }
122        }
123    }
124
125    // Fall back to standard parser for all other statements
126    // or if arena parsing failed
127    Parser::parse_sql(sql)
128}
129
130#[cfg(test)]
131mod arena_fallback_tests {
132    use super::*;
133
134    #[test]
135    fn test_arena_fallback_simple_select() {
136        let result = parse_with_arena_fallback("SELECT * FROM users");
137        assert!(result.is_ok());
138        assert!(matches!(result.unwrap(), Statement::Select(_)));
139    }
140
141    #[test]
142    fn test_arena_fallback_select_with_where() {
143        let result = parse_with_arena_fallback("SELECT id, name FROM users WHERE active = TRUE");
144        assert!(result.is_ok());
145        assert!(matches!(result.unwrap(), Statement::Select(_)));
146    }
147
148    #[test]
149    fn test_arena_fallback_select_with_cte() {
150        let result = parse_with_arena_fallback(
151            "WITH active_users AS (SELECT * FROM users WHERE active = TRUE) \
152             SELECT * FROM active_users",
153        );
154        assert!(result.is_ok());
155        assert!(matches!(result.unwrap(), Statement::Select(_)));
156    }
157
158    #[test]
159    fn test_arena_fallback_insert() {
160        let result = parse_with_arena_fallback("INSERT INTO users (id, name) VALUES (1, 'Alice')");
161        assert!(result.is_ok());
162        assert!(matches!(result.unwrap(), Statement::Insert(_)));
163    }
164
165    #[test]
166    fn test_arena_fallback_update() {
167        let result = parse_with_arena_fallback("UPDATE users SET name = 'Bob' WHERE id = 1");
168        assert!(result.is_ok());
169        assert!(matches!(result.unwrap(), Statement::Update(_)));
170    }
171
172    #[test]
173    fn test_arena_fallback_delete() {
174        let result = parse_with_arena_fallback("DELETE FROM users WHERE id = 1");
175        assert!(result.is_ok());
176        assert!(matches!(result.unwrap(), Statement::Delete(_)));
177    }
178
179    #[test]
180    fn test_arena_fallback_create_table() {
181        let result = parse_with_arena_fallback("CREATE TABLE users (id INT PRIMARY KEY)");
182        assert!(result.is_ok());
183        assert!(matches!(result.unwrap(), Statement::CreateTable(_)));
184    }
185
186    #[test]
187    fn test_arena_fallback_qualified_wildcard() {
188        let result = parse_with_arena_fallback("SELECT t1.* FROM t1");
189        assert!(result.is_ok());
190        if let Statement::Select(select) = result.unwrap() {
191            assert_eq!(select.select_list.len(), 1);
192            match &select.select_list[0] {
193                vibesql_ast::SelectItem::QualifiedWildcard { qualifier, alias: _ } => {
194                    assert_eq!(qualifier, "t1");
195                }
196                other => panic!("Expected QualifiedWildcard, got {:?}", other),
197            }
198        } else {
199            panic!("Expected SELECT statement");
200        }
201    }
202
203    #[test]
204    fn test_window_clause_parsing() {
205        // Test 1: Just OVER win (without WINDOW clause) - window name reference
206        let sql = "SELECT sum(x) OVER win FROM t1";
207        let result = Parser::parse_sql(sql);
208        assert!(result.is_ok(), "OVER win reference failed: {:?}", result.err());
209
210        // Test 2: WINDOW clause definition
211        let sql = "SELECT 1 FROM t1 WINDOW win AS (ORDER BY y)";
212        let result = Parser::parse_sql(sql);
213        assert!(result.is_ok(), "WINDOW clause failed: {:?}", result.err());
214
215        // Test 3: Full window clause with reference
216        let sql = "SELECT sum(x) OVER win FROM t1 WINDOW win AS (ORDER BY y)";
217        let result = Parser::parse_sql(sql);
218        assert!(result.is_ok(), "Full WINDOW clause failed: {:?}", result.err());
219
220        // Test 4: Window inheritance (WINDOW win2 AS (win ORDER BY ...))
221        let sql = "SELECT row_number() OVER win2 FROM t1 WINDOW win AS (PARTITION BY z), win2 AS (win ORDER BY x)";
222        let result = Parser::parse_sql(sql);
223        assert!(result.is_ok(), "Window inheritance failed: {:?}", result.err());
224    }
225
226    #[test]
227    fn test_is_keyword() {
228        // Reserved/keyword words (case-insensitive) — these must be quoted to be
229        // used as identifiers, and a SQL emitter must quote them (issue #5618).
230        assert!(is_keyword("create"));
231        assert!(is_keyword("CREATE"));
232        assert!(is_keyword("Select"));
233        assert!(is_keyword("from"));
234        assert!(is_keyword("table"));
235
236        // Ordinary identifiers are not keywords.
237        assert!(!is_keyword("mixedcase"));
238        assert!(!is_keyword("MixedCase"));
239        assert!(!is_keyword("f1"));
240        assert!(!is_keyword("users"));
241        assert!(!is_keyword("col_a"));
242
243        // A multi-token / punctuated string is not a single keyword.
244        assert!(!is_keyword("create table"));
245        assert!(!is_keyword("a.b"));
246        assert!(!is_keyword(""));
247    }
248}