diff --git a/docs/features.md b/docs/features.md index 68030cb7..0f2ab69e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -437,5 +437,7 @@ The `SqlDialect` trait methods: - `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 +- `comparison_type()` — Optional hook to pick the type both operands of a comparison (`=`, `<>`, `<`, `<=`, `>`, `>=`, `IN`, `BETWEEN`) are cast to +- `boolean_text()` — Optional hook to choose the text of a boolean in `CAST(.. AS CHAR)` or `CAST(.. AS VARCHAR)` (default `'true'`/`'false'`) By default, the `GenericSqlDialect` is used, which provides standard SQL behavior with no custom transformations. diff --git a/src/binder/expr.rs b/src/binder/expr.rs index 7767e6b7..b7e7f82b 100644 --- a/src/binder/expr.rs +++ b/src/binder/expr.rs @@ -28,6 +28,8 @@ use crate::planner::{ExprRef, LogicalPlan, MetaArena, PlanArena}; use crate::storage::StorageTransaction; use crate::types::value::{DataValue, Utf8Type}; use crate::types::{CharLengthUnits, LogicalType}; +use std::borrow::Cow; +use std::{iter, slice}; macro_rules! try_default { ($table_name:expr, $column_name:expr) => { @@ -414,11 +416,26 @@ impl<'a, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'a, '_, pub(crate) fn bind_binary_op_expr( &mut self, - left_expr: ExprRef, - right_expr: ExprRef, + mut left_expr: ExprRef, + mut right_expr: ExprRef, op: expression::BinaryOperator, arena: &mut PlanArena, ) -> Result { + if matches!( + op, + expression::BinaryOperator::Gt + | expression::BinaryOperator::Lt + | expression::BinaryOperator::GtEq + | expression::BinaryOperator::LtEq + | expression::BinaryOperator::Eq + | expression::BinaryOperator::NotEq + ) { + self.coerce_comparison_operands( + &mut left_expr, + slice::from_mut(&mut right_expr), + arena, + )?; + } let left_ty = left_expr.return_type(arena); let right_ty = right_expr.return_type(arena); let ty = match &op { @@ -464,6 +481,67 @@ impl<'a, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'a, '_, }) } + pub(crate) fn coerce_comparison_operands( + &self, + left: &mut ExprRef, + rest: &mut [ExprRef], + arena: &mut PlanArena, + ) -> Result<(), DatabaseError> { + let dialect = self.context.dialect; + let mut ty = left.return_type(arena).into_owned(); + let mut coerced = false; + for operand in rest.iter() { + let operand_ty = operand.return_type(arena); + ty = match dialect.comparison_type(&ty, &operand_ty) { + Some(dialect_ty) => { + coerced = true; + dialect_ty + } + None => LogicalType::max_logical_type(&ty, &operand_ty)?.into_owned(), + }; + } + if coerced { + for operand in iter::once(left).chain(rest.iter_mut()) { + *operand = operand.type_cast(Cow::Borrowed(&ty), arena)?; + } + } + Ok(()) + } + + pub(crate) fn bind_cast( + &self, + mut expr: ScalarExpression, + ty: LogicalType, + arena: &mut PlanArena, + ) -> Result { + if matches!(ty, LogicalType::Char(..) | LogicalType::Varchar(..)) + && expr.return_type(arena).as_ref() == &LogicalType::Boolean + { + let dialect = self.context.dialect; + let on_true = dialect.boolean_text(true); + let on_false = dialect.boolean_text(false); + if on_true.is_some() || on_false.is_some() { + let mut branch = |value: bool, text: &str| { + ( + arena.alloc_expression(value.into()), + arena.alloc_expression(text.into()), + ) + }; + let expr_pairs = vec![ + branch(true, on_true.unwrap_or("true")), + branch(false, on_false.unwrap_or("false")), + ]; + expr = ScalarExpression::CaseWhen { + operand_expr: Some(arena.alloc_expression(expr)), + expr_pairs, + else_expr: None, + ty: LogicalType::Varchar(None, CharLengthUnits::Characters), + }; + } + } + expr.type_cast(Cow::Owned(ty), arena) + } + pub(crate) fn bind_unary_op_expr( &mut self, expr: ExprRef, diff --git a/src/binder/parser.rs b/src/binder/parser.rs index 26b324a9..c29625a0 100644 --- a/src/binder/parser.rs +++ b/src/binder/parser.rs @@ -2399,16 +2399,17 @@ impl<'a, 'parent, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> list, negated, } => { - let args = list + let mut args: Vec = list .iter() .map(|expr| { self.bind_expr(expr, arena) .map(|expr| arena.alloc_expression(expr)) }) .try_collect()?; - let expr = self + let mut expr = self .bind_expr(expr, arena) .map(|expr| arena.alloc_expression(expr))?; + self.coerce_comparison_operands(&mut expr, &mut args, arena)?; Ok(ScalarExpression::In { negated: *negated, evaluator: None, @@ -2418,10 +2419,14 @@ impl<'a, 'parent, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> } Expr::Cast { expr, data_type, .. - } => self.bind_expr(expr, arena)?.type_cast( - Cow::Owned(convert_data_type(data_type, self.context.dialect)?), - arena, - ), + } => { + let expr = self.bind_expr(expr, arena)?; + self.bind_cast( + expr, + convert_data_type(data_type, self.context.dialect)?, + arena, + ) + } Expr::TypedString(TypedString { data_type, value, .. }) => { @@ -2445,15 +2450,17 @@ impl<'a, 'parent, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> low, high, } => { - let expr = self + let mut expr = self .bind_expr(expr, arena) .map(|expr| arena.alloc_expression(expr))?; - let left_expr = self - .bind_expr(low, arena) - .map(|expr| arena.alloc_expression(expr))?; - let right_expr = self - .bind_expr(high, arena) - .map(|expr| arena.alloc_expression(expr))?; + let mut bounds = [ + self.bind_expr(low, arena) + .map(|expr| arena.alloc_expression(expr))?, + self.bind_expr(high, arena) + .map(|expr| arena.alloc_expression(expr))?, + ]; + self.coerce_comparison_operands(&mut expr, &mut bounds, arena)?; + let [left_expr, right_expr] = bounds; Ok(ScalarExpression::Between { negated: *negated, left_evaluator: None, diff --git a/src/dialect/mod.rs b/src/dialect/mod.rs index 942af9b0..dd74d70e 100644 --- a/src/dialect/mod.rs +++ b/src/dialect/mod.rs @@ -64,6 +64,31 @@ pub trait SqlDialect: Debug + Send + Sync + 'static { ) -> Option> { self.map_data_type(data_type) } + + /// Returns the type both operands of a comparison are cast to before comparing. + /// + /// Called by the binder for `=`, `<>`, `<`, `<=`, `>`, `>=`, `IN` lists and `BETWEEN` + /// with the operand types. Return `Some(type)` to cast every operand to `type`, or + /// `None` to keep the built-in coercion. + /// + /// The default implementation returns `None` for all types. + fn comparison_type( + &self, + _left: &crate::types::LogicalType, + _right: &crate::types::LogicalType, + ) -> Option { + None + } + + /// Returns the text of a boolean in `CAST(.. AS CHAR)` or `CAST(.. AS VARCHAR)`. + /// + /// Called by the binder, so the text is fixed when the statement is bound. Return `Some(text)` to override the text, or `None` to keep the built-in + /// `'true'`/`'false'`. + /// + /// The default implementation returns `None`. + fn boolean_text(&self, _value: bool) -> Option<&'static str> { + None + } } /// Standard SQL behavior with no customizations; the default dialect. @@ -184,6 +209,18 @@ impl SqlDialect for DynDialect { ) -> Option> { self.current().map_column_type(data_type) } + + fn comparison_type( + &self, + left: &crate::types::LogicalType, + right: &crate::types::LogicalType, + ) -> Option { + self.current().comparison_type(left, right) + } + + fn boolean_text(&self, value: bool) -> Option<&'static str> { + self.current().boolean_text(value) + } } #[cfg(all(test, not(target_arch = "wasm32")))] @@ -305,4 +342,56 @@ mod tests { Ok(()) } + + #[derive(Debug, Default)] + struct CoercionDialect { + parser: GenericDialect, + } + + impl SqlDialect for CoercionDialect { + fn name(&self) -> &str { + "test_coercion" + } + + fn parser_dialect(&self) -> &dyn SqlParserDialect { + &self.parser + } + + fn comparison_type(&self, left: &LogicalType, right: &LogicalType) -> Option { + let is_text = + |ty: &LogicalType| matches!(ty, LogicalType::Char(..) | LogicalType::Varchar(..)); + ((left.is_numeric() && is_text(right)) || (is_text(left) && right.is_numeric())) + .then_some(LogicalType::Double) + } + + fn boolean_text(&self, value: bool) -> Option<&'static str> { + Some(if value { "1" } else { "0" }) + } + } + + #[test] + async fn comparison_type_and_boolean_text() -> Result<(), DatabaseError> { + let generic = DataBaseBuilder::path(".").build_in_memory().await?; + let custom = DataBaseBuilder::path(".") + .dialect(CoercionDialect::default()) + .build_in_memory() + .await?; + let sql = "select 10 < '9', 10 = '10.0', 10 in ('9', '10.0'), 10 between '9' and '11', \ + cast(true as varchar), cast(1 = 0 as char(5)), \ + cast(cast(null as boolean) as varchar) is null"; + let text = |rows: Vec>| -> Vec { + rows[0].iter().map(ToString::to_string).collect() + }; + + assert_eq!( + text(query(&generic, sql).await?), + ["true", "false", "false", "false", "true", "false", "true"] + ); + assert_eq!( + text(query(&custom, sql).await?), + ["false", "true", "true", "true", "1", "0", "true"] + ); + + Ok(()) + } }