Skip to content

feat: KiteSQL AST and SQLite dialect - #410

Merged
KKould merged 3 commits into
mainfrom
feat/sqlite-dialect
Nov 22, 2026
Merged

KKould merged 3 commits into
mainfrom
feat/sqlite-dialect

Conversation

@KKould

@KKould KKould commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Summary

SqlDialect

A dialect now owns parsing. It turns SQL text into KiteSQL statements with any parser it likes:

pub trait SqlDialect: Debug + Send + Sync + 'static {
    /// Unique name; `DynDialect` switches by it.
    fn name(&self) -> &str;

    /// SQL text -> KiteSQL statements. Reject unsupported syntax here; rewriting is allowed.
    fn parse(&self, sql: &str) -> Result<Vec<kite_sql::ast::Statement>, DatabaseError>;

    /// Binding hooks from #406; the defaults keep the built-in behavior.
    fn comparison_type(&self, left: &LogicalType, right: &LogicalType) -> Option<LogicalType> { None }
    fn boolean_text(&self, value: bool) -> Option<&'static str> { None }
}

Breaking changes compared with main:

  • parser_dialect, rewrite, map_data_type and map_column_type are removed and replaced by parse.
    • A sqlparser-based dialect calls kite_sql::parser::generic::SqlParser::new(&MyParserDialect).parse(sql), then rewrites the returned ast::Statements.
    • Custom type names go through DataTypeMapper.
  • DatabaseError::ParserSql now holds a String, so it no longer depends on sqlparser types.

Built-in dialects

Dialect Name const Feature Parser
GenericSqlDialect (default) DIALECT_GENERIC = "generic" parser sqlparser GenericDialect
SqliteDialect DIALECT_SQLITE = "sqlite" sqlite-parser sqlite3-parser
  • GenericSqlDialect::new().with_recursion_limit(n) limits how deeply nested the SQL may be. DataBaseBuilder::parser_recursion_limit(n) is shorthand for it on the default builder.
  • SqliteDialect covers SELECT (CTE, set operations, window functions, VALUES), INSERT (INSERT OR REPLACE maps to overwrite), UPDATE, DELETE, CREATE/DROP of tables, indexes and views, ALTER TABLE column operations, ANALYZE and EXPLAIN.
    • It also accepts SQLite spellings: substr/trim/ltrim/rtrim, ?N parameters, [..] quoting and postfix NOTNULL.
    • sqlite3-parser has no source positions, so its errors carry no span.

Dynamic dialect example

DynDialect holds several dialects and forwards every hook to the current one. It starts with GenericSqlDialect registered and current. All dialects share one catalog, so a table created under one dialect is visible under the others.

use kite_sql::db::DataBaseBuilder;
use kite_sql::dialect::{DynDialect, SqliteDialect, DIALECT_GENERIC, DIALECT_SQLITE};

let mut dialect = DynDialect::new(); // generic, current
dialect.register(SqliteDialect);     // registered under "sqlite"

let mut db = DataBaseBuilder::path("./data")
    .dialect(dialect)
    .build()?;

// Generic syntax.
db.run("create table t (id int primary key, v varchar)")?.done()?;
db.run("insert into t values (1, 'abc')")?.done()?;
db.run("select id from t where substring(v from 2 for 1) = 'b'")?.done()?;

// Switch to SQLite syntax for the following statements, on the same data.
assert!(db.switch_dialect(DIALECT_SQLITE));
db.run("insert or replace into t values (1, 'xyz')")?.done()?;
db.run("select [id] from t where substr(v, 2, 1) = 'y' and v notnull")?.done()?;
assert!(db.run("select substring(v from 2 for 1) from t").is_err()); // not SQLite grammar

// Back to generic. An unknown name returns false and keeps the current dialect.
assert!(db.switch_dialect(DIALECT_GENERIC));
assert!(!db.switch_dialect("mysql"));

You can also pick the dialect before building, for example from configuration, with dialect.switch(name). Use .dialect(SqliteDialect) directly when the dialect is fixed at compile time.

Testing

  • make test (631 passed), make test-async (599 passed), make clippy, make fmt
  • cargo check --no-default-features --features sqlite-parser,rocksdb, i.e. the SQLite frontend without sqlparser
  • New tests in src/dialect/mod.rs:
    • sqlite_dialect_matches_generic runs about 20 statements in both dialects and checks that the results match, and that unsupported SQLite syntax is rejected.
    • database_switches_between_generic_and_sqlite switches dialects on one database.

@KKould KKould self-assigned this Nov 22, 2026
@KKould KKould added the enhancement New feature or request label Nov 22, 2026
@KKould

KKould commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

@alexskinner what do you think of this PR in terms of how it reconstructs dialects?

@codecov

codecov Bot commented Nov 22, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.33333% with 119 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.08%. Comparing base (2c5fb1c) to head (d046cf1).

Files with missing lines Patch % Lines
src/parser/generic/statement.rs 88.69% 39 Missing ⚠️
src/parser/generic/expr.rs 85.77% 32 Missing ⚠️
src/ast/expr.rs 26.92% 19 Missing ⚠️
src/parser/generic/query.rs 90.00% 17 Missing ⚠️
src/ast/mod.rs 84.28% 11 Missing ⚠️
src/dialect/mod.rs 97.61% 1 Missing ⚠️

❌ Your patch check has failed because the patch coverage (88.33%) is below the target coverage (90.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #410      +/-   ##
==========================================
+ Coverage   92.99%   93.08%   +0.08%     
==========================================
  Files         275      282       +7     
  Lines       39538    39885     +347     
==========================================
+ Hits        36768    37125     +357     
+ Misses       2770     2760      -10     
Flag Coverage Δ
rust 93.08% <88.33%> (+0.08%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/ast/statement.rs 100.00% <100.00%> (ø)
src/binder/create_table.rs 78.12% <ø> (ø)
src/binder/mod.rs 95.18% <ø> (ø)
src/binder/parser.rs 93.63% <ø> (+3.30%) ⬆️
src/db.rs 94.10% <100.00%> (-0.09%) ⬇️
src/db/program.rs 82.60% <ø> (ø)
src/errors.rs 94.22% <100.00%> (+0.04%) ⬆️
src/optimizer/heuristic/optimizer.rs 98.70% <ø> (ø)
src/parser/generic/mod.rs 100.00% <100.00%> (ø)
src/parser/generic/types.rs 100.00% <100.00%> (ø)
... and 6 more
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@KKould
KKould merged commit 34a2123 into main Nov 22, 2026
14 checks passed
Add `kite_sql::ast`, the syntax tree the binder binds. A `SqlDialect`
now parses SQL text into it with `parse`, so a dialect may use any
parser; `comparison_type` and `boolean_text` stay as binding hooks.

The sqlparser frontend moves to `parser::generic`: `SqlParser` parses
with a sqlparser dialect and converts the statements, rejecting syntax
KiteSQL does not support and resolving type names through
`DataTypeMapper`. The binder no longer depends on sqlparser, so the
crate builds without the `parser` feature.
SqliteDialect parses SQL with SQLite's own grammar (sqlite3-parser) and
lowers it into KiteSQL's AST, behind the sqlite-parser feature. SQLite
syntax KiteSQL does not support is rejected.
@alexskinner

Copy link
Copy Markdown
Contributor

Sorry for the slow reply, I missed this before it merged. I like the direction a lot.

One small thing: #408 and #409 each add a flag to the parser's Lower struct, so whichever lands second will need a trivial rebase. I'll handle it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants