From 79b264e45efc7e78f23b554ea655884cd3ffe9e7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 21 Nov 2026 17:48:56 +0000 Subject: [PATCH 1/2] feat(dialect): add comparison coercion and boolean text hooks Add two SqlDialect hooks, both defaulting to the current behaviour: - comparison_type(left, right) picks the type both operands of a comparison (=, <>, <, <=, >, >=, IN lists, BETWEEN) are cast to. The binder applies it while binding the comparison; when the dialect returns None for every operand pair, nothing is cast and the built-in coercion applies as before. - boolean_text(value) picks the text of a boolean in CAST(.. AS CHAR) or CAST(.. AS VARCHAR). The binder reads it from the database's dialect when it binds the cast, so the text is fixed in the plan and cast evaluators stay dialect-free. GenericSqlDialect implements neither, so it is still a no-op, and DynDialect forwards both to its current dialect. A unit test in src/dialect/mod.rs checks both hooks against the generic results. Co-authored-by: Alex Skinner --- docs/features.md | 2 + src/binder/expr.rs | 83 ++++++++++++++++++++++++++++++++++++++++++ src/binder/parser.rs | 23 +++++++++--- src/dialect/mod.rs | 87 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 190 insertions(+), 5 deletions(-) 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..4441df27 100644 --- a/src/binder/expr.rs +++ b/src/binder/expr.rs @@ -28,6 +28,7 @@ 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; macro_rules! try_default { ($table_name:expr, $column_name:expr) => { @@ -419,6 +420,22 @@ impl<'a, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'a, '_, op: expression::BinaryOperator, arena: &mut PlanArena, ) -> Result { + let (left_expr, right_expr) = if matches!( + op, + expression::BinaryOperator::Gt + | expression::BinaryOperator::Lt + | expression::BinaryOperator::GtEq + | expression::BinaryOperator::LtEq + | expression::BinaryOperator::Eq + | expression::BinaryOperator::NotEq + ) { + let mut operands = [left_expr, right_expr]; + self.coerce_comparison_operands(&mut operands, arena)?; + let [left_expr, right_expr] = operands; + (left_expr, right_expr) + } else { + (left_expr, right_expr) + }; let left_ty = left_expr.return_type(arena); let right_ty = right_expr.return_type(arena); let ty = match &op { @@ -464,6 +481,72 @@ impl<'a, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'a, '_, }) } + /// `operands[0]` is the left-hand side. + pub(crate) fn coerce_comparison_operands( + &self, + operands: &mut [ExprRef], + arena: &mut PlanArena, + ) -> Result<(), DatabaseError> { + let Some((first, rest)) = operands.split_first() else { + return Ok(()); + }; + let dialect = self.context.dialect; + let mut ty = first.return_type(arena).into_owned(); + let mut coerced = false; + for operand in rest { + 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 operands.iter_mut() { + *operand = operand.type_cast(Cow::Borrowed(&ty), arena)?; + } + } + Ok(()) + } + + pub(crate) fn bind_cast( + &self, + expr: ScalarExpression, + ty: LogicalType, + arena: &mut PlanArena, + ) -> Result { + let dialect = self.context.dialect; + if matches!(ty, LogicalType::Char(..) | LogicalType::Varchar(..)) + && expr.return_type(arena).as_ref() == &LogicalType::Boolean + && (dialect.boolean_text(true).is_some() || dialect.boolean_text(false).is_some()) + { + let mut text = |value: bool| { + let text = dialect + .boolean_text(value) + .map_or_else(|| value.to_string(), str::to_string); + ( + arena.alloc_expression(ScalarExpression::Constant(DataValue::Boolean(value))), + arena.alloc_expression(ScalarExpression::Constant(DataValue::Utf8 { + value: text.into(), + ty: Utf8Type::Variable(None), + unit: CharLengthUnits::Characters, + })), + ) + }; + let expr_pairs = vec![text(true), text(false)]; + let expr = ScalarExpression::CaseWhen { + operand_expr: Some(arena.alloc_expression(expr)), + expr_pairs, + else_expr: None, + ty: LogicalType::Varchar(None, CharLengthUnits::Characters), + }; + return expr.type_cast(Cow::Owned(ty), arena); + } + 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..485ebdc0 100644 --- a/src/binder/parser.rs +++ b/src/binder/parser.rs @@ -2399,7 +2399,7 @@ impl<'a, 'parent, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> list, negated, } => { - let args = list + let args: Vec = list .iter() .map(|expr| { self.bind_expr(expr, arena) @@ -2409,6 +2409,12 @@ impl<'a, 'parent, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> let expr = self .bind_expr(expr, arena) .map(|expr| arena.alloc_expression(expr))?; + let mut operands = Vec::with_capacity(args.len() + 1); + operands.push(expr); + operands.extend(args); + self.coerce_comparison_operands(&mut operands, arena)?; + let expr = operands.remove(0); + let args = operands; Ok(ScalarExpression::In { negated: *negated, evaluator: None, @@ -2418,10 +2424,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, .. }) => { @@ -2454,6 +2464,9 @@ impl<'a, 'parent, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> let right_expr = self .bind_expr(high, arena) .map(|expr| arena.alloc_expression(expr))?; + let mut operands = [expr, left_expr, right_expr]; + self.coerce_comparison_operands(&mut operands, arena)?; + let [expr, left_expr, right_expr] = operands; Ok(ScalarExpression::Between { negated: *negated, left_evaluator: None, diff --git a/src/dialect/mod.rs b/src/dialect/mod.rs index 942af9b0..988ef2cc 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,54 @@ 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', cast(true as varchar), cast(1 = 0 as char(5))"; + let text = |rows: Vec>| -> Vec { + rows[0].iter().map(ToString::to_string).collect() + }; + + assert_eq!( + text(query(&generic, sql).await?), + ["true", "false", "true", "false"] + ); + assert_eq!( + text(query(&custom, sql).await?), + ["false", "true", "1", "0"] + ); + + Ok(()) + } } From 56805b056c2b10c7b13042c1fcb29ace8e468c33 Mon Sep 17 00:00:00 2001 From: kould Date: Sun, 22 Nov 2026 12:44:38 +0800 Subject: [PATCH 2/2] refactor(dialect): simplify comparison coercion and boolean casts --- src/binder/expr.rs | 79 +++++++++++++++++++++----------------------- src/binder/parser.rs | 30 +++++++---------- src/dialect/mod.rs | 8 +++-- 3 files changed, 54 insertions(+), 63 deletions(-) diff --git a/src/binder/expr.rs b/src/binder/expr.rs index 4441df27..b7e7f82b 100644 --- a/src/binder/expr.rs +++ b/src/binder/expr.rs @@ -29,6 +29,7 @@ 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) => { @@ -415,12 +416,12 @@ 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 { - let (left_expr, right_expr) = if matches!( + if matches!( op, expression::BinaryOperator::Gt | expression::BinaryOperator::Lt @@ -429,13 +430,12 @@ impl<'a, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'a, '_, | expression::BinaryOperator::Eq | expression::BinaryOperator::NotEq ) { - let mut operands = [left_expr, right_expr]; - self.coerce_comparison_operands(&mut operands, arena)?; - let [left_expr, right_expr] = operands; - (left_expr, right_expr) - } else { - (left_expr, right_expr) - }; + 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 { @@ -481,19 +481,16 @@ impl<'a, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'a, '_, }) } - /// `operands[0]` is the left-hand side. pub(crate) fn coerce_comparison_operands( &self, - operands: &mut [ExprRef], + left: &mut ExprRef, + rest: &mut [ExprRef], arena: &mut PlanArena, ) -> Result<(), DatabaseError> { - let Some((first, rest)) = operands.split_first() else { - return Ok(()); - }; let dialect = self.context.dialect; - let mut ty = first.return_type(arena).into_owned(); + let mut ty = left.return_type(arena).into_owned(); let mut coerced = false; - for operand in rest { + for operand in rest.iter() { let operand_ty = operand.return_type(arena); ty = match dialect.comparison_type(&ty, &operand_ty) { Some(dialect_ty) => { @@ -504,7 +501,7 @@ impl<'a, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'a, '_, }; } if coerced { - for operand in operands.iter_mut() { + for operand in iter::once(left).chain(rest.iter_mut()) { *operand = operand.type_cast(Cow::Borrowed(&ty), arena)?; } } @@ -513,36 +510,34 @@ impl<'a, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'a, '_, pub(crate) fn bind_cast( &self, - expr: ScalarExpression, + mut expr: ScalarExpression, ty: LogicalType, arena: &mut PlanArena, ) -> Result { - let dialect = self.context.dialect; if matches!(ty, LogicalType::Char(..) | LogicalType::Varchar(..)) && expr.return_type(arena).as_ref() == &LogicalType::Boolean - && (dialect.boolean_text(true).is_some() || dialect.boolean_text(false).is_some()) { - let mut text = |value: bool| { - let text = dialect - .boolean_text(value) - .map_or_else(|| value.to_string(), str::to_string); - ( - arena.alloc_expression(ScalarExpression::Constant(DataValue::Boolean(value))), - arena.alloc_expression(ScalarExpression::Constant(DataValue::Utf8 { - value: text.into(), - ty: Utf8Type::Variable(None), - unit: CharLengthUnits::Characters, - })), - ) - }; - let expr_pairs = vec![text(true), text(false)]; - let expr = ScalarExpression::CaseWhen { - operand_expr: Some(arena.alloc_expression(expr)), - expr_pairs, - else_expr: None, - ty: LogicalType::Varchar(None, CharLengthUnits::Characters), - }; - return expr.type_cast(Cow::Owned(ty), arena); + 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) } diff --git a/src/binder/parser.rs b/src/binder/parser.rs index 485ebdc0..c29625a0 100644 --- a/src/binder/parser.rs +++ b/src/binder/parser.rs @@ -2399,22 +2399,17 @@ impl<'a, 'parent, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> list, negated, } => { - let args: Vec = 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))?; - let mut operands = Vec::with_capacity(args.len() + 1); - operands.push(expr); - operands.extend(args); - self.coerce_comparison_operands(&mut operands, arena)?; - let expr = operands.remove(0); - let args = operands; + self.coerce_comparison_operands(&mut expr, &mut args, arena)?; Ok(ScalarExpression::In { negated: *negated, evaluator: None, @@ -2455,18 +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 operands = [expr, left_expr, right_expr]; - self.coerce_comparison_operands(&mut operands, arena)?; - let [expr, left_expr, right_expr] = operands; + 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 988ef2cc..dd74d70e 100644 --- a/src/dialect/mod.rs +++ b/src/dialect/mod.rs @@ -376,18 +376,20 @@ mod tests { .dialect(CoercionDialect::default()) .build_in_memory() .await?; - let sql = "select 10 < '9', 10 = '10.0', cast(true as varchar), cast(1 = 0 as char(5))"; + 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", "true", "false"] + ["true", "false", "false", "false", "true", "false", "true"] ); assert_eq!( text(query(&custom, sql).await?), - ["false", "true", "1", "0"] + ["false", "true", "true", "true", "1", "0", "true"] ); Ok(())