Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,3 +350,92 @@ If `unsafe_txdb_checkpoint` is not enabled, `build_rocksdb()` returns an explici
- Time
- TimeStamp
- Tuple

### Custom SQL Dialects

KiteSQL supports pluggable SQL dialects through the `SqlDialect` trait. This allows you to customize parsing, data type mapping, and SQL rewriting. A `Database` parses and binds statements with its current dialect. The default is `GenericSqlDialect`, the standard behaviour.

#### Using a Custom Dialect

Pass a dialect type to the builder when it is fixed at compile time:

```rust
use kite_sql::db::DataBaseBuilder;

let db = DataBaseBuilder::path("./my_db")
.dialect(MyDialect::new())
.build_rocksdb()?;
```

To pick the dialect at runtime, for example from configuration, opt in to `DynDialect`. It starts with the generic dialect registered and current, and forwards every hook to the current one:

```rust
use kite_sql::db::DataBaseBuilder;
use kite_sql::dialect::DynDialect;

let mut dialect = DynDialect::new();
dialect.register(MyDialect::new());
assert!(dialect.switch("my_dialect"));

let db = DataBaseBuilder::path("./my_db")
.dialect(dialect)
.build_rocksdb()?;
```

After opening a database with `DynDialect`, use `db.switch_dialect(name)` with mutable access to select another registered dialect for subsequent statements.

#### Implementing a Custom Dialect

Implement the `SqlDialect` trait to customize behavior:

```rust
use kite_sql::dialect::SqlDialect;
use kite_sql::errors::DatabaseError;
use kite_sql::types::LogicalType;
use sqlparser::ast::{DataType, Statement};
use sqlparser::dialect::{Dialect as SqlParserDialect, GenericDialect};

#[derive(Debug)]
struct MyDialect {
parser: GenericDialect,
}

impl SqlDialect for MyDialect {
fn name(&self) -> &str {
"my_dialect"
}

fn parser_dialect(&self) -> &dyn SqlParserDialect {
&self.parser
}

// Optional: map custom data types
fn map_data_type(
&self,
data_type: &DataType,
) -> Option<Result<LogicalType, DatabaseError>> {
match data_type {
DataType::Custom(name, _) if name.to_string() == "MY_TYPE" => {
Some(Ok(LogicalType::Integer))
}
_ => None,
}
}

// Optional: rewrite SQL statements before execution
fn rewrite(&self, stmt: &mut Statement) -> Result<(), DatabaseError> {
// Modify the statement if needed
Ok(())
}
}
```

The `SqlDialect` trait methods:

- `name()` — Returns the dialect's unique identifier
- `parser_dialect()` — Returns the sqlparser dialect for parsing SQL
- `map_data_type()` — Optional hook to map SQL data types in expressions (`CAST`, typed literals) to KiteSQL's `LogicalType`
- `map_column_type()` — Optional hook to map the data types of column definitions; defaults to `map_data_type()`
- `rewrite()` — Optional hook to transform each parsed statement before it is bound

