diff --git a/docs/features.md b/docs/features.md index 54765a05..68030cb7 100644 --- a/docs/features.md +++ b/docs/features.md @@ -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> { + 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. diff --git a/src/binder/aggregate.rs b/src/binder/aggregate.rs index aac5a6e2..dcba6a36 100644 --- a/src/binder/aggregate.rs +++ b/src/binder/aggregate.rs @@ -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( @@ -549,6 +550,7 @@ mod tests { &transaction, &scala_functions, &table_functions, + &dialect, ), &args, None, diff --git a/src/binder/create_table.rs b/src/binder/create_table.rs index d7faced4..63c5c629 100644 --- a/src/binder/create_table.rs +++ b/src/binder/create_table.rs @@ -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))"; @@ -92,6 +93,7 @@ mod tests { &transaction, &scala_functions, &table_functions, + &dialect, ), &[], None, diff --git a/src/binder/mod.rs b/src/binder/mod.rs index 5074663f..9b4375cc 100644 --- a/src/binder/mod.rs +++ b/src/binder/mod.rs @@ -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>, @@ -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, @@ -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, @@ -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(), @@ -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; @@ -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, @@ -839,6 +845,7 @@ pub mod test { &transaction, &scala_functions, &table_functions, + &dialect, ), &[], None, @@ -946,6 +953,7 @@ 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, @@ -953,6 +961,7 @@ pub mod test { &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(); diff --git a/src/binder/parser.rs b/src/binder/parser.rs index 14e38f78..643e5628 100644 --- a/src/binder/parser.rs +++ b/src/binder/parser.rs @@ -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; @@ -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 { + 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 { + 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; } @@ -137,15 +158,23 @@ pub fn command_type(stmt: &Statement) -> Result { } } -impl State { +impl State { pub(crate) fn prepare_all>( &self, sql: T, ) -> Result, 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) } @@ -173,7 +202,7 @@ fn statement_mutates_catalog_or_statistics(statement: &Statement) -> Result Database { +impl Database { /// Parses SQL statements using this database's configured parser recursion limit. pub fn prepare_all>(&self, sql: T) -> Result, DatabaseError> { self.state.prepare_all(sql) @@ -320,7 +349,7 @@ impl Database { } #[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>( &'a mut self, @@ -579,7 +608,7 @@ where )); } ( - LogicalType::try_from(data_type)?, + convert_column_type(&data_type, self.binder.context.dialect)?, DefaultChange::NoChange, NotNullChange::NoChange, ) @@ -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)?; @@ -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)?; @@ -823,7 +852,7 @@ where ) -> Result { 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, @@ -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()) })?; @@ -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, @@ -3633,6 +3664,7 @@ mod tests { &transaction, &scala_functions, &table_functions, + &dialect, ), &[], None, diff --git a/src/db.rs b/src/db.rs index c1afa659..6868b00b 100644 --- a/src/db.rs +++ b/src/db.rs @@ -16,6 +16,7 @@ mod program; #[cfg(feature = "parser")] pub use crate::binder::Statement; use crate::binder::{Binder, BinderContext}; +use crate::dialect::{DynDialect, GenericSqlDialect, SqlDialect}; use crate::errors::DatabaseError; pub use crate::execution::Executor; use crate::execution::{DDLApply, ExecArena, ExecBuffer, TxnPtr}; @@ -122,13 +123,14 @@ pub(crate) trait BindSource { type Transaction: StorageTransaction; type Storage: Storage; + type Dialect: SqlDialect; /// `read_only` lets a fresh transaction use the storage's read path; executors /// that already hold a transaction ignore it. async fn execute(self, read_only: bool, build: F) -> Result where F: for<'s> FnOnce( - &'s State, + &'s State, &Self::Transaction, ) -> Result<(Executor<'s>, PlanArena<'s>), DatabaseError> + MaybeSend; @@ -147,7 +149,7 @@ pub(crate) trait BindSource { /// /// The builder wires together storage, built-in functions and optional runtime /// features before the database is opened. -pub struct DataBaseBuilder { +pub struct DataBaseBuilder { #[cfg(all( not(target_arch = "wasm32"), any(feature = "rocksdb", feature = "lmdb") @@ -158,6 +160,7 @@ pub struct DataBaseBuilder { statistics_relative_error: Option, parser_recursion_limit: Option, transaction_isolation: Option, + dialect: D, #[cfg(all(not(target_arch = "wasm32"), feature = "rocksdb"))] storage_config: StorageConfig, #[cfg(all(not(target_arch = "wasm32"), feature = "lmdb"))] @@ -192,13 +195,16 @@ impl DataBaseBuilder { statistics_relative_error: None, parser_recursion_limit: None, transaction_isolation: None, + dialect: GenericSqlDialect::new(), #[cfg(all(not(target_arch = "wasm32"), feature = "rocksdb"))] storage_config: Default::default(), #[cfg(all(not(target_arch = "wasm32"), feature = "lmdb"))] lmdb_config: Default::default(), } } +} +impl DataBaseBuilder { /// Sets the maximum histogram bucket count used by `ANALYZE` (default: 10). /// The actual count is limited by the number of non-NULL samples. pub fn histogram_buckets(mut self, buckets: usize) -> Self { @@ -240,6 +246,27 @@ impl DataBaseBuilder { self } + /// Sets the SQL dialect used to parse and bind statements, [`GenericSqlDialect`] by default. + pub fn dialect(self, dialect: T) -> DataBaseBuilder { + DataBaseBuilder { + #[cfg(all( + not(target_arch = "wasm32"), + any(feature = "rocksdb", feature = "lmdb") + ))] + path: self.path, + histogram_buckets: self.histogram_buckets, + hll_precision: self.hll_precision, + statistics_relative_error: self.statistics_relative_error, + parser_recursion_limit: self.parser_recursion_limit, + transaction_isolation: self.transaction_isolation, + dialect, + #[cfg(all(not(target_arch = "wasm32"), feature = "rocksdb"))] + storage_config: self.storage_config, + #[cfg(all(not(target_arch = "wasm32"), feature = "lmdb"))] + lmdb_config: self.lmdb_config, + } + } + /// Enables or disables RocksDB statistics collection. #[cfg(all( not(target_arch = "wasm32"), @@ -313,7 +340,10 @@ impl DataBaseBuilder { } /// Builds a database using a custom storage implementation. - pub fn build_with_storage(self, storage: T) -> Result, DatabaseError> { + pub fn build_with_storage( + self, + storage: T, + ) -> Result, DatabaseError> { Self::_build::( storage, self.histogram_buckets, @@ -321,12 +351,13 @@ impl DataBaseBuilder { self.statistics_relative_error, self.parser_recursion_limit, self.transaction_isolation, + self.dialect, ) } /// Builds a database for the current target platform. #[cfg(all(target_arch = "wasm32", feature = "wasm"))] - pub fn build(self) -> Result, DatabaseError> { + pub fn build(self) -> Result, DatabaseError> { let storage = MemoryStorage::new(); Self::_build::( @@ -336,12 +367,13 @@ impl DataBaseBuilder { self.statistics_relative_error, self.parser_recursion_limit, self.transaction_isolation, + self.dialect, ) } /// Builds a RocksDB-backed database. #[cfg(all(not(target_arch = "wasm32"), feature = "rocksdb"))] - pub fn build_rocksdb(self) -> Result, DatabaseError> { + pub fn build_rocksdb(self) -> Result, DatabaseError> { let storage = RocksStorage::with_config(self.path, self.storage_config)?; Self::_build::( @@ -351,6 +383,7 @@ impl DataBaseBuilder { self.statistics_relative_error, self.parser_recursion_limit, self.transaction_isolation, + self.dialect, ) } @@ -358,7 +391,7 @@ impl DataBaseBuilder { /// /// This is convenient for tests, examples and temporary workloads. #[cfg(not(feature = "async"))] - pub fn build_in_memory(self) -> Result, DatabaseError> { + pub fn build_in_memory(self) -> Result, DatabaseError> { let storage = MemoryStorage::new(); Self::_build::( @@ -368,12 +401,13 @@ impl DataBaseBuilder { self.statistics_relative_error, self.parser_recursion_limit, self.transaction_isolation, + self.dialect, ) } /// Builds a LMDB-backed database. #[cfg(all(not(target_arch = "wasm32"), feature = "lmdb"))] - pub fn build_lmdb(self) -> Result, DatabaseError> { + pub fn build_lmdb(self) -> Result, DatabaseError> { let storage = LmdbStorage::with_config(self.path, self.lmdb_config)?; Self::_build::( @@ -383,13 +417,14 @@ impl DataBaseBuilder { self.statistics_relative_error, self.parser_recursion_limit, self.transaction_isolation, + self.dialect, ) } #[cfg(all(not(target_arch = "wasm32"), feature = "rocksdb"))] /// Builds a RocksDB-backed database that uses optimistic transactions. #[cfg(all(not(target_arch = "wasm32"), feature = "rocksdb"))] - pub fn build_optimistic(self) -> Result, DatabaseError> { + pub fn build_optimistic(self) -> Result, DatabaseError> { let storage = OptimisticRocksStorage::with_config(self.path, self.storage_config)?; Self::_build::( @@ -399,6 +434,7 @@ impl DataBaseBuilder { self.statistics_relative_error, self.parser_recursion_limit, self.transaction_isolation, + self.dialect, ) } @@ -409,7 +445,8 @@ impl DataBaseBuilder { statistics_relative_error: Option, parser_recursion_limit: Option, transaction_isolation: Option, - ) -> Result, DatabaseError> { + dialect: D, + ) -> Result, DatabaseError> { if matches!(histogram_buckets, Some(0)) { return Err(DatabaseError::InvalidValue( "histogram buckets must be >= 1".to_string(), @@ -453,6 +490,7 @@ impl DataBaseBuilder { hll_precision, statistics_relative_error: statistics_relative_error.map(OrderedFloat), parser_recursion_limit, + dialect, _p: Default::default(), }; @@ -697,7 +735,7 @@ where Ok(arena) } -pub(crate) struct State { +pub(crate) struct State { scala_functions: ScalaFunctions, table_functions: TableFunctions, meta_cache: StatisticsMetaCache, @@ -708,15 +746,20 @@ pub(crate) struct State { statistics_relative_error: Option>, #[cfg_attr(not(feature = "parser"), allow(dead_code))] parser_recursion_limit: Option, + dialect: D, _p: PhantomData, } -impl State { +impl State { #[cfg(feature = "parser")] pub(crate) fn parser_recursion_limit(&self) -> Option { self.parser_recursion_limit } + pub(crate) fn dialect(&self) -> &D { + &self.dialect + } + fn scala_functions(&self) -> &ScalaFunctions { &self.scala_functions } @@ -814,6 +857,7 @@ impl State { transaction, self.scala_functions(), self.table_functions(), + self.dialect(), ), ¶ms, None, @@ -843,7 +887,7 @@ impl State { } #[maybe_async] -impl State { +impl State { pub(crate) async fn execute<'a, 'p, 'txn, A: MetaArena + 'p>( &'p self, transaction: &'a mut S::TransactionType<'txn>, @@ -888,6 +932,7 @@ impl State { histogram_buckets, hll_precision, statistics_relative_error, + dialect, .. } = self; let arena = table_arena.borrow(); @@ -901,6 +946,7 @@ impl State { transaction, scala_functions, table_functions, + dialect, ), ¶ms, None, @@ -937,16 +983,24 @@ impl State { } /// Main database handle for executing SQL and creating transactions. -pub struct Database { +pub struct Database { pub(crate) storage: S, pub(crate) transaction_isolation: TransactionIsolationLevel, - pub(crate) state: State, + pub(crate) state: State, +} + +impl Database { + /// Selects a registered dialect for subsequent SQL parsing and binding. + /// Returns `false` and leaves the dialect unchanged if `name` is not registered. + pub fn switch_dialect(&mut self, name: &str) -> bool { + self.state.dialect.switch(name) + } } impl DDLApply { - fn apply_to( + fn apply_to( self, - state: &mut State, + state: &mut State, plan_arena: &mut PlanArena, ) -> Result { let mut catalog_changed = false; @@ -1005,7 +1059,7 @@ impl DDLApply { } #[maybe_async] -impl Database { +impl Database { pub(crate) async fn execute_mut( &mut self, context: &str, @@ -1198,7 +1252,7 @@ impl Database { /// transactional context until [`Transaction::commit`] is called. /// A `read_only` transaction rejects statements that write; on LMDB it runs /// alongside the single writer instead of waiting for it. - pub fn new_transaction(&self, read_only: bool) -> Result, DatabaseError> { + pub fn new_transaction(&self, read_only: bool) -> Result, DatabaseError> { let transaction = self .storage .transaction_with_isolation(self.transaction_isolation, read_only)?; @@ -1250,16 +1304,17 @@ impl ConsumeMut for () { } #[maybe_async] -impl<'a, S: Storage> BindSource for &'a Database { +impl<'a, S: Storage, D: SqlDialect> BindSource for &'a Database { type Iter = DatabaseIter<'a, S>; type Transaction = S::TransactionType<'a>; type Storage = S; + type Dialect = D; async fn execute(self, read_only: bool, build: F) -> Result where F: for<'s> FnOnce( - &'s State, + &'s State, &Self::Transaction, ) -> Result<(Executor<'s>, PlanArena<'s>), DatabaseError> + MaybeSend, @@ -1295,9 +1350,10 @@ impl<'a, S: Storage> BindSource for &'a Database { } } -impl Database +impl Database where S: CheckpointableStorage, + D: SqlDialect, { /// Creates an online consistent checkpoint in `path`. /// @@ -1694,14 +1750,14 @@ impl ResultIter for DatabaseIter<'_, S> { } /// Explicit transaction handle created by [`Database::new_transaction`]. -pub struct Transaction<'a, S: Storage + 'a> { +pub struct Transaction<'a, S: Storage + 'a, D: SqlDialect = GenericSqlDialect> { pub(crate) inner: S::TransactionType<'a>, - pub(crate) state: &'a State, + pub(crate) state: &'a State, read_only: bool, } #[maybe_async] -impl<'txn, S: Storage> Transaction<'txn, S> { +impl<'txn, S: Storage, D: SqlDialect> Transaction<'txn, S, D> { /// Commits the current transaction. pub async fn commit(self) -> Result<(), DatabaseError> { self.inner.commit().await?; @@ -1711,16 +1767,17 @@ impl<'txn, S: Storage> Transaction<'txn, S> { } #[maybe_async] -impl<'a, 'txn, S: Storage> BindSource for &'a mut Transaction<'txn, S> { +impl<'a, 'txn, S: Storage, D: SqlDialect> BindSource for &'a mut Transaction<'txn, S, D> { type Iter = TransactionIter<'a, 'a, S::TransactionType<'txn>>; type Transaction = S::TransactionType<'txn>; type Storage = S; + type Dialect = D; async fn execute(self, _read_only: bool, build: F) -> Result where F: for<'s> FnOnce( - &'s State, + &'s State, &Self::Transaction, ) -> Result<(Executor<'s>, PlanArena<'s>), DatabaseError> + MaybeSend, @@ -2419,6 +2476,7 @@ pub(crate) mod test { &transaction, kite_sql.state.scala_functions(), kite_sql.state.table_functions(), + kite_sql.state.dialect(), ), &[], None, @@ -2509,6 +2567,7 @@ pub(crate) mod test { &transaction, kite_sql.state.scala_functions(), kite_sql.state.table_functions(), + kite_sql.state.dialect(), ), &[], None, diff --git a/src/db/program.rs b/src/db/program.rs index 9b7d09e5..f0d4275f 100644 --- a/src/db/program.rs +++ b/src/db/program.rs @@ -69,9 +69,9 @@ pub struct Program<'p> { impl<'p> Program<'p> { /// Runs the program with `params` in `transaction`. The returned iterator borrows the /// program until the execution ends. - pub async fn execute<'a, 'txn, 'v, S: Storage>( + pub async fn execute<'a, 'txn, 'v, S: Storage, D: SqlDialect>( &'a mut self, - transaction: &'a mut Transaction<'txn, S>, + transaction: &'a mut Transaction<'txn, S, D>, params: impl AsRef<[(usize, Param<'v>)]>, ) -> Result>, DatabaseError> where @@ -124,7 +124,7 @@ impl<'p> Program<'p> { } } -impl Database { +impl Database { /// Prepares SQL with explicit positional parameter types into a program. /// Parameter values are supplied separately for each execution. #[cfg(feature = "parser")] @@ -141,7 +141,7 @@ impl Database { } } -impl<'db, S: Storage> Transaction<'db, S> { +impl<'db, S: Storage, D: SqlDialect> Transaction<'db, S, D> { #[cfg(feature = "parser")] pub fn program_sql( &self, @@ -153,7 +153,7 @@ impl<'db, S: Storage> Transaction<'db, S> { } } -impl State { +impl State { #[cfg(feature = "parser")] pub(crate) fn prepare_plan<'a, 'txn>( &'a self, diff --git a/src/dialect/mod.rs b/src/dialect/mod.rs new file mode 100644 index 00000000..942af9b0 --- /dev/null +++ b/src/dialect/mod.rs @@ -0,0 +1,308 @@ +// Copyright 2024 KipData/KiteSQL +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::errors::DatabaseError; +use sqlparser::ast::Statement; +use sqlparser::dialect::{Dialect as SqlParserDialect, GenericDialect}; +use std::fmt::Debug; + +pub const DIALECT_GENERIC: &str = "generic"; + +/// SQL dialect trait for customizing parsing, type mapping, and statement rewriting. +/// +/// Implement this trait to provide dialect-specific behavior. All methods have +/// default implementations that preserve standard SQL behavior. +pub trait SqlDialect: Debug + Send + Sync + 'static { + /// Returns the unique name of this dialect. + fn name(&self) -> &str; + + /// Returns the sqlparser dialect used for parsing SQL statements. + fn parser_dialect(&self) -> &dyn SqlParserDialect; + + /// Rewrites a parsed SQL statement before it is bound. + /// + /// Called once for every statement parsed with this dialect. The default + /// implementation performs no rewriting. + fn rewrite(&self, _stmt: &mut Statement) -> Result<(), DatabaseError> { + Ok(()) + } + + /// Maps a SQL data type to KiteSQL's internal logical type. + /// + /// Used for data types inside expressions, such as `CAST(.. AS type)` and typed + /// string literals. Return `Some(Ok(type))` to override the default type mapping, `Some(Err(...))` + /// to reject the type, or `None` to use the default mapping. + /// + /// The default implementation returns `None` for all types. + fn map_data_type( + &self, + _data_type: &sqlparser::ast::DataType, + ) -> Option> { + None + } + + /// Maps the data type of a column definition to KiteSQL's internal logical type. + /// + /// Used by `CREATE TABLE`, `ALTER TABLE .. ADD COLUMN` and column type changes; the + /// return value follows the same convention as [`map_data_type`](Self::map_data_type). + /// + /// The default implementation delegates to [`map_data_type`](Self::map_data_type). + fn map_column_type( + &self, + data_type: &sqlparser::ast::DataType, + ) -> Option> { + self.map_data_type(data_type) + } +} + +/// Standard SQL behavior with no customizations; the default dialect. +#[derive(Debug)] +pub struct GenericSqlDialect { + parser: GenericDialect, +} + +impl GenericSqlDialect { + pub fn new() -> Self { + Self { + parser: GenericDialect {}, + } + } +} + +impl Default for GenericSqlDialect { + fn default() -> Self { + Self::new() + } +} + +impl SqlDialect for GenericSqlDialect { + fn name(&self) -> &str { + DIALECT_GENERIC + } + + fn parser_dialect(&self) -> &dyn SqlParserDialect { + &self.parser + } +} + +/// A dialect chosen at runtime from a set of registered dialects. +/// +/// Pass it to [`DataBaseBuilder::dialect`](crate::db::DataBaseBuilder::dialect) when the dialect +/// is only known at runtime; the default stays [`GenericSqlDialect`]. It starts with +/// [`GenericSqlDialect`] registered and current; [`register`](Self::register) adds dialects and +/// [`switch`](Self::switch) changes the current one. Every [`SqlDialect`] hook forwards to +/// [`current`](Self::current). +#[derive(Debug)] +pub struct DynDialect { + dialects: Vec>, + current: usize, +} + +impl DynDialect { + /// Creates a set containing only the generic dialect, which is current. + pub fn new() -> Self { + Self { + dialects: vec![Box::new(GenericSqlDialect::new())], + current: 0, + } + } + + /// Registers a dialect under its [`SqlDialect::name`], replacing any with the same name. + pub fn register(&mut self, dialect: D) { + let dialect = Box::new(dialect); + match self + .dialects + .iter() + .position(|registered| registered.name() == dialect.name()) + { + Some(index) => self.dialects[index] = dialect, + None => self.dialects.push(dialect), + } + } + + /// Makes the dialect registered as `name` current; returns `false` if there is none. + pub fn switch(&mut self, name: &str) -> bool { + match self + .dialects + .iter() + .position(|dialect| dialect.name() == name) + { + Some(index) => { + self.current = index; + true + } + None => false, + } + } + + /// Returns the current dialect. + pub fn current(&self) -> &dyn SqlDialect { + self.dialects[self.current].as_ref() + } +} + +impl Default for DynDialect { + fn default() -> Self { + Self::new() + } +} + +impl SqlDialect for DynDialect { + fn name(&self) -> &str { + self.current().name() + } + + fn parser_dialect(&self) -> &dyn SqlParserDialect { + self.current().parser_dialect() + } + + fn rewrite(&self, stmt: &mut Statement) -> Result<(), DatabaseError> { + self.current().rewrite(stmt) + } + + fn map_data_type( + &self, + data_type: &sqlparser::ast::DataType, + ) -> Option> { + self.current().map_data_type(data_type) + } + + fn map_column_type( + &self, + data_type: &sqlparser::ast::DataType, + ) -> Option> { + self.current().map_column_type(data_type) + } +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +#[maybe_async] +mod tests { + use super::*; + use crate::db::{DataBaseBuilder, Database}; + use crate::storage::Storage; + use crate::types::value::DataValue; + use crate::types::LogicalType; + use sqlparser::ast::{DataType, Expr, LimitClause, Value}; + + #[derive(Debug, Default)] + struct TestDialect { + parser: GenericDialect, + } + + impl SqlDialect for TestDialect { + fn name(&self) -> &str { + "test" + } + + fn parser_dialect(&self) -> &dyn SqlParserDialect { + &self.parser + } + + fn map_data_type( + &self, + data_type: &DataType, + ) -> Option> { + matches!(data_type, DataType::Custom(name, _) if name.to_string() == "test_int") + .then_some(Ok(LogicalType::Integer)) + } + + fn rewrite(&self, stmt: &mut Statement) -> Result<(), DatabaseError> { + if let Statement::Query(query) = stmt { + if let Some(LimitClause::LimitOffset { + limit: Some(limit), .. + }) = &mut query.limit_clause + { + *limit = Expr::Value(Value::Number("1".to_string(), false).into()); + } + } + Ok(()) + } + } + + pub(super) async fn query( + db: &Database, + sql: &str, + ) -> Result>, DatabaseError> { + let mut iter = db.run(sql).await?; + let mut rows = Vec::new(); + while let Some(row) = iter.next_tuple(|_, row| row.take_values()).await? { + rows.push(row); + } + iter.done().await?; + Ok(rows) + } + + #[test] + async fn custom_dialect_maps_types_and_rewrites() -> Result<(), DatabaseError> { + let mut generic = DataBaseBuilder::path(".").build_in_memory().await?; + assert!(generic + .ddl("create table t1 (id test_int primary key)") + .await + .is_err()); + + let mut db = DataBaseBuilder::path(".") + .dialect(TestDialect::default()) + .build_in_memory() + .await?; + db.ddl("create table t1 (id test_int primary key)").await?; + db.run("insert into t1 values (1), (2)") + .await? + .done() + .await?; + let iter = db.run("select id from t1").await?; + iter.schema(|schema| assert_eq!(schema.get(0).unwrap().datatype(), &LogicalType::Integer)); + iter.done().await?; + assert_eq!(query(&db, "select id from t1 limit 10").await?.len(), 1); + + Ok(()) + } + + #[test] + async fn dyn_dialect_switches_at_runtime() -> Result<(), DatabaseError> { + let mut dialect = DynDialect::new(); + assert_eq!(dialect.name(), DIALECT_GENERIC); + assert!(!dialect.switch("test")); + dialect.register(TestDialect::default()); + assert!(dialect.switch("test")); + + let db = DataBaseBuilder::path(".") + .dialect(dialect) + .build_in_memory() + .await?; + assert_eq!( + query(&db, "select cast(7 as test_int) limit 10").await?, + vec![vec![DataValue::Int32(7)]] + ); + + Ok(()) + } + + #[test] + async fn database_switches_dialect_after_build() -> Result<(), DatabaseError> { + let mut dialect = DynDialect::new(); + dialect.register(TestDialect::default()); + let mut db = DataBaseBuilder::path(".") + .dialect(dialect) + .build_in_memory() + .await?; + + let sql = "select cast(7 as test_int)"; + assert!(query(&db, sql).await.is_err()); + assert!(db.switch_dialect("test")); + assert_eq!(query(&db, sql).await?, vec![vec![DataValue::Int32(7)]]); + + Ok(()) + } +} diff --git a/src/lib.rs b/src/lib.rs index 0a440516..a687f01d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -120,6 +120,7 @@ compile_error!("feature `spill` is not supported on wasm32 targets"); pub mod binder; pub mod catalog; pub mod db; +pub mod dialect; pub mod errors; pub mod execution; pub mod expression; diff --git a/src/optimizer/heuristic/optimizer.rs b/src/optimizer/heuristic/optimizer.rs index 9feb2a8b..828b5c38 100644 --- a/src/optimizer/heuristic/optimizer.rs +++ b/src/optimizer/heuristic/optimizer.rs @@ -868,6 +868,7 @@ mod tests { &transaction, &scala_functions, &table_functions, + database.state.dialect(), ), &[], None, diff --git a/src/orm/ddl.rs b/src/orm/ddl.rs index 3497cb89..63a1d7a6 100644 --- a/src/orm/ddl.rs +++ b/src/orm/ddl.rs @@ -7,7 +7,7 @@ enum OrmDefaultChange { } #[maybe_async] -impl Database { +impl Database { fn table_catalog(&self, table_name: &str) -> Result, DatabaseError> { let transaction = self.storage.transaction()?; transaction @@ -39,7 +39,7 @@ impl Database { /// database.create_table::().unwrap(); /// ``` pub async fn create_table(&mut self) -> Result<(), DatabaseError> { - execute_create_table::<_, M>(self, false).await?; + execute_create_table::<_, _, M>(self, false).await?; for index in M::indexes() { execute_create_index(self, M::table_name(), index, false).await?; @@ -54,7 +54,7 @@ impl Database { /// schema initialization should stay idempotent. Secondary indexes declared /// with `#[model(index)]` are created with `IF NOT EXISTS` as well. pub async fn create_table_if_not_exists(&mut self) -> Result<(), DatabaseError> { - execute_create_table::<_, M>(self, true).await?; + execute_create_table::<_, _, M>(self, true).await?; for index in M::indexes() { execute_create_index(self, M::table_name(), index, true).await?; @@ -434,8 +434,8 @@ impl Database { } #[maybe_async] -async fn execute_create_table( - database: &mut Database, +async fn execute_create_table( + database: &mut Database, if_not_exists: bool, ) -> Result<(), DatabaseError> { database @@ -450,8 +450,8 @@ async fn execute_create_table( } #[maybe_async] -async fn execute_create_index( - database: &mut Database, +async fn execute_create_index( + database: &mut Database, table_name: &'static str, index: &(&'static str, &'static [&'static str], bool), if_not_exists: bool, @@ -485,8 +485,8 @@ async fn execute_create_index( } #[maybe_async] -async fn execute_create_view( - database: &mut Database, +async fn execute_create_view( + database: &mut Database, view_name: &str, build: F, or_replace: bool, @@ -522,8 +522,8 @@ where } #[maybe_async] -async fn execute_drop_view( - database: &mut Database, +async fn execute_drop_view( + database: &mut Database, view_name: &str, if_exists: bool, ) -> Result<(), DatabaseError> { @@ -536,8 +536,8 @@ async fn execute_drop_view( } #[maybe_async] -async fn execute_change_column( - database: &mut Database, +async fn execute_change_column( + database: &mut Database, table_name: &'static str, old_column_name: &str, new_column_name: &str, @@ -567,8 +567,8 @@ async fn execute_change_column( } #[maybe_async] -async fn execute_drop_column( - database: &mut Database, +async fn execute_drop_column( + database: &mut Database, table_name: &'static str, column_name: &str, ) -> Result<(), DatabaseError> { @@ -581,8 +581,8 @@ async fn execute_drop_column( } #[maybe_async] -async fn execute_add_column( - database: &mut Database, +async fn execute_add_column( + database: &mut Database, table_name: &'static str, field: &OrmField, ) -> Result<(), DatabaseError> { @@ -595,8 +595,8 @@ async fn execute_add_column( } #[maybe_async] -async fn execute_drop_index( - database: &mut Database, +async fn execute_drop_index( + database: &mut Database, table_name: &'static str, index_name: &str, if_exists: bool, @@ -610,8 +610,8 @@ async fn execute_drop_index( } #[maybe_async] -async fn execute_drop_table( - database: &mut Database, +async fn execute_drop_table( + database: &mut Database, table_name: &'static str, if_exists: bool, ) -> Result<(), DatabaseError> { diff --git a/src/orm/dml.rs b/src/orm/dml.rs index bda6753e..80efb8a5 100644 --- a/src/orm/dml.rs +++ b/src/orm/dml.rs @@ -2,7 +2,7 @@ use super::*; use std::borrow::Borrow; #[maybe_async] -impl Database { +impl Database { /// Refreshes optimizer statistics for the model table. /// /// This runs `ANALYZE TABLE` for the backing table so the optimizer can use @@ -73,7 +73,7 @@ impl Database { } #[maybe_async] -impl<'a, S: Storage> Transaction<'a, S> { +impl<'a, S: Storage, D: SqlDialect> Transaction<'a, S, D> { /// Refreshes optimizer statistics for the model table inside the current transaction. pub async fn analyze(&mut self) -> Result<(), DatabaseError> { orm_analyze::<_, M>(self).await diff --git a/src/orm/dql.rs b/src/orm/dql.rs index 7f6e7afd..6d0e6cba 100644 --- a/src/orm/dql.rs +++ b/src/orm/dql.rs @@ -1,7 +1,7 @@ use super::*; #[maybe_async] -impl Database { +impl Database { /// Prepares an ORM-built plan once into a program for repeated execution with /// positional parameters. Use `e.param(id)` inside expression closures, then pass /// values to `Program::execute`. @@ -195,7 +195,7 @@ impl Database { } #[maybe_async] -impl<'a, S: Storage> Transaction<'a, S> { +impl<'a, S: Storage, D: SqlDialect> Transaction<'a, S, D> { /// Prepares an ORM-built plan into a program, against this transaction's view. pub fn program( &self, diff --git a/src/orm/mod.rs b/src/orm/mod.rs index 5858ae81..1e04e515 100644 --- a/src/orm/mod.rs +++ b/src/orm/mod.rs @@ -9,6 +9,7 @@ use crate::db::{ AsyncIter, BindSource, Database, DatabaseIter, Executor, OrmIter, ResultIter, ResultRow, Transaction, TransactionIter, TxnOrmIter, TxnResultIter, TxnValue, }; +use crate::dialect::SqlDialect; use crate::errors::DatabaseError; pub use crate::expression::agg::AggKind; use crate::expression::window::WindowFunctionKind; diff --git a/src/parser/mod.rs b/src/parser/mod.rs index d7d0b55f..011d67bf 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use sqlparser::dialect::Dialect as SqlParserDialect; use sqlparser::parser::ParserError; use sqlparser::{ast::Statement, dialect::GenericDialect, parser::Parser}; @@ -30,14 +31,15 @@ const DIALECT: GenericDialect = GenericDialect {}; /// println!("{:?}", ast); /// ``` pub fn parse_sql>(sql: S) -> Result, ParserError> { - parse_sql_with_recursion_limit(sql, None) + parse_sql_with_recursion_limit(&DIALECT, sql, None) } pub(crate) fn parse_sql_with_recursion_limit>( + dialect: &dyn SqlParserDialect, sql: S, recursion_limit: Option, ) -> Result, ParserError> { - let mut parser = Parser::new(&DIALECT); + let mut parser = Parser::new(dialect); if let Some(limit) = recursion_limit { parser = parser.with_recursion_limit(limit); } diff --git a/src/storage/mod.rs b/src/storage/mod.rs index 6f95872c..522ef397 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -2801,10 +2801,10 @@ pub(crate) async fn new_test_storage() -> TestStorage { // The async path's stand-in for `DataBaseBuilder::build_in_memory` in unit tests. #[cfg(all(test, feature = "async"))] -impl crate::db::DataBaseBuilder { +impl crate::db::DataBaseBuilder { pub(crate) async fn build_in_memory( self, - ) -> Result, DatabaseError> { + ) -> Result, DatabaseError> { self.build_with_storage(new_test_storage().await) } }