Lexer, parser and prepared statements
The SQL front end is a hand-written lexer and a recursive-descent parser in src/query/sql/. The parser does not build an abstract syntax tree: it returns a LogicalPlan (see logical plan) whose expressions are Expr values. SqlAnalyzer::parse_statement is the entry point; it calls Parser::new(sql)?.parse() (source: src/query/sql/mod.rs, SqlAnalyzer::parse_statement). Tested by test_simple_select and test_select_with_where in src/query/sql/mod.rs.
Parsing has three steps:
-
Lexerturns the text into aVec<Token>, where eachTokenhas atoken_type,lineandcolumn. -
resolve_named_windowsrewrites the token stream, inlining eachWINDOW w AS (...)definition whereOVER wis used. -
Parser::parsewalks the tokens and builds the plan.
(source: src/query/sql/lexer.rs, Lexer, Token; src/query/sql/parser.rs, Parser::new, resolve_named_windows, Parser::parse)
Lexer
Whitespace, comments and identifiers
| Input | Token |
|---|---|
-- ... to end of line, /* ... */
|
Skipped. Block comments do not nest. |
ASCII letter or _, then letters, digits, _
|
Keyword or Identifier. Keywords are matched case-insensitively in keyword_or_identifier, which has about 197 arms. |
"name" or `name`
|
Identifier with case preserved. A doubled quote escapes itself. |
(source: src/query/sql/lexer.rs, Lexer::next_token, Lexer::scan_identifier_or_keyword, keyword_or_identifier)
Literals
| Input | Token | Notes |
|---|---|---|
123 |
Integer(i64) |
A value that overflows i64 becomes Float with its source text kept. |
1.5, 1e10
|
Float(OrderedFloat<f64>, String) |
The source text is kept so the parser can build an exact NUMERIC. OrderedFloat is from the ordered_float crate. |
0x1F, 0o17, 0b101
|
Integer |
_ separators allowed. A value that fits u64 but not i64 is clamped to i64::MAX. |
'text' |
String |
'' escapes a quote. Under the MySQL dialect, backslash escapes are processed. Unterminated input fails with "Unterminated string". |
E'...' |
String |
Backslash escapes. |
B'0101' |
BitString |
Only when the MySQL dialect is off. |
X'...' |
hex string | |
$$...$$, $tag$...$tag$
|
String |
Dollar quoting. |
$1, $2
|
Parameter(usize) |
Bind placeholder. |
@var, @@var
|
variable | MySQL user and system variables. |
(source: src/query/sql/lexer.rs, Lexer::scan_number, Lexer::scan_string, Lexer::scan_parameter, TokenType)
Operators
| Group | Operators |
|---|---|
| Comparison and arithmetic | = <> != < <= > >= + - * / % ^ |
| String | \|\| |
| Bitwise | & \| # << >> ~ |
| Square and cube root |
\|/, \|\|/
|
| Casts and named args |
::, =>
|
| Regex and LIKE | ~ !~ ~* !~* ~~ !~~ ~~* !~~* |
| JSON | -> ->> #> #>> #- @> <@ ? ?\| ?& |
| Array overlap | && |
| Network |
>>=, <<=
|
| Full-text | @@ |
| pgvector distance |
<-> (L2), <=> (cosine), <#> (inner product), <+> (L1) |
Any other character fails with "Unknown character" (source: src/query/sql/lexer.rs, Lexer::scan_operator_or_punctuation). Tested by test_operators, test_regex_like_operators, test_bitwise_operators and test_bitwise_does_not_clobber_concat_or_overlap in src/query/sql/lexer.rs.
Lexer tests
test_simple_select, test_numbers, test_strings, test_operators, test_regex_like_operators, test_bitwise_operators, test_bitwise_does_not_clobber_concat_or_overlap, test_dollar_quoted_string, test_dollar_quoted_with_tag and test_param_placeholder_not_dollar_quote (source: src/query/sql/lexer.rs, mod tests).
Dialect hooks
The lexer and parser are shared by every wire. Dialect differences come from session flags:
| Hook | Where it is read | Effect |
|---|---|---|
MYSQL_DIALECT thread-local, set by MySqlDialectGuard::enable() and restored on drop |
Lexer |
<=> is null-safe equality instead of the cosine distance operator; backslash escapes in plain strings; B'..' is not a bit string |
same flag, mysql_dialect_enabled()
|
Parser |
XOR operator; HAVING without GROUP BY or aggregates acts as WHERE; STD/STDDEV/VARIANCE are population forms; schema.table drops the schema part |
DECIMAL_DIVISION thread-local, DecimalDivisionGuard
|
Optimizer and evaluator | Integer division is not folded as integer division (Snowflake) |
sqlite_dialect, mssql_dialect, clickhouse_dialect fields on QueryEngine
|
Engine execution | Typing and result-shape rules per dialect; not read by the lexer or parser |
| T-SQL translation | SQL Server wire, before the engine | Splits batches and rewrites T-SQL syntax into the engine's dialect |
(source: src/query/sql/lexer.rs, MySqlDialectGuard, DecimalDivisionGuard; src/query/sql/parser.rs, parse_select, parse_variance_family, relation_from_parts; src/query/engine.rs, set_sqlite_dialect, set_mssql_dialect, set_clickhouse_dialect; src/protocol/mssql/tsql.rs)
Because the flags are thread-local and armed per statement by execute and execute_unguarded, a parse that happens outside those calls uses the default PostgreSQL rules (source: src/query/engine.rs, QueryEngine::execute_unguarded).
Parser
Parser::parse
parse parses one statement. If the statement had data-modifying CTEs (WITH x AS (INSERT ... RETURNING ...)), it wraps the plan in LogicalPlan::WithDml. One trailing ; is allowed; any other remaining token fails with "Unexpected tokens after statement" (source: src/query/sql/parser.rs, Parser::parse). Multi-statement strings are split before this point by the caller.
Statement dispatch
parse_statement is the source of truth for the statements the SQL parser accepts:
| Leading token(s) | Result |
|---|---|
| empty or comments only | Empty |
WITH |
parse_with_clause: RECURSIVE, column lists, [NOT] MATERIALIZED, VALUES anchors, DML CTEs |
SELECT, (
|
parse_select |
INSERT; REPLACE not followed by (
|
parse_insert |
UPDATE, DELETE, CREATE, DROP, ALTER
|
their parse functions |
RENAME [TABLE] a TO b |
AlterTableRename |
GRANT |
parse_grant; on a parse failure a warning is logged and Empty is returned |
REVOKE |
parse_revoke; a parse failure is an error |
BEGIN, START, COMMIT, ROLLBACK, SAVEPOINT, RELEASE
|
transaction plans |
ABORT |
Rollback |
SET |
parse_set_statement; SET CONSTRAINTS is a no-op |
RESET, SHOW
|
their parse functions |
EXPLAIN |
parse_explain |
DISCARD, LOCK, FLUSH, COMMENT
|
Empty |
TRUNCATE |
Delete with no filter; accepts TABLE, IF EXISTS, ONLY, ON CLUSTER, RESTART/CONTINUE IDENTITY, CASCADE
|
DO [LANGUAGE l] body |
DoBlock, default language plpgsql
|
REFRESH MATERIALIZED VIEW [CONCURRENTLY] v |
RefreshMatView (CONCURRENTLY is accepted and ignored) |
DECLARE, FETCH, MOVE, CLOSE
|
cursor plans, see cursors |
| anything else | error "Expected statement" |
(source: src/query/sql/parser.rs, Parser::parse_statement)
Several statements never reach this dispatch because the engine answers them from the text first; see statements that bypass the planner.
SELECT grammar
| Clause | Supported forms |
|---|---|
| Select list | expressions, *, t.*, aliases with or without AS; DISTINCT, DISTINCT ON (...)
|
FROM |
tables, subqueries, table functions, VALUES; comma joins; INNER, LEFT, RIGHT, FULL, CROSS joins; NATURAL; USING (...); LATERAL; MySQL STRAIGHT_JOIN (an inner join); ONLY
|
| Sampling |
TABLESAMPLE BERNOULLI(p) and SYSTEM(p), both turned into a random-probability Filter
|
WHERE, HAVING
|
any expression |
GROUP BY |
expressions, ROLLUP, CUBE, GROUPING SETS, MySQL WITH ROLLUP
|
WINDOW |
named windows, inlined before parsing |
ORDER BY |
expressions and output ordinals, ASC/DESC, NULLS FIRST/LAST
|
| Limits |
LIMIT n, OFFSET n, MySQL LIMIT offset, count, FETCH FIRST/NEXT n ROWS ONLY, FETCH ... WITH TIES (LimitWithTies) |
| Locking |
FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE, OF t, NOWAIT, SKIP LOCKED
|
| Set operations |
UNION [ALL], INTERSECT [ALL], EXCEPT [ALL], with a trailing ORDER BY/LIMIT that applies to the whole result |
(source: src/query/sql/parser.rs, parse_select, parse_from_clause, parse_table_reference, parse_group_by_clause, parse_order_by_list, parse_lock_clause, parse_limit_after_lock)
Tested by test_parse_join in src/query/sql/parser.rs.
Tested by test_parse_for_update_skip_locked (src/query/sql/parser.rs) and, through the engine, by test_set_op_trailing_order_by_limit_applies_to_whole and test_comma_join_becomes_inner_join (src/query/engine.rs).
Expression precedence
The expression parser is a precedence-climbing chain, lowest first:
| Level | Function | Operators |
|---|---|---|
| 1 | parse_or_expression |
OR |
| 2 | parse_xor_expression |
XOR (MySQL only) |
| 3 | parse_and_expression |
AND |
| 4 | parse_not_expression |
NOT |
| 5 | parse_comparison_expression |
comparisons, IS, IN, BETWEEN, LIKE/ILIKE, regex, JSON operators (->, ->>, containment), vector distance |
| 6 | parse_bitwise_expression |
&, \|, #, <<, >>
|
| 7 | parse_additive_expression |
+, -, \|\|
|
| 8 | parse_multiplicative_expression |
*, /, %
|
| 9 | parse_power_expression |
^ |
| 10 | parse_unary_expression |
unary -, ~ (bitwise not), \|/, \|\|/, @
|
| 11 | parse_postfix_expression |
::type casts, [i] subscripts, [a:b] slices |
| 12 | parse_primary_expression |
literals, columns, function calls, CASE (parse_case_expression), CAST, subqueries, EXISTS, ARRAY[...], parameters |
(source: src/query/sql/parser.rs, parse_expression and the functions named above)
$n becomes Expr::Param(n - 1), so parameters are bound at evaluation time, not spliced into the text (source: src/query/sql/parser.rs, Parser::parse_primary_expression). A comment in that branch says the branch is dead because parameters are text-spliced before parsing; that is no longer true. execute_with_timeout_inner does not call substitute_query_params, and only LIMIT/OFFSET parameters are spliced (source: src/query/engine.rs, substitute_limit_offset_params). The Expr::Param doc comment in src/plan/logical.rs, which says the parser never produces it, is stale for the same reason.
Other statement parsers
-
parse_explainacceptsEXPLAIN ANALYZE stmtandEXPLAIN (option, ...) stmt. In the list,FORMAT JSONselects JSON and any other format selects text;ANALYZE [TRUE|FALSE]sets analyze;BUFFERS,COSTS,VERBOSEandTIMINGare skipped. See EXPLAIN. -
parse_declare_cursorskipsBINARY,INSENSITIVE,ASENSITIVE,[NO] SCROLLandWITH/WITHOUT HOLD, and requiresCURSORandFOR. -
INSERTsupportsON CONFLICT ... DO NOTHING | DO UPDATE, MySQLON DUPLICATE KEY UPDATE,RETURNINGandINSERT ... SELECT. Tested bytest_parse_insert_on_conflict_do_update. -
CREATE MATERIALIZED VIEWis tested bytest_parse_create_materialized_view. -
INFORMATION_SCHEMA_VIEWSlists theinformation_schemarelations the parser recognises.
(source: src/query/sql/parser.rs, parse_explain, parse_declare_cursor, parse_insert, INFORMATION_SCHEMA_VIEWS)
Errors
Parse failures are Error::Parse with a message such as "Expected statement", "Unexpected tokens after statement", "Unterminated string" or "Unknown character". When the plan cache misses and parsing fails, the engine first tries catalog_fallback, then returns the parse error (source: src/query/engine.rs, QueryEngine::execute_with_timeout_inner, catalog_fallback).
Other query languages
QueryLanguage lists SQL, MQL, Cypher, GraphQL, SynergyQL and SPARQL, and each analyzer implements the Analyzer trait (source: src/query/mod.rs, QueryLanguage, Analyzer). In QueryEngine, Cypher and MQL have their own analyzers, GraphQL and SynergyQL go through the SQL analyzer, and SPARQL is rejected (source: src/query/engine.rs, parse_query). See statement lifecycle.
Prepared statement cache
There are three separate mechanisms. Only the first two are live.
| Mechanism | Scope | Status |
|---|---|---|
plan_cache / opt_plan_cache on QueryEngine
|
One session, keyed by statement text | Live, see lifecycle |
sql_prepared on QueryEngine
|
SQL-level PREPARE name AS ..., EXECUTE name(args), DEALLOCATE
|
Live. EXECUTE substitutes the argument text into the stored statement and runs it through execute. |
StatementCache in src/query/stmt_cache.rs
|
Process-wide | Not wired |
(source: src/query/engine.rs, QueryEngine::execute_unguarded; src/query/stmt_cache.rs)
Wire-level prepared statements (PostgreSQL extended protocol, MySQL COM_STMT_PREPARE) are kept by the wires; the MySQL wire has its own PreparedStatementCache (source: src/protocol/mysql/mod.rs, PreparedStatementCache). See the PostgreSQL and MySQL wire pages.
StatementCache
Not wired: StatementCache is re-exported from src/query/mod.rs but no code outside stmt_cache.rs calls it, and global_statement_cache / init_global_statement_cache have no callers (source: src/query/mod.rs; src/query/stmt_cache.rs, global_statement_cache). What it implements:
- An LRU map from the
lrucrate behind aparking_lot::RwLock. - Key
StatementCacheKey { sql, database }, wheresqlis normalized by collapsing runs of whitespace outside quoted strings. - Value
CachedStatement { plan, columns, param_count, param_types, use_count }. -
StatementCacheConfigdefaults:max_entries1000,max_age_secs3600,enable_statstrue. -
getdrops an expired entry;insert,remove,clear,statsandprune_expired.
(source: src/query/stmt_cache.rs, StatementCache, StatementCacheConfig, normalize_sql)
Tested in isolation by test_cache_insert_and_get, test_cache_miss, test_cache_hit_ratio, test_normalize_sql, test_cache_remove and test_cache_clear (source: src/query/stmt_cache.rs, mod tests).
Benchmarks
benches/query_bench.rs uses the criterion crate to time SqlAnalyzer on a simple and a complex SELECT (parse_simple_select, parse_complex_select), plus vector distance functions. No results are recorded in the repository for these benches (source: benches/query_bench.rs).