By default, the `GenericSqlDialect` is used, which provides standard SQL behavior with no custom transformations.
2 changes: 2 additions & 0 deletions src/binder/aggregate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,7 @@ mod tests {
let table_functions = Default::default();
let transaction = tables.storage.transaction()?;
let arena = tables.table_arena.borrow();
let dialect = crate::dialect::GenericSqlDialect::new();
let args: [(usize, LogicalType); 0] = [];
let mut binder = Binder::new(
BinderContext::new(
Expand All @@ -549,6 +550,7 @@ mod tests {
&transaction,
&scala_functions,
&table_functions,
&dialect,
),
&args,
None,
Expand Down
2 changes: 2 additions & 0 deletions src/binder/create_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ mod tests {
let view_cache = crate::storage::ViewCache::default();
let scala_functions = Default::default();
let table_functions = Default::default();
let dialect = crate::dialect::GenericSqlDialect::new();

let sql = "create table t1 (id int primary key default 5 null, \
name varchar(10) null, unique (name, id))";
Expand All @@ -92,6 +93,7 @@ mod tests {
&transaction,
&scala_functions,
&table_functions,
&dialect,
),
&[],
None,
Expand Down
9 changes: 9 additions & 0 deletions src/binder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ pub struct BinderContext<'a, T: StorageTransaction> {
pub(crate) table_cache: &'a TableCache,
pub(crate) view_cache: &'a ViewCache,
pub(crate) transaction: &'a T,
pub(crate) dialect: &'a dyn crate::dialect::SqlDialect,
// Tips: retain binding order so wildcard expansion and position derivation
// follow FROM/JOIN order directly.
pub(crate) bind_table: Vec<BoundSource<'a>>,
Expand Down Expand Up @@ -333,6 +334,7 @@ impl<'a, T: StorageTransaction> BinderContext<'a, T> {
transaction: &'a T,
scala_functions: &'a ScalaFunctions,
table_functions: &'a TableFunctions,
dialect: &'a dyn crate::dialect::SqlDialect,
) -> Self {
BinderContext {
scala_functions,
Expand All @@ -341,6 +343,7 @@ impl<'a, T: StorageTransaction> BinderContext<'a, T> {
table_cache,
view_cache,
transaction,
dialect,
bind_table: Default::default(),
name_bindings: Vec::new(),
source_scope_start: 0,
Expand Down Expand Up @@ -372,6 +375,7 @@ impl<'a, T: StorageTransaction> BinderContext<'a, T> {
table_cache: self.table_cache,
view_cache: self.view_cache,
transaction: self.transaction,
dialect: self.dialect,
bind_table: self.bind_table.clone(),
name_bindings: self.name_bindings.clone(),
source_scope_start: self.bind_table.len(),
Expand Down Expand Up @@ -403,6 +407,7 @@ impl<'a, T: StorageTransaction> BinderContext<'a, T> {
self.transaction,
self.scala_functions,
self.table_functions,
self.dialect,
);
context.ctes = self.ctes.clone();
context.cte_depth = self.cte_depth;
Expand Down Expand Up @@ -831,6 +836,7 @@ pub mod test {
let table_functions = Default::default();
let transaction = self.storage.transaction()?;
let arena = self.table_arena.borrow();
let dialect = crate::dialect::GenericSqlDialect::new();
let mut binder = Binder::new(
BinderContext::new(
&arena.names,
Expand All @@ -839,6 +845,7 @@ pub mod test {
&transaction,
&scala_functions,
&table_functions,
&dialect,
),
&[],
None,
Expand Down Expand Up @@ -946,13 +953,15 @@ pub mod test {
let transaction = state.storage.transaction()?;
let scala_functions = Default::default();
let table_functions = Default::default();
let dialect = crate::dialect::GenericSqlDialect::new();
let mut context = BinderContext::new(
&arena.names,
&arena.tables,
&arena.views,
&transaction,
&scala_functions,
&table_functions,
&dialect,
);
let c1 = state.table.get_column_by_name("c1").unwrap();
let c2 = state.table.get_column_by_name("c2").unwrap();
Expand Down
56 changes: 44 additions & 12 deletions src/binder/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use crate::db::{
BindSource, ConsumeMut, Database, DatabaseIter, Executor, OwnedPtr, State, Transaction,
TransactionIter,
};
use crate::dialect::SqlDialect;
use crate::errors::{DatabaseError, SqlErrorSpan};
use crate::expression;
use crate::expression::agg::AggKind;
Expand Down Expand Up @@ -67,6 +68,26 @@ use std::slice;
/// Parsed SQL statement type used by KiteSQL SQL frontend APIs.
pub type Statement = sqlparser::ast::Statement;

pub(crate) fn convert_data_type(
data_type: &DataType,
dialect: &dyn crate::dialect::SqlDialect,
) -> Result<LogicalType, DatabaseError> {
if let Some(result) = dialect.map_data_type(data_type) {
return result;
}
LogicalType::try_from(data_type.clone())
}

pub(crate) fn convert_column_type(
data_type: &DataType,
dialect: &dyn crate::dialect::SqlDialect,
) -> Result<LogicalType, DatabaseError> {
if let Some(result) = dialect.map_column_type(data_type) {
return result;
}
LogicalType::try_from(data_type.clone())
}

pub(crate) trait AttachSpanSource {
fn sql_error_span(self) -> Option<SqlErrorSpan>;
}
Expand Down Expand Up @@ -137,15 +158,23 @@ pub fn command_type(stmt: &Statement) -> Result<CommandType, DatabaseError> {
}
}

impl<S: Storage> State<S> {
impl<S: Storage, D: SqlDialect> State<S, D> {
pub(crate) fn prepare_all<T: AsRef<str>>(
&self,
sql: T,
) -> Result<Vec<Statement>, DatabaseError> {
let stmts = parse_sql_with_recursion_limit(sql, self.parser_recursion_limit())?;
let dialect = self.dialect();
let mut stmts = parse_sql_with_recursion_limit(
dialect.parser_dialect(),
sql,
self.parser_recursion_limit(),
)?;
if stmts.is_empty() {
return Err(DatabaseError::EmptyStatement);
}
for stmt in stmts.iter_mut() {
dialect.rewrite(stmt)?;
}
Ok(stmts)
}

Expand Down Expand Up @@ -173,7 +202,7 @@ fn statement_mutates_catalog_or_statistics(statement: &Statement) -> Result<bool
}

#[maybe_async]
impl<S: Storage> Database<S> {
impl<S: Storage, D: SqlDialect> Database<S, D> {
/// Parses SQL statements using this database's configured parser recursion limit.
pub fn prepare_all<T: AsRef<str>>(&self, sql: T) -> Result<Vec<Statement>, DatabaseError> {
self.state.prepare_all(sql)
Expand Down Expand Up @@ -320,7 +349,7 @@ impl<S: Storage> Database<S> {
}

#[maybe_async]
impl<'txn, S: Storage> Transaction<'txn, S> {
impl<'txn, S: Storage, D: SqlDialect> Transaction<'txn, S, D> {
/// Runs SQL inside the current transaction and returns the final result iterator.
pub async fn run<'a, T: AsRef<str>>(
&'a mut self,
Expand Down Expand Up @@ -579,7 +608,7 @@ where
));
}
(
LogicalType::try_from(data_type)?,
convert_column_type(&data_type, self.binder.context.dialect)?,
DefaultChange::NoChange,
NotNullChange::NoChange,
)
Expand Down Expand Up @@ -645,7 +674,7 @@ where
})?;
}
let old_column_name = old_column_name.into_owned();
let data_type = LogicalType::try_from(data_type)?;
let data_type = convert_column_type(&data_type, self.binder.context.dialect)?;
let (default_change, not_null_change) =
self.bind_change_column_options(options, &data_type)?;

Expand Down Expand Up @@ -690,7 +719,7 @@ where
"illegal column naming".to_string(),
));
}
let data_type = LogicalType::try_from(data_type)?;
let data_type = convert_column_type(&data_type, self.binder.context.dialect)?;
let (default_change, not_null_change) =
self.bind_change_column_options(options, &data_type)?;

Expand Down Expand Up @@ -823,7 +852,7 @@ where
) -> Result<ColumnCatalog, DatabaseError> {
let column_name = lower_ident(&column_def.name).into_owned();
let mut column_desc = ColumnDesc::new(
LogicalType::try_from(column_def.data_type)?,
convert_column_type(&column_def.data_type, self.binder.context.dialect)?,
None,
false,
None,
Expand Down Expand Up @@ -2386,13 +2415,14 @@ impl<'a, 'parent, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>>
}
Expr::Cast {
expr, data_type, ..
} => self
.bind_expr(expr, arena)?
.type_cast(Cow::Owned(LogicalType::try_from(data_type.clone())?), arena),
} => self.bind_expr(expr, arena)?.type_cast(
Cow::Owned(convert_data_type(data_type, self.context.dialect)?),
arena,
),
Expr::TypedString(TypedString {
data_type, value, ..
}) => {
let logical_type = LogicalType::try_from(data_type.clone())?;
let logical_type = convert_data_type(data_type, self.context.dialect)?;
let raw = value.clone().into_string().ok_or_else(|| {
DatabaseError::InvalidValue("typed string literal must be a string".to_string())
})?;
Expand Down Expand Up @@ -3625,6 +3655,7 @@ mod tests {
let table_functions = Default::default();
let transaction = tables.storage.transaction()?;
let arena = tables.table_arena.borrow();
let dialect = crate::dialect::GenericSqlDialect::new();
let mut binder = Binder::new(
BinderContext::new(
&arena.names,
Expand All @@ -3633,6 +3664,7 @@ mod tests {
&transaction,
&scala_functions,
&table_functions,
&dialect,
),
&[],
None,
Expand Down
Loading
Loading