Download datafusion_1/solution/solution.patch from lolbench26/LoLBench: direct link, hf CLI and curl.
- Browser
- Download file 142 kB
-
https://huggingface.co/datasets/lolbench26/LoLBench/resolve/main/datafusion_1/solution/solution.patch
- Command line
-
hf download hf://datasets/lolbench26/LoLBench/datafusion_1/solution/solution.patch
-
curl -L -o solution.patch https://huggingface.co/datasets/lolbench26/LoLBench/resolve/main/datafusion_1/solution/solution.patch
142 kB
| diff --git a/datafusion-cli/src/functions.rs b/datafusion-cli/src/functions.rs | |
| index 911bbf34b..f07dac649 100644 | |
| --- a/datafusion-cli/src/functions.rs | |
| +++ b/datafusion-cli/src/functions.rs | |
| pub struct ParquetMetadataFunc {} | |
| impl TableFunctionImpl for ParquetMetadataFunc { | |
| fn call(&self, exprs: &[Expr]) -> Result<Arc<dyn TableProvider>> { | |
| let filename = match exprs.first() { | |
| - Some(Expr::Literal(ScalarValue::Utf8(Some(s)))) => s, // single quote: parquet_metadata('x.parquet') | |
| + Some(Expr::Literal(ScalarValue::Utf8(Some(s)), _)) => s, // single quote: parquet_metadata('x.parquet') | |
| Some(Expr::Column(Column { name, .. })) => name, // double quote: parquet_metadata("x.parquet") | |
| _ => { | |
| return plan_err!( | |
| diff --git a/datafusion-examples/examples/expr_api.rs b/datafusion-examples/examples/expr_api.rs | |
| index 089b8db6a..92cf33f4f 100644 | |
| --- a/datafusion-examples/examples/expr_api.rs | |
| +++ b/datafusion-examples/examples/expr_api.rs | |
| async fn main() -> Result<()> { | |
| let expr2 = Expr::BinaryExpr(BinaryExpr::new( | |
| Box::new(col("a")), | |
| Operator::Plus, | |
| - Box::new(Expr::Literal(ScalarValue::Int32(Some(5)))), | |
| + Box::new(Expr::Literal(ScalarValue::Int32(Some(5)), None)), | |
| )); | |
| assert_eq!(expr, expr2); | |
| diff --git a/datafusion-examples/examples/optimizer_rule.rs b/datafusion-examples/examples/optimizer_rule.rs | |
| index 63f174848..176b1a698 100644 | |
| --- a/datafusion-examples/examples/optimizer_rule.rs | |
| +++ b/datafusion-examples/examples/optimizer_rule.rs | |
| fn is_binary_eq(binary_expr: &BinaryExpr) -> bool { | |
| /// Return true if the expression is a literal or column reference | |
| fn is_lit_or_col(expr: &Expr) -> bool { | |
| - matches!(expr, Expr::Column(_) | Expr::Literal(_)) | |
| + matches!(expr, Expr::Column(_) | Expr::Literal(_, _)) | |
| } | |
| /// A simple user defined filter function | |
| diff --git a/datafusion-examples/examples/simple_udtf.rs b/datafusion-examples/examples/simple_udtf.rs | |
| index d2b2d1bf9..b65ffb8d7 100644 | |
| --- a/datafusion-examples/examples/simple_udtf.rs | |
| +++ b/datafusion-examples/examples/simple_udtf.rs | |
| struct LocalCsvTableFunc {} | |
| impl TableFunctionImpl for LocalCsvTableFunc { | |
| fn call(&self, exprs: &[Expr]) -> Result<Arc<dyn TableProvider>> { | |
| - let Some(Expr::Literal(ScalarValue::Utf8(Some(ref path)))) = exprs.first() else { | |
| + let Some(Expr::Literal(ScalarValue::Utf8(Some(ref path)), _)) = exprs.first() | |
| + else { | |
| return plan_err!("read_csv requires at least one string argument"); | |
| }; | |
| impl TableFunctionImpl for LocalCsvTableFunc { | |
| let info = SimplifyContext::new(&execution_props); | |
| let expr = ExprSimplifier::new(info).simplify(expr.clone())?; | |
| - if let Expr::Literal(ScalarValue::Int64(Some(limit))) = expr { | |
| + if let Expr::Literal(ScalarValue::Int64(Some(limit)), _) = expr { | |
| Ok(limit as usize) | |
| } else { | |
| plan_err!("Limit must be an integer") | |
| diff --git a/datafusion/catalog-listing/src/helpers.rs b/datafusion/catalog-listing/src/helpers.rs | |
| index 037c69ceb..00e9c71df 100644 | |
| --- a/datafusion/catalog-listing/src/helpers.rs | |
| +++ b/datafusion/catalog-listing/src/helpers.rs | |
| pub fn expr_applicable_for_cols(col_names: &[&str], expr: &Expr) -> bool { | |
| Ok(TreeNodeRecursion::Stop) | |
| } | |
| } | |
| - Expr::Literal(_) | |
| + Expr::Literal(_, _) | |
| | Expr::Alias(_) | |
| | Expr::OuterReferenceColumn(_, _) | |
| | Expr::ScalarVariable(_, _) | |
| fn populate_partition_values<'a>( | |
| { | |
| match op { | |
| Operator::Eq => match (left.as_ref(), right.as_ref()) { | |
| - (Expr::Column(Column { ref name, .. }), Expr::Literal(val)) | |
| - | (Expr::Literal(val), Expr::Column(Column { ref name, .. })) => { | |
| + (Expr::Column(Column { ref name, .. }), Expr::Literal(val, _)) | |
| + | (Expr::Literal(val, _), Expr::Column(Column { ref name, .. })) => { | |
| if partition_values | |
| .insert(name, PartitionValue::Single(val.to_string())) | |
| .is_some() | |
| mod tests { | |
| assert_eq!( | |
| evaluate_partition_prefix( | |
| partitions, | |
| - &[col("a").eq(Expr::Literal(ScalarValue::Date32(Some(3))))], | |
| + &[col("a").eq(Expr::Literal(ScalarValue::Date32(Some(3)), None))], | |
| ), | |
| Some(Path::from("a=1970-01-04")), | |
| ); | |
| mod tests { | |
| assert_eq!( | |
| evaluate_partition_prefix( | |
| partitions, | |
| - &[col("a").eq(Expr::Literal(ScalarValue::Date64(Some( | |
| - 4 * 24 * 60 * 60 * 1000 | |
| - )))),], | |
| + &[col("a").eq(Expr::Literal( | |
| + ScalarValue::Date64(Some(4 * 24 * 60 * 60 * 1000)), | |
| + None | |
| + )),], | |
| ), | |
| Some(Path::from("a=1970-01-05")), | |
| ); | |
| diff --git a/datafusion/core/benches/map_query_sql.rs b/datafusion/core/benches/map_query_sql.rs | |
| index 97d47fc3b..063b8e6c8 100644 | |
| --- a/datafusion/core/benches/map_query_sql.rs | |
| +++ b/datafusion/core/benches/map_query_sql.rs | |
| fn criterion_benchmark(c: &mut Criterion) { | |
| let mut value_buffer = Vec::new(); | |
| for i in 0..1000 { | |
| - key_buffer.push(Expr::Literal(ScalarValue::Utf8(Some(keys[i].clone())))); | |
| - value_buffer.push(Expr::Literal(ScalarValue::Int32(Some(values[i])))); | |
| + key_buffer.push(Expr::Literal( | |
| + ScalarValue::Utf8(Some(keys[i].clone())), | |
| + None, | |
| + )); | |
| + value_buffer.push(Expr::Literal(ScalarValue::Int32(Some(values[i])), None)); | |
| } | |
| c.bench_function("map_1000_1", |b| { | |
| b.iter(|| { | |
| diff --git a/datafusion/core/src/dataframe/mod.rs b/datafusion/core/src/dataframe/mod.rs | |
| index 69992e57c..02a18f22c 100644 | |
| --- a/datafusion/core/src/dataframe/mod.rs | |
| +++ b/datafusion/core/src/dataframe/mod.rs | |
| impl DataFrame { | |
| /// ``` | |
| pub async fn count(self) -> Result<usize> { | |
| let rows = self | |
| - .aggregate(vec![], vec![count(Expr::Literal(COUNT_STAR_EXPANSION))])? | |
| + .aggregate( | |
| + vec![], | |
| + vec![count(Expr::Literal(COUNT_STAR_EXPANSION, None))], | |
| + )? | |
| .collect() | |
| .await?; | |
| let len = *rows | |
| diff --git a/datafusion/core/src/datasource/listing/table.rs b/datafusion/core/src/datasource/listing/table.rs | |
| index 3c87d3ee2..0dd6cd38b 100644 | |
| --- a/datafusion/core/src/datasource/listing/table.rs | |
| +++ b/datafusion/core/src/datasource/listing/table.rs | |
| mod tests { | |
| let filter_predicate = Expr::BinaryExpr(BinaryExpr::new( | |
| Box::new(Expr::Column("column1".into())), | |
| Operator::GtEq, | |
| - Box::new(Expr::Literal(ScalarValue::Int32(Some(0)))), | |
| + Box::new(Expr::Literal(ScalarValue::Int32(Some(0)), None)), | |
| )); | |
| // Create a new batch of data to insert into the table | |
| diff --git a/datafusion/core/src/execution/context/mod.rs b/datafusion/core/src/execution/context/mod.rs | |
| index 5ef666b61..dbe5c2c00 100644 | |
| --- a/datafusion/core/src/execution/context/mod.rs | |
| +++ b/datafusion/core/src/execution/context/mod.rs | |
| impl SessionContext { | |
| let mut params: Vec<ScalarValue> = parameters | |
| .into_iter() | |
| .map(|e| match e { | |
| - Expr::Literal(scalar) => Ok(scalar), | |
| + Expr::Literal(scalar, _) => Ok(scalar), | |
| _ => not_impl_err!("Unsupported parameter type: {}", e), | |
| }) | |
| .collect::<Result<_>>()?; | |
| diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs | |
| index 61d1fee79..c65fcb4c4 100644 | |
| --- a/datafusion/core/src/physical_planner.rs | |
| +++ b/datafusion/core/src/physical_planner.rs | |
| mod tests { | |
| // verify that the plan correctly casts u8 to i64 | |
| // the cast from u8 to i64 for literal will be simplified, and get lit(int64(5)) | |
| // the cast here is implicit so has CastOptions with safe=true | |
| - let expected = "BinaryExpr { left: Column { name: \"c7\", index: 2 }, op: Lt, right: Literal { value: Int64(5) }, fail_on_overflow: false }"; | |
| + let expected = r#"BinaryExpr { left: Column { name: "c7", index: 2 }, op: Lt, right: Literal { value: Int64(5), field: Field { name: "5", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} } }, fail_on_overflow: false }"#; | |
| + | |
| assert!(format!("{exec_plan:?}").contains(expected)); | |
| Ok(()) | |
| } | |
| mod tests { | |
| &session_state, | |
| ); | |
| - let expected = r#"Ok(PhysicalGroupBy { expr: [(Column { name: "c1", index: 0 }, "c1"), (Column { name: "c2", index: 1 }, "c2"), (Column { name: "c3", index: 2 }, "c3")], null_expr: [(Literal { value: Utf8(NULL) }, "c1"), (Literal { value: Int64(NULL) }, "c2"), (Literal { value: Int64(NULL) }, "c3")], groups: [[false, false, false], [true, false, false], [false, true, false], [false, false, true], [true, true, false], [true, false, true], [false, true, true], [true, true, true]] })"#; | |
| + let expected = r#"Ok(PhysicalGroupBy { expr: [(Column { name: "c1", index: 0 }, "c1"), (Column { name: "c2", index: 1 }, "c2"), (Column { name: "c3", index: 2 }, "c3")], null_expr: [(Literal { value: Utf8(NULL), field: Field { name: "NULL", data_type: Utf8, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} } }, "c1"), (Literal { value: Int64(NULL), field: Field { name: "NULL", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} } }, "c2"), (Literal { value: Int64(NULL), field: Field { name: "NULL", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} } }, "c3")], groups: [[false, false, false], [true, false, false], [false, true, false], [false, false, true], [true, true, false], [true, false, true], [false, true, true], [true, true, true]] })"#; | |
| assert_eq!(format!("{cube:?}"), expected); | |
| mod tests { | |
| &session_state, | |
| ); | |
| - let expected = r#"Ok(PhysicalGroupBy { expr: [(Column { name: "c1", index: 0 }, "c1"), (Column { name: "c2", index: 1 }, "c2"), (Column { name: "c3", index: 2 }, "c3")], null_expr: [(Literal { value: Utf8(NULL) }, "c1"), (Literal { value: Int64(NULL) }, "c2"), (Literal { value: Int64(NULL) }, "c3")], groups: [[true, true, true], [false, true, true], [false, false, true], [false, false, false]] })"#; | |
| + let expected = r#"Ok(PhysicalGroupBy { expr: [(Column { name: "c1", index: 0 }, "c1"), (Column { name: "c2", index: 1 }, "c2"), (Column { name: "c3", index: 2 }, "c3")], null_expr: [(Literal { value: Utf8(NULL), field: Field { name: "NULL", data_type: Utf8, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} } }, "c1"), (Literal { value: Int64(NULL), field: Field { name: "NULL", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} } }, "c2"), (Literal { value: Int64(NULL), field: Field { name: "NULL", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} } }, "c3")], groups: [[true, true, true], [false, true, true], [false, false, true], [false, false, false]] })"#; | |
| assert_eq!(format!("{rollup:?}"), expected); | |
| mod tests { | |
| let execution_plan = plan(&logical_plan).await?; | |
| // verify that the plan correctly adds cast from Int64(1) to Utf8, and the const will be evaluated. | |
| - let expected = "expr: [(BinaryExpr { left: BinaryExpr { left: Column { name: \"c1\", index: 0 }, op: Eq, right: Literal { value: Utf8(\"a\") }, fail_on_overflow: false }, op: Or, right: BinaryExpr { left: Column { name: \"c1\", index: 0 }, op: Eq, right: Literal { value: Utf8(\"1\") }, fail_on_overflow: false }, fail_on_overflow: false }"; | |
| + let expected = "expr: [(BinaryExpr { left: BinaryExpr { left: Column { name: \"c1\", index: 0 }, op: Eq, right: Literal { value: Utf8(\"a\"), field: Field { name: \"a\", data_type: Utf8, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} } }, fail_on_overflow: false }, op: Or, right: BinaryExpr { left: Column { name: \"c1\", index: 0 }, op: Eq, right: Literal { value: Utf8(\"1\"), field: Field { name: \"1\", data_type: Utf8, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} } }, fail_on_overflow: false }, fail_on_overflow: false }"; | |
| let actual = format!("{execution_plan:?}"); | |
| assert!(actual.contains(expected), "{}", actual); | |
| diff --git a/datafusion/datasource-parquet/src/row_filter.rs b/datafusion/datasource-parquet/src/row_filter.rs | |
| index cde9e56c9..db455fed6 100644 | |
| --- a/datafusion/datasource-parquet/src/row_filter.rs | |
| +++ b/datafusion/datasource-parquet/src/row_filter.rs | |
| mod test { | |
| // Test all should fail | |
| let expr = col("timestamp_col").lt(Expr::Literal( | |
| ScalarValue::TimestampNanosecond(Some(1), Some(Arc::from("UTC"))), | |
| + None, | |
| )); | |
| let expr = logical2physical(&expr, &table_schema); | |
| let schema_adapter_factory = Arc::new(DefaultSchemaAdapterFactory); | |
| mod test { | |
| // Test all should pass | |
| let expr = col("timestamp_col").gt(Expr::Literal( | |
| ScalarValue::TimestampNanosecond(Some(0), Some(Arc::from("UTC"))), | |
| + None, | |
| )); | |
| let expr = logical2physical(&expr, &table_schema); | |
| let schema_adapter_factory = Arc::new(DefaultSchemaAdapterFactory); | |
| mod test { | |
| let expr = col("string_col") | |
| .is_not_null() | |
| - .or(col("bigint_col").gt(Expr::Literal(ScalarValue::Int64(Some(5))))); | |
| + .or(col("bigint_col").gt(Expr::Literal(ScalarValue::Int64(Some(5)), None))); | |
| let expr = logical2physical(&expr, &table_schema); | |
| assert!(can_expr_be_pushed_down_with_schemas(&expr, &table_schema)); | |
| diff --git a/datafusion/datasource-parquet/src/row_group_filter.rs b/datafusion/datasource-parquet/src/row_group_filter.rs | |
| index d44fa1684..f9fb92144 100644 | |
| --- a/datafusion/datasource-parquet/src/row_group_filter.rs | |
| +++ b/datafusion/datasource-parquet/src/row_group_filter.rs | |
| mod tests { | |
| .run( | |
| lit("1").eq(lit("1")).and( | |
| col(r#""String""#) | |
| - .eq(Expr::Literal(ScalarValue::Utf8View(Some(String::from( | |
| - "Hello_Not_Exists", | |
| - ))))) | |
| - .or(col(r#""String""#).eq(Expr::Literal(ScalarValue::Utf8View( | |
| - Some(String::from("Hello_Not_Exists2")), | |
| - )))), | |
| + .eq(Expr::Literal( | |
| + ScalarValue::Utf8View(Some(String::from("Hello_Not_Exists"))), | |
| + None, | |
| + )) | |
| + .or(col(r#""String""#).eq(Expr::Literal( | |
| + ScalarValue::Utf8View(Some(String::from( | |
| + "Hello_Not_Exists2", | |
| + ))), | |
| + None, | |
| + ))), | |
| ), | |
| ) | |
| .await | |
| mod tests { | |
| // generate pruning predicate `(String = "Hello") OR (String = "the quick") OR (String = "are you")` | |
| .run( | |
| col(r#""String""#) | |
| - .eq(Expr::Literal(ScalarValue::Utf8View(Some(String::from( | |
| - "Hello", | |
| - ))))) | |
| - .or(col(r#""String""#).eq(Expr::Literal(ScalarValue::Utf8View( | |
| - Some(String::from("the quick")), | |
| - )))) | |
| - .or(col(r#""String""#).eq(Expr::Literal(ScalarValue::Utf8View( | |
| - Some(String::from("are you")), | |
| - )))), | |
| + .eq(Expr::Literal( | |
| + ScalarValue::Utf8View(Some(String::from("Hello"))), | |
| + None, | |
| + )) | |
| + .or(col(r#""String""#).eq(Expr::Literal( | |
| + ScalarValue::Utf8View(Some(String::from("the quick"))), | |
| + None, | |
| + ))) | |
| + .or(col(r#""String""#).eq(Expr::Literal( | |
| + ScalarValue::Utf8View(Some(String::from("are you"))), | |
| + None, | |
| + ))), | |
| ) | |
| .await | |
| } | |
| diff --git a/datafusion/expr/src/conditional_expressions.rs b/datafusion/expr/src/conditional_expressions.rs | |
| index 9cb51612d..69525ea52 100644 | |
| --- a/datafusion/expr/src/conditional_expressions.rs | |
| +++ b/datafusion/expr/src/conditional_expressions.rs | |
| impl CaseBuilder { | |
| let then_types: Vec<DataType> = then_expr | |
| .iter() | |
| .map(|e| match e { | |
| - Expr::Literal(_) => e.get_type(&DFSchema::empty()), | |
| + Expr::Literal(_, _) => e.get_type(&DFSchema::empty()), | |
| _ => Ok(DataType::Null), | |
| }) | |
| .collect::<Result<Vec<_>>>()?; | |
| diff --git a/datafusion/expr/src/expr.rs b/datafusion/expr/src/expr.rs | |
| index dcd5380b4..f379edf10 100644 | |
| --- a/datafusion/expr/src/expr.rs | |
| +++ b/datafusion/expr/src/expr.rs | |
| //! Logical Expressions: [`Expr`] | |
| -use std::collections::HashSet; | |
| +use std::cmp::Ordering; | |
| +use std::collections::{BTreeMap, HashSet}; | |
| use std::fmt::{self, Display, Formatter, Write}; | |
| use std::hash::{Hash, Hasher}; | |
| use std::mem; | |
| use sqlparser::ast::{ | |
| /// BinaryExpr { | |
| /// left: Expr::Column("A"), | |
| /// op: Operator::Plus, | |
| -/// right: Expr::Literal(ScalarValue::Int32(Some(1))) | |
| +/// right: Expr::Literal(ScalarValue::Int32(Some(1)), None) | |
| /// } | |
| /// ``` | |
| /// | |
| use sqlparser::ast::{ | |
| /// # use datafusion_expr::{lit, col, Expr}; | |
| /// // All literals are strongly typed in DataFusion. To make an `i64` 42: | |
| /// let expr = lit(42i64); | |
| -/// assert_eq!(expr, Expr::Literal(ScalarValue::Int64(Some(42)))); | |
| -/// assert_eq!(expr, Expr::Literal(ScalarValue::Int64(Some(42)))); | |
| +/// assert_eq!(expr, Expr::Literal(ScalarValue::Int64(Some(42)), None)); | |
| +/// assert_eq!(expr, Expr::Literal(ScalarValue::Int64(Some(42)), None)); | |
| /// // To make a (typed) NULL: | |
| -/// let expr = Expr::Literal(ScalarValue::Int64(None)); | |
| +/// let expr = Expr::Literal(ScalarValue::Int64(None), None); | |
| /// // to make an (untyped) NULL (the optimizer will coerce this to the correct type): | |
| /// let expr = lit(ScalarValue::Null); | |
| /// ``` | |
| use sqlparser::ast::{ | |
| /// if let Expr::BinaryExpr(binary_expr) = expr { | |
| /// assert_eq!(*binary_expr.left, col("c1")); | |
| /// let scalar = ScalarValue::Int32(Some(42)); | |
| -/// assert_eq!(*binary_expr.right, Expr::Literal(scalar)); | |
| +/// assert_eq!(*binary_expr.right, Expr::Literal(scalar, None)); | |
| /// assert_eq!(binary_expr.op, Operator::Eq); | |
| /// } | |
| /// ``` | |
| use sqlparser::ast::{ | |
| /// ``` | |
| /// # use datafusion_expr::{lit, col}; | |
| /// let expr = col("c1") + lit(42); | |
| -/// assert_eq!(format!("{expr:?}"), "BinaryExpr(BinaryExpr { left: Column(Column { relation: None, name: \"c1\" }), op: Plus, right: Literal(Int32(42)) })"); | |
| +/// assert_eq!(format!("{expr:?}"), "BinaryExpr(BinaryExpr { left: Column(Column { relation: None, name: \"c1\" }), op: Plus, right: Literal(Int32(42), None) })"); | |
| /// ``` | |
| /// | |
| /// ## Use the `Display` trait (detailed expression) | |
| use sqlparser::ast::{ | |
| /// let mut scalars = HashSet::new(); | |
| /// // apply recursively visits all nodes in the expression tree | |
| /// expr.apply(|e| { | |
| -/// if let Expr::Literal(scalar) = e { | |
| +/// if let Expr::Literal(scalar, _) = e { | |
| /// scalars.insert(scalar); | |
| /// } | |
| /// // The return value controls whether to continue visiting the tree | |
| use sqlparser::ast::{ | |
| /// assert!(rewritten.transformed); | |
| /// // to 42 = 5 AND b = 6 | |
| /// assert_eq!(rewritten.data, lit(42).eq(lit(5)).and(col("b").eq(lit(6)))); | |
| -#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)] | |
| +#[derive(Clone, PartialEq, PartialOrd, Eq, Debug, Hash)] | |
| pub enum Expr { | |
| /// An expression with a specific name. | |
| Alias(Alias), | |
| pub enum Expr { | |
| Column(Column), | |
| /// A named reference to a variable in a registry. | |
| ScalarVariable(DataType, Vec<String>), | |
| - /// A constant value. | |
| - Literal(ScalarValue), | |
| + /// A constant value along with associated metadata | |
| + Literal(ScalarValue, Option<BTreeMap<String, String>>), | |
| /// A binary expression such as "age > 21" | |
| BinaryExpr(BinaryExpr), | |
| /// LIKE expression | |
| pub enum Expr { | |
| impl Default for Expr { | |
| fn default() -> Self { | |
| - Expr::Literal(ScalarValue::Null) | |
| + Expr::Literal(ScalarValue::Null, None) | |
| } | |
| } | |
| impl Hash for Alias { | |
| } | |
| impl PartialOrd for Alias { | |
| - fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { | |
| + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | |
| let cmp = self.expr.partial_cmp(&other.expr); | |
| - let Some(std::cmp::Ordering::Equal) = cmp else { | |
| + let Some(Ordering::Equal) = cmp else { | |
| return cmp; | |
| }; | |
| let cmp = self.relation.partial_cmp(&other.relation); | |
| - let Some(std::cmp::Ordering::Equal) = cmp else { | |
| + let Some(Ordering::Equal) = cmp else { | |
| return cmp; | |
| }; | |
| self.name.partial_cmp(&other.name) | |
| impl Expr { | |
| |expr| { | |
| // f_up: unalias on up so we can remove nested aliases like | |
| // `(x as foo) as bar` | |
| - if let Expr::Alias(Alias { expr, .. }) = expr { | |
| - Ok(Transformed::yes(*expr)) | |
| + if let Expr::Alias(alias) = expr { | |
| + match alias | |
| + .metadata | |
| + .as_ref() | |
| + .map(|h| h.is_empty()) | |
| + .unwrap_or(true) | |
| + { | |
| + true => Ok(Transformed::yes(*alias.expr)), | |
| + false => Ok(Transformed::no(Expr::Alias(alias))), | |
| + } | |
| } else { | |
| Ok(Transformed::no(expr)) | |
| } | |
| impl HashNode for Expr { | |
| data_type.hash(state); | |
| name.hash(state); | |
| } | |
| - Expr::Literal(scalar_value) => { | |
| + Expr::Literal(scalar_value, _) => { | |
| scalar_value.hash(state); | |
| } | |
| Expr::BinaryExpr(BinaryExpr { | |
| impl Display for SchemaDisplay<'_> { | |
| // TODO: remove the next line after `Expr::Wildcard` is removed | |
| #[expect(deprecated)] | |
| Expr::Column(_) | |
| - | Expr::Literal(_) | |
| + | Expr::Literal(_, _) | |
| | Expr::ScalarVariable(..) | |
| | Expr::OuterReferenceColumn(..) | |
| | Expr::Placeholder(_) | |
| struct SqlDisplay<'a>(&'a Expr); | |
| impl Display for SqlDisplay<'_> { | |
| fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { | |
| match self.0 { | |
| - Expr::Literal(scalar) => scalar.fmt(f), | |
| + Expr::Literal(scalar, _) => scalar.fmt(f), | |
| Expr::Alias(Alias { name, .. }) => write!(f, "{name}"), | |
| Expr::Between(Between { | |
| expr, | |
| impl Display for Expr { | |
| write!(f, "{OUTER_REFERENCE_COLUMN_PREFIX}({c})") | |
| } | |
| Expr::ScalarVariable(_, var_names) => write!(f, "{}", var_names.join(".")), | |
| - Expr::Literal(v) => write!(f, "{v:?}"), | |
| + Expr::Literal(v, metadata) => { | |
| + match metadata.as_ref().map(|m| m.is_empty()).unwrap_or(true) { | |
| + false => write!(f, "{v:?} {:?}", metadata.as_ref().unwrap()), | |
| + true => write!(f, "{v:?}"), | |
| + } | |
| + } | |
| Expr::Case(case) => { | |
| write!(f, "CASE ")?; | |
| if let Some(e) = &case.expr { | |
| mod test { | |
| #[allow(deprecated)] | |
| fn format_cast() -> Result<()> { | |
| let expr = Expr::Cast(Cast { | |
| - expr: Box::new(Expr::Literal(ScalarValue::Float32(Some(1.23)))), | |
| + expr: Box::new(Expr::Literal(ScalarValue::Float32(Some(1.23)), None)), | |
| data_type: DataType::Utf8, | |
| }); | |
| let expected_canonical = "CAST(Float32(1.23) AS Utf8)"; | |
| diff --git a/datafusion/expr/src/expr_fn.rs b/datafusion/expr/src/expr_fn.rs | |
| index 5182ccb15..e8885ed6b 100644 | |
| --- a/datafusion/expr/src/expr_fn.rs | |
| +++ b/datafusion/expr/src/expr_fn.rs | |
| impl WindowUDFImpl for SimpleWindowUDF { | |
| pub fn interval_year_month_lit(value: &str) -> Expr { | |
| let interval = parse_interval_year_month(value).ok(); | |
| - Expr::Literal(ScalarValue::IntervalYearMonth(interval)) | |
| + Expr::Literal(ScalarValue::IntervalYearMonth(interval), None) | |
| } | |
| pub fn interval_datetime_lit(value: &str) -> Expr { | |
| let interval = parse_interval_day_time(value).ok(); | |
| - Expr::Literal(ScalarValue::IntervalDayTime(interval)) | |
| + Expr::Literal(ScalarValue::IntervalDayTime(interval), None) | |
| } | |
| pub fn interval_month_day_nano_lit(value: &str) -> Expr { | |
| let interval = parse_interval_month_day_nano(value).ok(); | |
| - Expr::Literal(ScalarValue::IntervalMonthDayNano(interval)) | |
| + Expr::Literal(ScalarValue::IntervalMonthDayNano(interval), None) | |
| } | |
| /// Extensions for configuring [`Expr::AggregateFunction`] or [`Expr::WindowFunction`] | |
| diff --git a/datafusion/expr/src/expr_rewriter/mod.rs b/datafusion/expr/src/expr_rewriter/mod.rs | |
| index 90dcbce46..f80b8e5a7 100644 | |
| --- a/datafusion/expr/src/expr_rewriter/mod.rs | |
| +++ b/datafusion/expr/src/expr_rewriter/mod.rs | |
| mod test { | |
| use std::ops::Add; | |
| use super::*; | |
| + use crate::literal::lit_with_metadata; | |
| use crate::{col, lit, Cast}; | |
| use arrow::datatypes::{DataType, Field, Schema}; | |
| use datafusion_common::tree_node::TreeNodeRewriter; | |
| mod test { | |
| // rewrites all "foo" string literals to "bar" | |
| let transformer = |expr: Expr| -> Result<Transformed<Expr>> { | |
| match expr { | |
| - Expr::Literal(ScalarValue::Utf8(Some(utf8_val))) => { | |
| + Expr::Literal(ScalarValue::Utf8(Some(utf8_val)), metadata) => { | |
| let utf8_val = if utf8_val == "foo" { | |
| "bar".to_string() | |
| } else { | |
| utf8_val | |
| }; | |
| - Ok(Transformed::yes(lit(utf8_val))) | |
| + Ok(Transformed::yes(lit_with_metadata( | |
| + utf8_val, | |
| + metadata | |
| + .map(|m| m.into_iter().collect::<HashMap<String, String>>()), | |
| + ))) | |
| } | |
| // otherwise, return None | |
| _ => Ok(Transformed::no(expr)), | |
| diff --git a/datafusion/expr/src/expr_schema.rs b/datafusion/expr/src/expr_schema.rs | |
| index bdf9911b0..1973a00a6 100644 | |
| --- a/datafusion/expr/src/expr_schema.rs | |
| +++ b/datafusion/expr/src/expr_schema.rs | |
| impl ExprSchemable for Expr { | |
| Expr::Column(c) => Ok(schema.data_type(c)?.clone()), | |
| Expr::OuterReferenceColumn(ty, _) => Ok(ty.clone()), | |
| Expr::ScalarVariable(ty, _) => Ok(ty.clone()), | |
| - Expr::Literal(l) => Ok(l.data_type()), | |
| + Expr::Literal(l, _) => Ok(l.data_type()), | |
| Expr::Case(case) => { | |
| for (_, then_expr) in &case.when_then_expr { | |
| let then_type = then_expr.get_type(schema)?; | |
| impl ExprSchemable for Expr { | |
| Expr::Column(c) => input_schema.nullable(c), | |
| Expr::OuterReferenceColumn(_, _) => Ok(true), | |
| - Expr::Literal(value) => Ok(value.is_null()), | |
| + Expr::Literal(value, _) => Ok(value.is_null()), | |
| Expr::Case(case) => { | |
| // This expression is nullable if any of the input expressions are nullable | |
| let then_nullable = case | |
| impl ExprSchemable for Expr { | |
| Expr::ScalarVariable(ty, _) => { | |
| Ok(Arc::new(Field::new(&schema_name, ty.clone(), true))) | |
| } | |
| - Expr::Literal(l) => Ok(Arc::new(Field::new( | |
| - &schema_name, | |
| - l.data_type(), | |
| - l.is_null(), | |
| - ))), | |
| + Expr::Literal(l, metadata) => { | |
| + let mut field = Field::new(&schema_name, l.data_type(), l.is_null()); | |
| + if let Some(metadata) = metadata { | |
| + field = field.with_metadata( | |
| + metadata | |
| + .iter() | |
| + .map(|(k, v)| (k.clone(), v.clone())) | |
| + .collect(), | |
| + ); | |
| + } | |
| + Ok(Arc::new(field)) | |
| + } | |
| Expr::IsNull(_) | |
| | Expr::IsNotNull(_) | |
| | Expr::IsTrue(_) | |
| impl ExprSchemable for Expr { | |
| let arguments = args | |
| .iter() | |
| .map(|e| match e { | |
| - Expr::Literal(sv) => Some(sv), | |
| + Expr::Literal(sv, _) => Some(sv), | |
| _ => None, | |
| }) | |
| .collect::<Vec<_>>(); | |
| diff --git a/datafusion/expr/src/lib.rs b/datafusion/expr/src/lib.rs | |
| index 48931d652..1f44f755b 100644 | |
| --- a/datafusion/expr/src/lib.rs | |
| +++ b/datafusion/expr/src/lib.rs | |
| pub use function::{ | |
| AccumulatorFactoryFunction, PartitionEvaluatorFactory, ReturnTypeFunction, | |
| ScalarFunctionImplementation, StateTypeFunction, | |
| }; | |
| -pub use literal::{lit, lit_timestamp_nano, Literal, TimestampLiteral}; | |
| +pub use literal::{ | |
| + lit, lit_timestamp_nano, lit_with_metadata, Literal, TimestampLiteral, | |
| +}; | |
| pub use logical_plan::*; | |
| pub use partition_evaluator::PartitionEvaluator; | |
| pub use sqlparser; | |
| diff --git a/datafusion/expr/src/literal.rs b/datafusion/expr/src/literal.rs | |
| index 90ba5a9a6..48e058b8b 100644 | |
| --- a/datafusion/expr/src/literal.rs | |
| +++ b/datafusion/expr/src/literal.rs | |
| use crate::Expr; | |
| use datafusion_common::ScalarValue; | |
| +use std::collections::HashMap; | |
| /// Create a literal expression | |
| pub fn lit<T: Literal>(n: T) -> Expr { | |
| n.lit() | |
| } | |
| +pub fn lit_with_metadata<T: Literal>( | |
| + n: T, | |
| + metadata: impl Into<Option<HashMap<String, String>>>, | |
| +) -> Expr { | |
| + let metadata = metadata.into(); | |
| + let Some(metadata) = metadata else { | |
| + return n.lit(); | |
| + }; | |
| + | |
| + let Expr::Literal(sv, prior_metadata) = n.lit() else { | |
| + unreachable!(); | |
| + }; | |
| + | |
| + let new_metadata = match prior_metadata { | |
| + Some(mut prior) => { | |
| + prior.extend(metadata); | |
| + prior | |
| + } | |
| + None => metadata.into_iter().collect(), | |
| + }; | |
| + | |
| + Expr::Literal(sv, Some(new_metadata)) | |
| +} | |
| + | |
| /// Create a literal timestamp expression | |
| pub fn lit_timestamp_nano<T: TimestampLiteral>(n: T) -> Expr { | |
| n.lit_timestamp_nano() | |
| pub trait TimestampLiteral { | |
| impl Literal for &str { | |
| fn lit(&self) -> Expr { | |
| - Expr::Literal(ScalarValue::from(*self)) | |
| + Expr::Literal(ScalarValue::from(*self), None) | |
| } | |
| } | |
| impl Literal for String { | |
| fn lit(&self) -> Expr { | |
| - Expr::Literal(ScalarValue::from(self.as_ref())) | |
| + Expr::Literal(ScalarValue::from(self.as_ref()), None) | |
| } | |
| } | |
| impl Literal for &String { | |
| fn lit(&self) -> Expr { | |
| - Expr::Literal(ScalarValue::from(self.as_ref())) | |
| + Expr::Literal(ScalarValue::from(self.as_ref()), None) | |
| } | |
| } | |
| impl Literal for Vec<u8> { | |
| fn lit(&self) -> Expr { | |
| - Expr::Literal(ScalarValue::Binary(Some((*self).to_owned()))) | |
| + Expr::Literal(ScalarValue::Binary(Some((*self).to_owned())), None) | |
| } | |
| } | |
| impl Literal for &[u8] { | |
| fn lit(&self) -> Expr { | |
| - Expr::Literal(ScalarValue::Binary(Some((*self).to_owned()))) | |
| + Expr::Literal(ScalarValue::Binary(Some((*self).to_owned())), None) | |
| } | |
| } | |
| impl Literal for ScalarValue { | |
| fn lit(&self) -> Expr { | |
| - Expr::Literal(self.clone()) | |
| + Expr::Literal(self.clone(), None) | |
| } | |
| } | |
| macro_rules! make_literal { | |
| #[doc = $DOC] | |
| impl Literal for $TYPE { | |
| fn lit(&self) -> Expr { | |
| - Expr::Literal(ScalarValue::$SCALAR(Some(self.clone()))) | |
| + Expr::Literal(ScalarValue::$SCALAR(Some(self.clone())), None) | |
| } | |
| } | |
| }; | |
| macro_rules! make_nonzero_literal { | |
| #[doc = $DOC] | |
| impl Literal for $TYPE { | |
| fn lit(&self) -> Expr { | |
| - Expr::Literal(ScalarValue::$SCALAR(Some(self.get()))) | |
| + Expr::Literal(ScalarValue::$SCALAR(Some(self.get())), None) | |
| } | |
| } | |
| }; | |
| macro_rules! make_timestamp_literal { | |
| #[doc = $DOC] | |
| impl TimestampLiteral for $TYPE { | |
| fn lit_timestamp_nano(&self) -> Expr { | |
| - Expr::Literal(ScalarValue::TimestampNanosecond( | |
| - Some((self.clone()).into()), | |
| + Expr::Literal( | |
| + ScalarValue::TimestampNanosecond(Some((self.clone()).into()), None), | |
| None, | |
| - )) | |
| + ) | |
| } | |
| } | |
| }; | |
| diff --git a/datafusion/expr/src/logical_plan/builder.rs b/datafusion/expr/src/logical_plan/builder.rs | |
| index f75e79cd6..533e81e64 100644 | |
| --- a/datafusion/expr/src/logical_plan/builder.rs | |
| +++ b/datafusion/expr/src/logical_plan/builder.rs | |
| impl LogicalPlanBuilder { | |
| // wrap cast if data type is not same as common type. | |
| for row in &mut values { | |
| for (j, field_type) in fields.iter().map(|f| f.data_type()).enumerate() { | |
| - if let Expr::Literal(ScalarValue::Null) = row[j] { | |
| - row[j] = Expr::Literal(ScalarValue::try_from(field_type)?); | |
| + if let Expr::Literal(ScalarValue::Null, metadata) = &row[j] { | |
| + row[j] = Expr::Literal( | |
| + ScalarValue::try_from(field_type)?, | |
| + metadata.clone(), | |
| + ); | |
| } else { | |
| row[j] = std::mem::take(&mut row[j]).cast_to(field_type, schema)?; | |
| } | |
| diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs | |
| index 691f5684a..5bc07cf62 100644 | |
| --- a/datafusion/expr/src/logical_plan/plan.rs | |
| +++ b/datafusion/expr/src/logical_plan/plan.rs | |
| impl LogicalPlan { | |
| // Empty group_expr will return Some(1) | |
| if group_expr | |
| .iter() | |
| - .all(|expr| matches!(expr, Expr::Literal(_))) | |
| + .all(|expr| matches!(expr, Expr::Literal(_, _))) | |
| { | |
| Some(1) | |
| } else { | |
| impl LogicalPlan { | |
| let transformed_expr = e.transform_up(|e| { | |
| if let Expr::Placeholder(Placeholder { id, .. }) = e { | |
| let value = param_values.get_placeholders_with_values(&id)?; | |
| - Ok(Transformed::yes(Expr::Literal(value))) | |
| + Ok(Transformed::yes(Expr::Literal(value, None))) | |
| } else { | |
| Ok(Transformed::no(e)) | |
| } | |
| impl Union { | |
| { | |
| expr.push(Expr::Column(column)); | |
| } else { | |
| - expr.push(Expr::Literal(ScalarValue::Null).alias(column.name())); | |
| + expr.push( | |
| + Expr::Literal(ScalarValue::Null, None).alias(column.name()), | |
| + ); | |
| } | |
| } | |
| wrapped_inputs.push(Arc::new(LogicalPlan::Projection( | |
| impl Limit { | |
| pub fn get_skip_type(&self) -> Result<SkipType> { | |
| match self.skip.as_deref() { | |
| Some(expr) => match *expr { | |
| - Expr::Literal(ScalarValue::Int64(s)) => { | |
| + Expr::Literal(ScalarValue::Int64(s), _) => { | |
| // `skip = NULL` is equivalent to `skip = 0` | |
| let s = s.unwrap_or(0); | |
| if s >= 0 { | |
| impl Limit { | |
| pub fn get_fetch_type(&self) -> Result<FetchType> { | |
| match self.fetch.as_deref() { | |
| Some(expr) => match *expr { | |
| - Expr::Literal(ScalarValue::Int64(Some(s))) => { | |
| + Expr::Literal(ScalarValue::Int64(Some(s)), _) => { | |
| if s >= 0 { | |
| Ok(FetchType::Literal(Some(s as usize))) | |
| } else { | |
| plan_err!("LIMIT must be >= 0, '{}' was provided", s) | |
| } | |
| } | |
| - Expr::Literal(ScalarValue::Int64(None)) => Ok(FetchType::Literal(None)), | |
| + Expr::Literal(ScalarValue::Int64(None), _) => { | |
| + Ok(FetchType::Literal(None)) | |
| + } | |
| _ => Ok(FetchType::UnsupportedExpr), | |
| }, | |
| None => Ok(FetchType::Literal(None)), | |
| mod tests { | |
| let col = schema.field_names()[0].clone(); | |
| let filter = Filter::try_new( | |
| - Expr::Column(col.into()).eq(Expr::Literal(ScalarValue::Int32(Some(1)))), | |
| + Expr::Column(col.into()).eq(Expr::Literal(ScalarValue::Int32(Some(1)), None)), | |
| scan, | |
| ) | |
| .unwrap(); | |
| mod tests { | |
| skip: None, | |
| fetch: Some(Box::new(Expr::Literal( | |
| ScalarValue::new_ten(&DataType::UInt32).unwrap(), | |
| + None, | |
| ))), | |
| input: Arc::clone(&input), | |
| }), | |
| LogicalPlan::Limit(Limit { | |
| skip: Some(Box::new(Expr::Literal( | |
| ScalarValue::new_ten(&DataType::UInt32).unwrap(), | |
| + None, | |
| ))), | |
| fetch: None, | |
| input: Arc::clone(&input), | |
| mod tests { | |
| LogicalPlan::Limit(Limit { | |
| skip: Some(Box::new(Expr::Literal( | |
| ScalarValue::new_one(&DataType::UInt32).unwrap(), | |
| + None, | |
| ))), | |
| fetch: Some(Box::new(Expr::Literal( | |
| ScalarValue::new_ten(&DataType::UInt32).unwrap(), | |
| + None, | |
| ))), | |
| input, | |
| }), | |
| diff --git a/datafusion/expr/src/tree_node.rs b/datafusion/expr/src/tree_node.rs | |
| index bfdc19394..f953aec5a 100644 | |
| --- a/datafusion/expr/src/tree_node.rs | |
| +++ b/datafusion/expr/src/tree_node.rs | |
| impl TreeNode for Expr { | |
| // Treat OuterReferenceColumn as a leaf expression | |
| | Expr::OuterReferenceColumn(_, _) | |
| | Expr::ScalarVariable(_, _) | |
| - | Expr::Literal(_) | |
| + | Expr::Literal(_, _) | |
| | Expr::Exists { .. } | |
| | Expr::ScalarSubquery(_) | |
| | Expr::Wildcard { .. } | |
| impl TreeNode for Expr { | |
| | Expr::Exists { .. } | |
| | Expr::ScalarSubquery(_) | |
| | Expr::ScalarVariable(_, _) | |
| - | Expr::Literal(_) => Transformed::no(self), | |
| + | Expr::Literal(_, _) => Transformed::no(self), | |
| Expr::Unnest(Unnest { expr, .. }) => expr | |
| .map_elements(f)? | |
| .update_data(|expr| Expr::Unnest(Unnest { expr })), | |
| diff --git a/datafusion/expr/src/utils.rs b/datafusion/expr/src/utils.rs | |
| index 6f44e37d0..b7851e530 100644 | |
| --- a/datafusion/expr/src/utils.rs | |
| +++ b/datafusion/expr/src/utils.rs | |
| pub fn expr_to_columns(expr: &Expr, accum: &mut HashSet<Column>) -> Result<()> { | |
| Expr::Unnest(_) | |
| | Expr::ScalarVariable(_, _) | |
| | Expr::Alias(_) | |
| - | Expr::Literal(_) | |
| + | Expr::Literal(_, _) | |
| | Expr::BinaryExpr { .. } | |
| | Expr::Like { .. } | |
| | Expr::SimilarTo { .. } | |
| pub(crate) fn find_column_indexes_referenced_by_expr( | |
| indexes.push(idx); | |
| } | |
| } | |
| - Expr::Literal(_) => { | |
| + Expr::Literal(_, _) => { | |
| indexes.push(usize::MAX); | |
| } | |
| _ => {} | |
| diff --git a/datafusion/ffi/src/udtf.rs b/datafusion/ffi/src/udtf.rs | |
| index 08bc4d0cd..ceedec259 100644 | |
| --- a/datafusion/ffi/src/udtf.rs | |
| +++ b/datafusion/ffi/src/udtf.rs | |
| mod tests { | |
| let args = args | |
| .iter() | |
| .map(|arg| { | |
| - if let Expr::Literal(scalar) = arg { | |
| + if let Expr::Literal(scalar, _) = arg { | |
| Ok(scalar) | |
| } else { | |
| exec_err!("Expected only literal arguments to table udf") | |
| diff --git a/datafusion/functions-aggregate/src/count.rs b/datafusion/functions-aggregate/src/count.rs | |
| index f375a68d9..6b7199c44 100644 | |
| --- a/datafusion/functions-aggregate/src/count.rs | |
| +++ b/datafusion/functions-aggregate/src/count.rs | |
| pub fn count_distinct(expr: Expr) -> Expr { | |
| /// let expr = col(expr.schema_name().to_string()); | |
| /// ``` | |
| pub fn count_all() -> Expr { | |
| - count(Expr::Literal(COUNT_STAR_EXPANSION)).alias("count(*)") | |
| + count(Expr::Literal(COUNT_STAR_EXPANSION, None)).alias("count(*)") | |
| } | |
| /// Creates window aggregation to count all rows. | |
| pub fn count_all() -> Expr { | |
| pub fn count_all_window() -> Expr { | |
| Expr::from(WindowFunction::new( | |
| WindowFunctionDefinition::AggregateUDF(count_udaf()), | |
| - vec![Expr::Literal(COUNT_STAR_EXPANSION)], | |
| + vec![Expr::Literal(COUNT_STAR_EXPANSION, None)], | |
| )) | |
| } | |
| diff --git a/datafusion/functions-aggregate/src/planner.rs b/datafusion/functions-aggregate/src/planner.rs | |
| index c8cb84118..f0e37f6b1 100644 | |
| --- a/datafusion/functions-aggregate/src/planner.rs | |
| +++ b/datafusion/functions-aggregate/src/planner.rs | |
| impl ExprPlanner for AggregateFunctionPlanner { | |
| let new_expr = Expr::AggregateFunction(AggregateFunction::new_udf( | |
| func, | |
| - vec![Expr::Literal(COUNT_STAR_EXPANSION)], | |
| + vec![Expr::Literal(COUNT_STAR_EXPANSION, None)], | |
| distinct, | |
| filter, | |
| order_by, | |
| diff --git a/datafusion/functions-nested/benches/map.rs b/datafusion/functions-nested/benches/map.rs | |
| index a752a47bc..55dd7ad14 100644 | |
| --- a/datafusion/functions-nested/benches/map.rs | |
| +++ b/datafusion/functions-nested/benches/map.rs | |
| fn criterion_benchmark(c: &mut Criterion) { | |
| let values = values(&mut rng); | |
| let mut buffer = Vec::new(); | |
| for i in 0..1000 { | |
| - buffer.push(Expr::Literal(ScalarValue::Utf8(Some(keys[i].clone())))); | |
| - buffer.push(Expr::Literal(ScalarValue::Int32(Some(values[i])))); | |
| + buffer.push(Expr::Literal( | |
| + ScalarValue::Utf8(Some(keys[i].clone())), | |
| + None, | |
| + )); | |
| + buffer.push(Expr::Literal(ScalarValue::Int32(Some(values[i])), None)); | |
| } | |
| let planner = NestedFunctionPlanner {}; | |
| diff --git a/datafusion/functions-nested/src/array_has.rs b/datafusion/functions-nested/src/array_has.rs | |
| index 5ef149131..3b9b705e7 100644 | |
| --- a/datafusion/functions-nested/src/array_has.rs | |
| +++ b/datafusion/functions-nested/src/array_has.rs | |
| impl ScalarUDFImpl for ArrayHas { | |
| // if the haystack is a constant list, we can use an inlist expression which is more | |
| // efficient because the haystack is not varying per-row | |
| - if let Expr::Literal(ScalarValue::List(array)) = haystack { | |
| + if let Expr::Literal(ScalarValue::List(array), _) = haystack { | |
| // TODO: support LargeList | |
| // (not supported by `convert_array_to_scalar_vec`) | |
| // (FixedSizeList not supported either, but seems to have worked fine when attempting to | |
| impl ScalarUDFImpl for ArrayHas { | |
| let list = scalar_values | |
| .into_iter() | |
| .flatten() | |
| - .map(Expr::Literal) | |
| + .map(|v| Expr::Literal(v, None)) | |
| .collect(); | |
| return Ok(ExprSimplifyResult::Simplified(Expr::InList(InList { | |
| diff --git a/datafusion/functions-table/src/generate_series.rs b/datafusion/functions-table/src/generate_series.rs | |
| index ee95567ab..ffb93cf59 100644 | |
| --- a/datafusion/functions-table/src/generate_series.rs | |
| +++ b/datafusion/functions-table/src/generate_series.rs | |
| impl TableFunctionImpl for GenerateSeriesFuncImpl { | |
| let mut normalize_args = Vec::new(); | |
| for expr in exprs { | |
| match expr { | |
| - Expr::Literal(ScalarValue::Null) => {} | |
| - Expr::Literal(ScalarValue::Int64(Some(n))) => normalize_args.push(*n), | |
| + Expr::Literal(ScalarValue::Null, _) => {} | |
| + Expr::Literal(ScalarValue::Int64(Some(n)), _) => normalize_args.push(*n), | |
| _ => return plan_err!("First argument must be an integer literal"), | |
| }; | |
| } | |
| diff --git a/datafusion/functions-window/src/planner.rs b/datafusion/functions-window/src/planner.rs | |
| index 8fca0114f..091737bb9 100644 | |
| --- a/datafusion/functions-window/src/planner.rs | |
| +++ b/datafusion/functions-window/src/planner.rs | |
| impl ExprPlanner for WindowFunctionPlanner { | |
| let new_expr = Expr::from(WindowFunction::new( | |
| func_def, | |
| - vec![Expr::Literal(COUNT_STAR_EXPANSION)], | |
| + vec![Expr::Literal(COUNT_STAR_EXPANSION, None)], | |
| )) | |
| .partition_by(partition_by) | |
| .order_by(order_by) | |
| diff --git a/datafusion/functions/src/core/arrow_cast.rs b/datafusion/functions/src/core/arrow_cast.rs | |
| index 2d769dfa5..e9dee09e7 100644 | |
| --- a/datafusion/functions/src/core/arrow_cast.rs | |
| +++ b/datafusion/functions/src/core/arrow_cast.rs | |
| impl ScalarUDFImpl for ArrowCastFunc { | |
| fn data_type_from_args(args: &[Expr]) -> Result<DataType> { | |
| let [_, type_arg] = take_function_args("arrow_cast", args)?; | |
| - let Expr::Literal(ScalarValue::Utf8(Some(val))) = type_arg else { | |
| + let Expr::Literal(ScalarValue::Utf8(Some(val)), _) = type_arg else { | |
| return exec_err!( | |
| "arrow_cast requires its second argument to be a constant string, got {:?}", | |
| type_arg | |
| diff --git a/datafusion/functions/src/core/getfield.rs b/datafusion/functions/src/core/getfield.rs | |
| index de87308ef..2f3913287 100644 | |
| --- a/datafusion/functions/src/core/getfield.rs | |
| +++ b/datafusion/functions/src/core/getfield.rs | |
| impl ScalarUDFImpl for GetFieldFunc { | |
| let [base, field_name] = take_function_args(self.name(), args)?; | |
| let name = match field_name { | |
| - Expr::Literal(name) => name, | |
| + Expr::Literal(name, _) => name, | |
| other => &ScalarValue::Utf8(Some(other.schema_name().to_string())), | |
| }; | |
| impl ScalarUDFImpl for GetFieldFunc { | |
| fn schema_name(&self, args: &[Expr]) -> Result<String> { | |
| let [base, field_name] = take_function_args(self.name(), args)?; | |
| let name = match field_name { | |
| - Expr::Literal(name) => name, | |
| + Expr::Literal(name, _) => name, | |
| other => &ScalarValue::Utf8(Some(other.schema_name().to_string())), | |
| }; | |
| diff --git a/datafusion/functions/src/datetime/current_date.rs b/datafusion/functions/src/datetime/current_date.rs | |
| index 9998e7d37..2bda1f262 100644 | |
| --- a/datafusion/functions/src/datetime/current_date.rs | |
| +++ b/datafusion/functions/src/datetime/current_date.rs | |
| impl ScalarUDFImpl for CurrentDateFunc { | |
| ); | |
| Ok(ExprSimplifyResult::Simplified(Expr::Literal( | |
| ScalarValue::Date32(days), | |
| + None, | |
| ))) | |
| } | |
| diff --git a/datafusion/functions/src/datetime/current_time.rs b/datafusion/functions/src/datetime/current_time.rs | |
| index c416d0240..9b9d3997e 100644 | |
| --- a/datafusion/functions/src/datetime/current_time.rs | |
| +++ b/datafusion/functions/src/datetime/current_time.rs | |
| impl ScalarUDFImpl for CurrentTimeFunc { | |
| let nano = now_ts.timestamp_nanos_opt().map(|ts| ts % 86400000000000); | |
| Ok(ExprSimplifyResult::Simplified(Expr::Literal( | |
| ScalarValue::Time64Nanosecond(nano), | |
| + None, | |
| ))) | |
| } | |
| diff --git a/datafusion/functions/src/datetime/now.rs b/datafusion/functions/src/datetime/now.rs | |
| index 30b4d4ca9..ffb3aed5a 100644 | |
| --- a/datafusion/functions/src/datetime/now.rs | |
| +++ b/datafusion/functions/src/datetime/now.rs | |
| impl ScalarUDFImpl for NowFunc { | |
| .timestamp_nanos_opt(); | |
| Ok(ExprSimplifyResult::Simplified(Expr::Literal( | |
| ScalarValue::TimestampNanosecond(now_ts, Some("+00:00".into())), | |
| + None, | |
| ))) | |
| } | |
| diff --git a/datafusion/functions/src/math/log.rs b/datafusion/functions/src/math/log.rs | |
| index ee52c035a..23e267a32 100644 | |
| --- a/datafusion/functions/src/math/log.rs | |
| +++ b/datafusion/functions/src/math/log.rs | |
| impl ScalarUDFImpl for LogFunc { | |
| }; | |
| match number { | |
| - Expr::Literal(value) if value == ScalarValue::new_one(&number_datatype)? => { | |
| + Expr::Literal(value, _) | |
| + if value == ScalarValue::new_one(&number_datatype)? => | |
| + { | |
| Ok(ExprSimplifyResult::Simplified(lit(ScalarValue::new_zero( | |
| &info.get_data_type(&base)?, | |
| )?))) | |
| diff --git a/datafusion/functions/src/math/power.rs b/datafusion/functions/src/math/power.rs | |
| index bd1ae7c31..465844704 100644 | |
| --- a/datafusion/functions/src/math/power.rs | |
| +++ b/datafusion/functions/src/math/power.rs | |
| impl ScalarUDFImpl for PowerFunc { | |
| let exponent_type = info.get_data_type(&exponent)?; | |
| match exponent { | |
| - Expr::Literal(value) if value == ScalarValue::new_zero(&exponent_type)? => { | |
| + Expr::Literal(value, _) | |
| + if value == ScalarValue::new_zero(&exponent_type)? => | |
| + { | |
| Ok(ExprSimplifyResult::Simplified(Expr::Literal( | |
| ScalarValue::new_one(&info.get_data_type(&base)?)?, | |
| + None, | |
| ))) | |
| } | |
| - Expr::Literal(value) if value == ScalarValue::new_one(&exponent_type)? => { | |
| + Expr::Literal(value, _) if value == ScalarValue::new_one(&exponent_type)? => { | |
| Ok(ExprSimplifyResult::Simplified(base)) | |
| } | |
| Expr::ScalarFunction(ScalarFunction { func, mut args }) | |
| diff --git a/datafusion/functions/src/string/concat.rs b/datafusion/functions/src/string/concat.rs | |
| index 773c31642..64a527eac 100644 | |
| --- a/datafusion/functions/src/string/concat.rs | |
| +++ b/datafusion/functions/src/string/concat.rs | |
| pub fn simplify_concat(args: Vec<Expr>) -> Result<ExprSimplifyResult> { | |
| let data_types: Vec<_> = args | |
| .iter() | |
| .filter_map(|expr| match expr { | |
| - Expr::Literal(l) => Some(l.data_type()), | |
| + Expr::Literal(l, _) => Some(l.data_type()), | |
| _ => None, | |
| }) | |
| .collect(); | |
| pub fn simplify_concat(args: Vec<Expr>) -> Result<ExprSimplifyResult> { | |
| for arg in args.clone() { | |
| match arg { | |
| - Expr::Literal(ScalarValue::Utf8(None)) => {} | |
| - Expr::Literal(ScalarValue::LargeUtf8(None)) => { | |
| + Expr::Literal(ScalarValue::Utf8(None), _) => {} | |
| + Expr::Literal(ScalarValue::LargeUtf8(None), _) => { | |
| } | |
| - Expr::Literal(ScalarValue::Utf8View(None)) => { } | |
| + Expr::Literal(ScalarValue::Utf8View(None), _) => { } | |
| // filter out `null` args | |
| // All literals have been converted to Utf8 or LargeUtf8 in type_coercion. | |
| // Concatenate it with the `contiguous_scalar`. | |
| - Expr::Literal(ScalarValue::Utf8(Some(v))) => { | |
| + Expr::Literal(ScalarValue::Utf8(Some(v)), _) => { | |
| contiguous_scalar += &v; | |
| } | |
| - Expr::Literal(ScalarValue::LargeUtf8(Some(v))) => { | |
| + Expr::Literal(ScalarValue::LargeUtf8(Some(v)), _) => { | |
| contiguous_scalar += &v; | |
| } | |
| - Expr::Literal(ScalarValue::Utf8View(Some(v))) => { | |
| + Expr::Literal(ScalarValue::Utf8View(Some(v)), _) => { | |
| contiguous_scalar += &v; | |
| } | |
| - Expr::Literal(x) => { | |
| + Expr::Literal(x, _) => { | |
| return internal_err!( | |
| "The scalar {x} should be casted to string type during the type coercion." | |
| ) | |
| diff --git a/datafusion/functions/src/string/concat_ws.rs b/datafusion/functions/src/string/concat_ws.rs | |
| index 2a2f9429f..1f45f8501 100644 | |
| --- a/datafusion/functions/src/string/concat_ws.rs | |
| +++ b/datafusion/functions/src/string/concat_ws.rs | |
| fn simplify_concat_ws(delimiter: &Expr, args: &[Expr]) -> Result<ExprSimplifyRes | |
| ScalarValue::Utf8(delimiter) | |
| | ScalarValue::LargeUtf8(delimiter) | |
| | ScalarValue::Utf8View(delimiter), | |
| + _, | |
| ) => { | |
| match delimiter { | |
| // when the delimiter is an empty string, | |
| fn simplify_concat_ws(delimiter: &Expr, args: &[Expr]) -> Result<ExprSimplifyRes | |
| for arg in args { | |
| match arg { | |
| // filter out null args | |
| - Expr::Literal(ScalarValue::Utf8(None) | ScalarValue::LargeUtf8(None) | ScalarValue::Utf8View(None)) => {} | |
| - Expr::Literal(ScalarValue::Utf8(Some(v)) | ScalarValue::LargeUtf8(Some(v)) | ScalarValue::Utf8View(Some(v))) => { | |
| + Expr::Literal(ScalarValue::Utf8(None) | ScalarValue::LargeUtf8(None) | ScalarValue::Utf8View(None), _) => {} | |
| + Expr::Literal(ScalarValue::Utf8(Some(v)) | ScalarValue::LargeUtf8(Some(v)) | ScalarValue::Utf8View(Some(v)), _) => { | |
| match contiguous_scalar { | |
| None => contiguous_scalar = Some(v.to_string()), | |
| Some(mut pre) => { | |
| fn simplify_concat_ws(delimiter: &Expr, args: &[Expr]) -> Result<ExprSimplifyRes | |
| } | |
| } | |
| } | |
| - Expr::Literal(s) => return internal_err!("The scalar {s} should be casted to string type during the type coercion."), | |
| + Expr::Literal(s, _) => return internal_err!("The scalar {s} should be casted to string type during the type coercion."), | |
| // If the arg is not a literal, we should first push the current `contiguous_scalar` | |
| // to the `new_args` and reset it to None. | |
| // Then pushing this arg to the `new_args`. | |
| fn simplify_concat_ws(delimiter: &Expr, args: &[Expr]) -> Result<ExprSimplifyRes | |
| // if the delimiter is null, then the value of the whole expression is null. | |
| None => Ok(ExprSimplifyResult::Simplified(Expr::Literal( | |
| ScalarValue::Utf8(None), | |
| + None, | |
| ))), | |
| } | |
| } | |
| - Expr::Literal(d) => internal_err!( | |
| + Expr::Literal(d, _) => internal_err!( | |
| "The scalar {d} should be casted to string type during the type coercion." | |
| ), | |
| _ => { | |
| fn simplify_concat_ws(delimiter: &Expr, args: &[Expr]) -> Result<ExprSimplifyRes | |
| fn is_null(expr: &Expr) -> bool { | |
| match expr { | |
| - Expr::Literal(v) => v.is_null(), | |
| + Expr::Literal(v, _) => v.is_null(), | |
| _ => false, | |
| } | |
| } | |
| diff --git a/datafusion/functions/src/string/contains.rs b/datafusion/functions/src/string/contains.rs | |
| index b74be1546..215f8f7a2 100644 | |
| --- a/datafusion/functions/src/string/contains.rs | |
| +++ b/datafusion/functions/src/string/contains.rs | |
| mod test { | |
| #[test] | |
| fn test_contains_api() { | |
| let expr = contains( | |
| - Expr::Literal(ScalarValue::Utf8(Some("the quick brown fox".to_string()))), | |
| - Expr::Literal(ScalarValue::Utf8(Some("row".to_string()))), | |
| + Expr::Literal( | |
| + ScalarValue::Utf8(Some("the quick brown fox".to_string())), | |
| + None, | |
| + ), | |
| + Expr::Literal(ScalarValue::Utf8(Some("row".to_string())), None), | |
| ); | |
| assert_eq!( | |
| expr.to_string(), | |
| diff --git a/datafusion/functions/src/string/starts_with.rs b/datafusion/functions/src/string/starts_with.rs | |
| index a59d7080a..ecab1af13 100644 | |
| --- a/datafusion/functions/src/string/starts_with.rs | |
| +++ b/datafusion/functions/src/string/starts_with.rs | |
| impl ScalarUDFImpl for StartsWithFunc { | |
| args: Vec<Expr>, | |
| info: &dyn SimplifyInfo, | |
| ) -> Result<ExprSimplifyResult> { | |
| - if let Expr::Literal(scalar_value) = &args[1] { | |
| + if let Expr::Literal(scalar_value, _) = &args[1] { | |
| // Convert starts_with(col, 'prefix') to col LIKE 'prefix%' with proper escaping | |
| // Example: starts_with(col, 'ja%') -> col LIKE 'ja\%%' | |
| // 1. 'ja%' (input pattern) | |
| impl ScalarUDFImpl for StartsWithFunc { | |
| | ScalarValue::Utf8View(Some(pattern)) => { | |
| let escaped_pattern = pattern.replace("%", "\\%"); | |
| let like_pattern = format!("{escaped_pattern}%"); | |
| - Expr::Literal(ScalarValue::Utf8(Some(like_pattern))) | |
| + Expr::Literal(ScalarValue::Utf8(Some(like_pattern)), None) | |
| } | |
| _ => return Ok(ExprSimplifyResult::Original(args)), | |
| }; | |
| diff --git a/datafusion/optimizer/benches/projection_unnecessary.rs b/datafusion/optimizer/benches/projection_unnecessary.rs | |
| index ee7889eb3..c9f248fe4 100644 | |
| --- a/datafusion/optimizer/benches/projection_unnecessary.rs | |
| +++ b/datafusion/optimizer/benches/projection_unnecessary.rs | |
| fn is_projection_unnecessary_old( | |
| // First check if all expressions are trivial (cheaper operation than `projection_schema`) | |
| if !proj_exprs | |
| .iter() | |
| - .all(|expr| matches!(expr, Expr::Column(_) | Expr::Literal(_))) | |
| + .all(|expr| matches!(expr, Expr::Column(_) | Expr::Literal(_, _))) | |
| { | |
| return Ok(false); | |
| } | |
| diff --git a/datafusion/optimizer/src/analyzer/resolve_grouping_function.rs b/datafusion/optimizer/src/analyzer/resolve_grouping_function.rs | |
| index f8a818563..fa7ff1b8b 100644 | |
| --- a/datafusion/optimizer/src/analyzer/resolve_grouping_function.rs | |
| +++ b/datafusion/optimizer/src/analyzer/resolve_grouping_function.rs | |
| fn grouping_function_on_id( | |
| // Postgres allows grouping function for group by without grouping sets, the result is then | |
| // always 0 | |
| if !is_grouping_set { | |
| - return Ok(Expr::Literal(ScalarValue::from(0i32))); | |
| + return Ok(Expr::Literal(ScalarValue::from(0i32), None)); | |
| } | |
| let group_by_expr_count = group_by_expr.len(); | |
| let literal = |value: usize| { | |
| if group_by_expr_count < 8 { | |
| - Expr::Literal(ScalarValue::from(value as u8)) | |
| + Expr::Literal(ScalarValue::from(value as u8), None) | |
| } else if group_by_expr_count < 16 { | |
| - Expr::Literal(ScalarValue::from(value as u16)) | |
| + Expr::Literal(ScalarValue::from(value as u16), None) | |
| } else if group_by_expr_count < 32 { | |
| - Expr::Literal(ScalarValue::from(value as u32)) | |
| + Expr::Literal(ScalarValue::from(value as u32), None) | |
| } else { | |
| - Expr::Literal(ScalarValue::from(value as u64)) | |
| + Expr::Literal(ScalarValue::from(value as u64), None) | |
| } | |
| }; | |
| diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs | |
| index 703498295..b5a3e9a2d 100644 | |
| --- a/datafusion/optimizer/src/analyzer/type_coercion.rs | |
| +++ b/datafusion/optimizer/src/analyzer/type_coercion.rs | |
| impl TreeNodeRewriter for TypeCoercionRewriter<'_> { | |
| Expr::Alias(_) | |
| | Expr::Column(_) | |
| | Expr::ScalarVariable(_, _) | |
| - | Expr::Literal(_) | |
| + | Expr::Literal(_, _) | |
| | Expr::SimilarTo(_) | |
| | Expr::IsNotNull(_) | |
| | Expr::IsNull(_) | |
| diff --git a/datafusion/optimizer/src/decorrelate.rs b/datafusion/optimizer/src/decorrelate.rs | |
| index 1378b53fa..632367877 100644 | |
| --- a/datafusion/optimizer/src/decorrelate.rs | |
| +++ b/datafusion/optimizer/src/decorrelate.rs | |
| fn agg_exprs_evaluation_result_on_empty_batch( | |
| let new_expr = match expr { | |
| Expr::AggregateFunction(expr::AggregateFunction { func, .. }) => { | |
| if func.name() == "count" { | |
| - Transformed::yes(Expr::Literal(ScalarValue::Int64(Some(0)))) | |
| + Transformed::yes(Expr::Literal( | |
| + ScalarValue::Int64(Some(0)), | |
| + None, | |
| + )) | |
| } else { | |
| - Transformed::yes(Expr::Literal(ScalarValue::Null)) | |
| + Transformed::yes(Expr::Literal(ScalarValue::Null, None)) | |
| } | |
| } | |
| _ => Transformed::no(expr), | |
| fn filter_exprs_evaluation_result_on_empty_batch( | |
| let result_expr = simplifier.simplify(result_expr)?; | |
| match &result_expr { | |
| // evaluate to false or null on empty batch, no need to pull up | |
| - Expr::Literal(ScalarValue::Null) | |
| - | Expr::Literal(ScalarValue::Boolean(Some(false))) => None, | |
| + Expr::Literal(ScalarValue::Null, _) | |
| + | Expr::Literal(ScalarValue::Boolean(Some(false)), _) => None, | |
| // evaluate to true on empty batch, need to pull up the expr | |
| - Expr::Literal(ScalarValue::Boolean(Some(true))) => { | |
| + Expr::Literal(ScalarValue::Boolean(Some(true)), _) => { | |
| for (name, exprs) in input_expr_result_map_for_count_bug { | |
| expr_result_map_for_count_bug.insert(name.clone(), exprs.clone()); | |
| } | |
| fn filter_exprs_evaluation_result_on_empty_batch( | |
| Box::new(result_expr.clone()), | |
| Box::new(input_expr.clone()), | |
| )], | |
| - else_expr: Some(Box::new(Expr::Literal(ScalarValue::Null))), | |
| + else_expr: Some(Box::new(Expr::Literal(ScalarValue::Null, None))), | |
| }); | |
| let expr_key = new_expr.schema_name().to_string(); | |
| expr_result_map_for_count_bug.insert(expr_key, new_expr); | |
| diff --git a/datafusion/optimizer/src/eliminate_filter.rs b/datafusion/optimizer/src/eliminate_filter.rs | |
| index 452df6e83..e28771be5 100644 | |
| --- a/datafusion/optimizer/src/eliminate_filter.rs | |
| +++ b/datafusion/optimizer/src/eliminate_filter.rs | |
| impl OptimizerRule for EliminateFilter { | |
| ) -> Result<Transformed<LogicalPlan>> { | |
| match plan { | |
| LogicalPlan::Filter(Filter { | |
| - predicate: Expr::Literal(ScalarValue::Boolean(v)), | |
| + predicate: Expr::Literal(ScalarValue::Boolean(v), _), | |
| input, | |
| .. | |
| }) => match v { | |
| mod tests { | |
| #[test] | |
| fn filter_null() -> Result<()> { | |
| - let filter_expr = Expr::Literal(ScalarValue::Boolean(None)); | |
| + let filter_expr = Expr::Literal(ScalarValue::Boolean(None), None); | |
| let table_scan = test_table_scan().unwrap(); | |
| let plan = LogicalPlanBuilder::from(table_scan) | |
| diff --git a/datafusion/optimizer/src/eliminate_group_by_constant.rs b/datafusion/optimizer/src/eliminate_group_by_constant.rs | |
| index 604f083b3..9c47ce024 100644 | |
| --- a/datafusion/optimizer/src/eliminate_group_by_constant.rs | |
| +++ b/datafusion/optimizer/src/eliminate_group_by_constant.rs | |
| fn is_constant_expression(expr: &Expr) -> bool { | |
| Expr::BinaryExpr(e) => { | |
| is_constant_expression(&e.left) && is_constant_expression(&e.right) | |
| } | |
| - Expr::Literal(_) => true, | |
| + Expr::Literal(_, _) => true, | |
| Expr::ScalarFunction(e) => { | |
| matches!( | |
| e.func.signature().volatility, | |
| diff --git a/datafusion/optimizer/src/eliminate_join.rs b/datafusion/optimizer/src/eliminate_join.rs | |
| index 2aad889b2..dfc3a220d 100644 | |
| --- a/datafusion/optimizer/src/eliminate_join.rs | |
| +++ b/datafusion/optimizer/src/eliminate_join.rs | |
| impl OptimizerRule for EliminateJoin { | |
| match plan { | |
| LogicalPlan::Join(join) if join.join_type == Inner && join.on.is_empty() => { | |
| match join.filter { | |
| - Some(Expr::Literal(ScalarValue::Boolean(Some(false)))) => Ok( | |
| + Some(Expr::Literal(ScalarValue::Boolean(Some(false)), _)) => Ok( | |
| Transformed::yes(LogicalPlan::EmptyRelation(EmptyRelation { | |
| produce_one_row: false, | |
| schema: join.schema, | |
| diff --git a/datafusion/optimizer/src/optimize_projections/mod.rs b/datafusion/optimizer/src/optimize_projections/mod.rs | |
| index ba583a8d7..d0457e709 100644 | |
| --- a/datafusion/optimizer/src/optimize_projections/mod.rs | |
| +++ b/datafusion/optimizer/src/optimize_projections/mod.rs | |
| fn merge_consecutive_projections(proj: Projection) -> Result<Transformed<Project | |
| // Check whether `expr` is trivial; i.e. it doesn't imply any computation. | |
| fn is_expr_trivial(expr: &Expr) -> bool { | |
| - matches!(expr, Expr::Column(_) | Expr::Literal(_)) | |
| + matches!(expr, Expr::Column(_) | Expr::Literal(_, _)) | |
| } | |
| /// Rewrites a projection expression using the projection before it (i.e. its input) | |
| fn is_expr_trivial(expr: &Expr) -> bool { | |
| fn rewrite_expr(expr: Expr, input: &Projection) -> Result<Transformed<Expr>> { | |
| expr.transform_up(|expr| { | |
| match expr { | |
| - // remove any intermediate aliases | |
| - Expr::Alias(alias) => Ok(Transformed::yes(*alias.expr)), | |
| + // remove any intermediate aliases if they do not carry metadata | |
| + Expr::Alias(alias) => { | |
| + match alias | |
| + .metadata | |
| + .as_ref() | |
| + .map(|h| h.is_empty()) | |
| + .unwrap_or(true) | |
| + { | |
| + true => Ok(Transformed::yes(*alias.expr)), | |
| + false => Ok(Transformed::no(Expr::Alias(alias))), | |
| + } | |
| + } | |
| Expr::Column(col) => { | |
| // Find index of column: | |
| let idx = input.schema.index_of_column(&col)?; | |
| diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs | |
| index 7c352031b..1c1996d6a 100644 | |
| --- a/datafusion/optimizer/src/push_down_filter.rs | |
| +++ b/datafusion/optimizer/src/push_down_filter.rs | |
| fn can_evaluate_as_join_condition(predicate: &Expr) -> Result<bool> { | |
| let mut is_evaluate = true; | |
| predicate.apply(|expr| match expr { | |
| Expr::Column(_) | |
| - | Expr::Literal(_) | |
| + | Expr::Literal(_, _) | |
| | Expr::Placeholder(_) | |
| | Expr::ScalarVariable(_, _) => Ok(TreeNodeRecursion::Jump), | |
| Expr::Exists { .. } | |
| diff --git a/datafusion/optimizer/src/scalar_subquery_to_join.rs b/datafusion/optimizer/src/scalar_subquery_to_join.rs | |
| index 897e07cb9..2f9a2f6bb 100644 | |
| --- a/datafusion/optimizer/src/scalar_subquery_to_join.rs | |
| +++ b/datafusion/optimizer/src/scalar_subquery_to_join.rs | |
| fn build_join( | |
| .join_on( | |
| sub_query_alias, | |
| JoinType::Left, | |
| - vec![Expr::Literal(ScalarValue::Boolean(Some(true)))], | |
| + vec![Expr::Literal(ScalarValue::Boolean(Some(true)), None)], | |
| )? | |
| .build()? | |
| } | |
| fn build_join( | |
| ), | |
| ( | |
| Box::new(Expr::Not(Box::new(filter.clone()))), | |
| - Box::new(Expr::Literal(ScalarValue::Null)), | |
| + Box::new(Expr::Literal(ScalarValue::Null, None)), | |
| ), | |
| ], | |
| else_expr: Some(Box::new(Expr::Column(Column::new_unqualified( | |
| diff --git a/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs b/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs | |
| index fa565a973..e91aea330 100644 | |
| --- a/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs | |
| +++ b/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs | |
| //! Expression simplification API | |
| use std::borrow::Cow; | |
| -use std::collections::HashSet; | |
| +use std::collections::{BTreeMap, HashSet}; | |
| use std::ops::Not; | |
| use arrow::{ | |
| impl TreeNodeRewriter for Canonicalizer { | |
| }))) | |
| } | |
| // <literal> <op> <col> | |
| - (Expr::Literal(_a), Expr::Column(_b), Some(swapped_op)) => { | |
| + (Expr::Literal(_a, _), Expr::Column(_b), Some(swapped_op)) => { | |
| Ok(Transformed::yes(Expr::BinaryExpr(BinaryExpr { | |
| left: right, | |
| op: swapped_op, | |
| struct ConstEvaluator<'a> { | |
| #[allow(clippy::large_enum_variant)] | |
| enum ConstSimplifyResult { | |
| // Expr was simplified and contains the new expression | |
| - Simplified(ScalarValue), | |
| + Simplified(ScalarValue, Option<BTreeMap<String, String>>), | |
| // Expr was not simplified and original value is returned | |
| - NotSimplified(ScalarValue), | |
| + NotSimplified(ScalarValue, Option<BTreeMap<String, String>>), | |
| // Evaluation encountered an error, contains the original expression | |
| SimplifyRuntimeError(DataFusionError, Expr), | |
| } | |
| impl TreeNodeRewriter for ConstEvaluator<'_> { | |
| // any error is countered during simplification, return the original | |
| // so that normal evaluation can occur | |
| Some(true) => match self.evaluate_to_scalar(expr) { | |
| - ConstSimplifyResult::Simplified(s) => { | |
| - Ok(Transformed::yes(Expr::Literal(s))) | |
| + ConstSimplifyResult::Simplified(s, m) => { | |
| + Ok(Transformed::yes(Expr::Literal(s, m))) | |
| } | |
| - ConstSimplifyResult::NotSimplified(s) => { | |
| - Ok(Transformed::no(Expr::Literal(s))) | |
| + ConstSimplifyResult::NotSimplified(s, m) => { | |
| + Ok(Transformed::no(Expr::Literal(s, m))) | |
| } | |
| ConstSimplifyResult::SimplifyRuntimeError(_, expr) => { | |
| Ok(Transformed::yes(expr)) | |
| impl<'a> ConstEvaluator<'a> { | |
| Expr::ScalarFunction(ScalarFunction { func, .. }) => { | |
| Self::volatility_ok(func.signature().volatility) | |
| } | |
| - Expr::Literal(_) | |
| + Expr::Literal(_, _) | |
| | Expr::Alias(..) | |
| | Expr::Unnest(_) | |
| | Expr::BinaryExpr { .. } | |
| impl<'a> ConstEvaluator<'a> { | |
| /// Internal helper to evaluates an Expr | |
| pub(crate) fn evaluate_to_scalar(&mut self, expr: Expr) -> ConstSimplifyResult { | |
| - if let Expr::Literal(s) = expr { | |
| - return ConstSimplifyResult::NotSimplified(s); | |
| + if let Expr::Literal(s, m) = expr { | |
| + return ConstSimplifyResult::NotSimplified(s, m); | |
| } | |
| let phys_expr = | |
| impl<'a> ConstEvaluator<'a> { | |
| Ok(e) => e, | |
| Err(err) => return ConstSimplifyResult::SimplifyRuntimeError(err, expr), | |
| }; | |
| + let metadata = phys_expr | |
| + .return_field(self.input_batch.schema_ref()) | |
| + .ok() | |
| + .and_then(|f| { | |
| + let m = f.metadata(); | |
| + match m.is_empty() { | |
| + true => None, | |
| + false => { | |
| + Some(m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()) | |
| + } | |
| + } | |
| + }); | |
| let col_val = match phys_expr.evaluate(&self.input_batch) { | |
| Ok(v) => v, | |
| Err(err) => return ConstSimplifyResult::SimplifyRuntimeError(err, expr), | |
| impl<'a> ConstEvaluator<'a> { | |
| expr, | |
| ) | |
| } else if as_list_array(&a).is_ok() { | |
| - ConstSimplifyResult::Simplified(ScalarValue::List( | |
| - a.as_list::<i32>().to_owned().into(), | |
| - )) | |
| + ConstSimplifyResult::Simplified( | |
| + ScalarValue::List(a.as_list::<i32>().to_owned().into()), | |
| + metadata, | |
| + ) | |
| } else if as_large_list_array(&a).is_ok() { | |
| - ConstSimplifyResult::Simplified(ScalarValue::LargeList( | |
| - a.as_list::<i64>().to_owned().into(), | |
| - )) | |
| + ConstSimplifyResult::Simplified( | |
| + ScalarValue::LargeList(a.as_list::<i64>().to_owned().into()), | |
| + metadata, | |
| + ) | |
| } else { | |
| // Non-ListArray | |
| match ScalarValue::try_from_array(&a, 0) { | |
| impl<'a> ConstEvaluator<'a> { | |
| expr, | |
| ) | |
| } else { | |
| - ConstSimplifyResult::Simplified(s) | |
| + ConstSimplifyResult::Simplified(s, metadata) | |
| } | |
| } | |
| Err(err) => ConstSimplifyResult::SimplifyRuntimeError(err, expr), | |
| impl<'a> ConstEvaluator<'a> { | |
| expr, | |
| ) | |
| } else { | |
| - ConstSimplifyResult::Simplified(s) | |
| + ConstSimplifyResult::Simplified(s, metadata) | |
| } | |
| } | |
| } | |
| impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> { | |
| && !info.get_data_type(&left)?.is_floating() | |
| && is_one(&right) => | |
| { | |
| - Transformed::yes(Expr::Literal(ScalarValue::new_zero( | |
| - &info.get_data_type(&left)?, | |
| - )?)) | |
| + Transformed::yes(Expr::Literal( | |
| + ScalarValue::new_zero(&info.get_data_type(&left)?)?, | |
| + None, | |
| + )) | |
| } | |
| // | |
| impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> { | |
| op: BitwiseAnd, | |
| right, | |
| }) if is_negative_of(&left, &right) && !info.nullable(&right)? => { | |
| - Transformed::yes(Expr::Literal(ScalarValue::new_zero( | |
| - &info.get_data_type(&left)?, | |
| - )?)) | |
| + Transformed::yes(Expr::Literal( | |
| + ScalarValue::new_zero(&info.get_data_type(&left)?)?, | |
| + None, | |
| + )) | |
| } | |
| // A & !A -> 0 (if A not nullable) | |
| impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> { | |
| op: BitwiseAnd, | |
| right, | |
| }) if is_negative_of(&right, &left) && !info.nullable(&left)? => { | |
| - Transformed::yes(Expr::Literal(ScalarValue::new_zero( | |
| - &info.get_data_type(&left)?, | |
| - )?)) | |
| + Transformed::yes(Expr::Literal( | |
| + ScalarValue::new_zero(&info.get_data_type(&left)?)?, | |
| + None, | |
| + )) | |
| } | |
| // (..A..) & A --> (..A..) | |
| impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> { | |
| op: BitwiseOr, | |
| right, | |
| }) if is_negative_of(&left, &right) && !info.nullable(&right)? => { | |
| - Transformed::yes(Expr::Literal(ScalarValue::new_negative_one( | |
| - &info.get_data_type(&left)?, | |
| - )?)) | |
| + Transformed::yes(Expr::Literal( | |
| + ScalarValue::new_negative_one(&info.get_data_type(&left)?)?, | |
| + None, | |
| + )) | |
| } | |
| // A | !A -> -1 (if A not nullable) | |
| impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> { | |
| op: BitwiseOr, | |
| right, | |
| }) if is_negative_of(&right, &left) && !info.nullable(&left)? => { | |
| - Transformed::yes(Expr::Literal(ScalarValue::new_negative_one( | |
| - &info.get_data_type(&left)?, | |
| - )?)) | |
| + Transformed::yes(Expr::Literal( | |
| + ScalarValue::new_negative_one(&info.get_data_type(&left)?)?, | |
| + None, | |
| + )) | |
| } | |
| // (..A..) | A --> (..A..) | |
| impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> { | |
| op: BitwiseXor, | |
| right, | |
| }) if is_negative_of(&left, &right) && !info.nullable(&right)? => { | |
| - Transformed::yes(Expr::Literal(ScalarValue::new_negative_one( | |
| - &info.get_data_type(&left)?, | |
| - )?)) | |
| + Transformed::yes(Expr::Literal( | |
| + ScalarValue::new_negative_one(&info.get_data_type(&left)?)?, | |
| + None, | |
| + )) | |
| } | |
| // A ^ !A -> -1 (if A not nullable) | |
| impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> { | |
| op: BitwiseXor, | |
| right, | |
| }) if is_negative_of(&right, &left) && !info.nullable(&left)? => { | |
| - Transformed::yes(Expr::Literal(ScalarValue::new_negative_one( | |
| - &info.get_data_type(&left)?, | |
| - )?)) | |
| + Transformed::yes(Expr::Literal( | |
| + ScalarValue::new_negative_one(&info.get_data_type(&left)?)?, | |
| + None, | |
| + )) | |
| } | |
| // (..A..) ^ A --> (the expression without A, if number of A is odd, otherwise one A) | |
| impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> { | |
| }) if expr_contains(&left, &right, BitwiseXor) => { | |
| let expr = delete_xor_in_complex_expr(&left, &right, false); | |
| Transformed::yes(if expr == *right { | |
| - Expr::Literal(ScalarValue::new_zero(&info.get_data_type(&right)?)?) | |
| + Expr::Literal( | |
| + ScalarValue::new_zero(&info.get_data_type(&right)?)?, | |
| + None, | |
| + ) | |
| } else { | |
| expr | |
| }) | |
| impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> { | |
| }) if expr_contains(&right, &left, BitwiseXor) => { | |
| let expr = delete_xor_in_complex_expr(&right, &left, true); | |
| Transformed::yes(if expr == *left { | |
| - Expr::Literal(ScalarValue::new_zero(&info.get_data_type(&left)?)?) | |
| + Expr::Literal( | |
| + ScalarValue::new_zero(&info.get_data_type(&left)?)?, | |
| + None, | |
| + ) | |
| } else { | |
| expr | |
| }) | |
| impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> { | |
| expr, | |
| list, | |
| negated, | |
| - }) if list.is_empty() && *expr != Expr::Literal(ScalarValue::Null) => { | |
| + }) if list.is_empty() && *expr != Expr::Literal(ScalarValue::Null, None) => { | |
| Transformed::yes(lit(negated)) | |
| } | |
| impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> { | |
| .into_iter() | |
| .map(|right| { | |
| match right { | |
| - Expr::Literal(right_lit_value) => { | |
| + Expr::Literal(right_lit_value, _) => { | |
| // if the right_lit_value can be casted to the type of internal_left_expr | |
| // we need to unwrap the cast for cast/try_cast expr, and add cast to the literal | |
| let Some(value) = try_cast_literal_to_type(&right_lit_value, &expr_type) else { | |
| impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> { | |
| fn as_string_scalar(expr: &Expr) -> Option<(DataType, &Option<String>)> { | |
| match expr { | |
| - Expr::Literal(ScalarValue::Utf8(s)) => Some((DataType::Utf8, s)), | |
| - Expr::Literal(ScalarValue::LargeUtf8(s)) => Some((DataType::LargeUtf8, s)), | |
| - Expr::Literal(ScalarValue::Utf8View(s)) => Some((DataType::Utf8View, s)), | |
| + Expr::Literal(ScalarValue::Utf8(s), _) => Some((DataType::Utf8, s)), | |
| + Expr::Literal(ScalarValue::LargeUtf8(s), _) => Some((DataType::LargeUtf8, s)), | |
| + Expr::Literal(ScalarValue::Utf8View(s), _) => Some((DataType::Utf8View, s)), | |
| _ => None, | |
| } | |
| } | |
| fn to_string_scalar(data_type: DataType, value: Option<String>) -> Expr { | |
| match data_type { | |
| - DataType::Utf8 => Expr::Literal(ScalarValue::Utf8(value)), | |
| - DataType::LargeUtf8 => Expr::Literal(ScalarValue::LargeUtf8(value)), | |
| - DataType::Utf8View => Expr::Literal(ScalarValue::Utf8View(value)), | |
| + DataType::Utf8 => Expr::Literal(ScalarValue::Utf8(value), None), | |
| + DataType::LargeUtf8 => Expr::Literal(ScalarValue::LargeUtf8(value), None), | |
| + DataType::Utf8View => Expr::Literal(ScalarValue::Utf8View(value), None), | |
| _ => unreachable!(), | |
| } | |
| } | |
| fn as_inlist(expr: &Expr) -> Option<Cow<InList>> { | |
| Expr::InList(inlist) => Some(Cow::Borrowed(inlist)), | |
| Expr::BinaryExpr(BinaryExpr { left, op, right }) if *op == Operator::Eq => { | |
| match (left.as_ref(), right.as_ref()) { | |
| - (Expr::Column(_), Expr::Literal(_)) => Some(Cow::Owned(InList { | |
| + (Expr::Column(_), Expr::Literal(_, _)) => Some(Cow::Owned(InList { | |
| expr: left.clone(), | |
| list: vec![*right.clone()], | |
| negated: false, | |
| })), | |
| - (Expr::Literal(_), Expr::Column(_)) => Some(Cow::Owned(InList { | |
| + (Expr::Literal(_, _), Expr::Column(_)) => Some(Cow::Owned(InList { | |
| expr: right.clone(), | |
| list: vec![*left.clone()], | |
| negated: false, | |
| fn to_inlist(expr: Expr) -> Option<InList> { | |
| op: Operator::Eq, | |
| right, | |
| }) => match (left.as_ref(), right.as_ref()) { | |
| - (Expr::Column(_), Expr::Literal(_)) => Some(InList { | |
| + (Expr::Column(_), Expr::Literal(_, _)) => Some(InList { | |
| expr: left, | |
| list: vec![*right], | |
| negated: false, | |
| }), | |
| - (Expr::Literal(_), Expr::Column(_)) => Some(InList { | |
| + (Expr::Literal(_, _), Expr::Column(_)) => Some(InList { | |
| expr: right, | |
| list: vec![*left], | |
| negated: false, | |
| mod tests { | |
| #[test] | |
| fn test_simplify_multiply_by_null() { | |
| - let null = Expr::Literal(ScalarValue::Null); | |
| + let null = Expr::Literal(ScalarValue::Null, None); | |
| // A * null --> null | |
| { | |
| let expr = col("c2") * null.clone(); | |
| mod tests { | |
| // The simplifier removes the cast. | |
| assert_eq!( | |
| simplify(coerced), | |
| - col("c5").eq(Expr::Literal(ScalarValue::FixedSizeBinary( | |
| - 3, | |
| - Some(bytes.to_vec()), | |
| - ))) | |
| + col("c5").eq(Expr::Literal( | |
| + ScalarValue::FixedSizeBinary(3, Some(bytes.to_vec()),), | |
| + None | |
| + )) | |
| ); | |
| } | |
| diff --git a/datafusion/optimizer/src/simplify_expressions/guarantees.rs b/datafusion/optimizer/src/simplify_expressions/guarantees.rs | |
| index 2c11632ad..bbb023cfb 100644 | |
| --- a/datafusion/optimizer/src/simplify_expressions/guarantees.rs | |
| +++ b/datafusion/optimizer/src/simplify_expressions/guarantees.rs | |
| impl TreeNodeRewriter for GuaranteeRewriter<'_> { | |
| low, | |
| high, | |
| }) => { | |
| - if let (Some(interval), Expr::Literal(low), Expr::Literal(high)) = ( | |
| + if let (Some(interval), Expr::Literal(low, _), Expr::Literal(high, _)) = ( | |
| self.guarantees.get(inner.as_ref()), | |
| low.as_ref(), | |
| high.as_ref(), | |
| impl TreeNodeRewriter for GuaranteeRewriter<'_> { | |
| .get(left.as_ref()) | |
| .map(|interval| Cow::Borrowed(*interval)) | |
| .or_else(|| { | |
| - if let Expr::Literal(value) = left.as_ref() { | |
| + if let Expr::Literal(value, _) = left.as_ref() { | |
| Some(Cow::Owned(value.clone().into())) | |
| } else { | |
| None | |
| impl TreeNodeRewriter for GuaranteeRewriter<'_> { | |
| .get(right.as_ref()) | |
| .map(|interval| Cow::Borrowed(*interval)) | |
| .or_else(|| { | |
| - if let Expr::Literal(value) = right.as_ref() { | |
| + if let Expr::Literal(value, _) = right.as_ref() { | |
| Some(Cow::Owned(value.clone().into())) | |
| } else { | |
| None | |
| impl TreeNodeRewriter for GuaranteeRewriter<'_> { | |
| let new_list: Vec<Expr> = list | |
| .iter() | |
| .filter_map(|expr| { | |
| - if let Expr::Literal(item) = expr { | |
| + if let Expr::Literal(item, _) = expr { | |
| match interval | |
| .contains(NullableInterval::from(item.clone())) | |
| { | |
| mod tests { | |
| let mut rewriter = GuaranteeRewriter::new(guarantees.iter()); | |
| let output = col("x").rewrite(&mut rewriter).data().unwrap(); | |
| - assert_eq!(output, Expr::Literal(scalar.clone())); | |
| + assert_eq!(output, Expr::Literal(scalar.clone(), None)); | |
| } | |
| } | |
| diff --git a/datafusion/optimizer/src/simplify_expressions/regex.rs b/datafusion/optimizer/src/simplify_expressions/regex.rs | |
| index ec6485bf4..82c5ea3d8 100644 | |
| --- a/datafusion/optimizer/src/simplify_expressions/regex.rs | |
| +++ b/datafusion/optimizer/src/simplify_expressions/regex.rs | |
| pub fn simplify_regex_expr( | |
| ) -> Result<Expr> { | |
| let mode = OperatorMode::new(&op); | |
| - if let Expr::Literal(ScalarValue::Utf8(Some(pattern))) = right.as_ref() { | |
| + if let Expr::Literal(ScalarValue::Utf8(Some(pattern)), _) = right.as_ref() { | |
| // Handle the special case for ".*" pattern | |
| if pattern == ANY_CHAR_REGEX_PATTERN { | |
| let new_expr = if mode.not { | |
| impl OperatorMode { | |
| let like = Like { | |
| negated: self.not, | |
| expr, | |
| - pattern: Box::new(Expr::Literal(ScalarValue::from(pattern))), | |
| + pattern: Box::new(Expr::Literal(ScalarValue::from(pattern), None)), | |
| escape_char: None, | |
| case_insensitive: self.i, | |
| }; | |
| diff --git a/datafusion/optimizer/src/simplify_expressions/unwrap_cast.rs b/datafusion/optimizer/src/simplify_expressions/unwrap_cast.rs | |
| index b70b19bae..7c8ff8305 100644 | |
| --- a/datafusion/optimizer/src/simplify_expressions/unwrap_cast.rs | |
| +++ b/datafusion/optimizer/src/simplify_expressions/unwrap_cast.rs | |
| pub(super) fn unwrap_cast_in_comparison_for_binary<S: SimplifyInfo>( | |
| match (cast_expr, literal) { | |
| ( | |
| Expr::TryCast(TryCast { expr, .. }) | Expr::Cast(Cast { expr, .. }), | |
| - Expr::Literal(lit_value), | |
| + Expr::Literal(lit_value, _), | |
| ) => { | |
| let Ok(expr_type) = info.get_data_type(&expr) else { | |
| return internal_err!("Can't get the data type of the expr {:?}", &expr); | |
| pub(super) fn is_cast_expr_and_support_unwrap_cast_in_comparison_for_binary< | |
| | Expr::Cast(Cast { | |
| expr: left_expr, .. | |
| }), | |
| - Expr::Literal(lit_val), | |
| + Expr::Literal(lit_val, _), | |
| ) => { | |
| let Ok(expr_type) = info.get_data_type(left_expr) else { | |
| return false; | |
| pub(super) fn is_cast_expr_and_support_unwrap_cast_in_comparison_for_inlist< | |
| } | |
| match right { | |
| - Expr::Literal(lit_val) | |
| + Expr::Literal(lit_val, _) | |
| if try_cast_literal_to_type(lit_val, &expr_type).is_some() => {} | |
| _ => return false, | |
| } | |
| diff --git a/datafusion/optimizer/src/simplify_expressions/utils.rs b/datafusion/optimizer/src/simplify_expressions/utils.rs | |
| index cf182175e..4df0e125e 100644 | |
| --- a/datafusion/optimizer/src/simplify_expressions/utils.rs | |
| +++ b/datafusion/optimizer/src/simplify_expressions/utils.rs | |
| pub fn delete_xor_in_complex_expr(expr: &Expr, needle: &Expr, is_left: bool) -> | |
| pub fn is_zero(s: &Expr) -> bool { | |
| match s { | |
| - Expr::Literal(ScalarValue::Int8(Some(0))) | |
| - | Expr::Literal(ScalarValue::Int16(Some(0))) | |
| - | Expr::Literal(ScalarValue::Int32(Some(0))) | |
| - | Expr::Literal(ScalarValue::Int64(Some(0))) | |
| - | Expr::Literal(ScalarValue::UInt8(Some(0))) | |
| - | Expr::Literal(ScalarValue::UInt16(Some(0))) | |
| - | Expr::Literal(ScalarValue::UInt32(Some(0))) | |
| - | Expr::Literal(ScalarValue::UInt64(Some(0))) => true, | |
| - Expr::Literal(ScalarValue::Float32(Some(v))) if *v == 0. => true, | |
| - Expr::Literal(ScalarValue::Float64(Some(v))) if *v == 0. => true, | |
| - Expr::Literal(ScalarValue::Decimal128(Some(v), _p, _s)) if *v == 0 => true, | |
| + Expr::Literal(ScalarValue::Int8(Some(0)), _) | |
| + | Expr::Literal(ScalarValue::Int16(Some(0)), _) | |
| + | Expr::Literal(ScalarValue::Int32(Some(0)), _) | |
| + | Expr::Literal(ScalarValue::Int64(Some(0)), _) | |
| + | Expr::Literal(ScalarValue::UInt8(Some(0)), _) | |
| + | Expr::Literal(ScalarValue::UInt16(Some(0)), _) | |
| + | Expr::Literal(ScalarValue::UInt32(Some(0)), _) | |
| + | Expr::Literal(ScalarValue::UInt64(Some(0)), _) => true, | |
| + Expr::Literal(ScalarValue::Float32(Some(v)), _) if *v == 0. => true, | |
| + Expr::Literal(ScalarValue::Float64(Some(v)), _) if *v == 0. => true, | |
| + Expr::Literal(ScalarValue::Decimal128(Some(v), _p, _s), _) if *v == 0 => true, | |
| _ => false, | |
| } | |
| } | |
| pub fn is_one(s: &Expr) -> bool { | |
| match s { | |
| - Expr::Literal(ScalarValue::Int8(Some(1))) | |
| - | Expr::Literal(ScalarValue::Int16(Some(1))) | |
| - | Expr::Literal(ScalarValue::Int32(Some(1))) | |
| - | Expr::Literal(ScalarValue::Int64(Some(1))) | |
| - | Expr::Literal(ScalarValue::UInt8(Some(1))) | |
| - | Expr::Literal(ScalarValue::UInt16(Some(1))) | |
| - | Expr::Literal(ScalarValue::UInt32(Some(1))) | |
| - | Expr::Literal(ScalarValue::UInt64(Some(1))) => true, | |
| - Expr::Literal(ScalarValue::Float32(Some(v))) if *v == 1. => true, | |
| - Expr::Literal(ScalarValue::Float64(Some(v))) if *v == 1. => true, | |
| - Expr::Literal(ScalarValue::Decimal128(Some(v), _p, s)) => { | |
| + Expr::Literal(ScalarValue::Int8(Some(1)), _) | |
| + | Expr::Literal(ScalarValue::Int16(Some(1)), _) | |
| + | Expr::Literal(ScalarValue::Int32(Some(1)), _) | |
| + | Expr::Literal(ScalarValue::Int64(Some(1)), _) | |
| + | Expr::Literal(ScalarValue::UInt8(Some(1)), _) | |
| + | Expr::Literal(ScalarValue::UInt16(Some(1)), _) | |
| + | Expr::Literal(ScalarValue::UInt32(Some(1)), _) | |
| + | Expr::Literal(ScalarValue::UInt64(Some(1)), _) => true, | |
| + Expr::Literal(ScalarValue::Float32(Some(v)), _) if *v == 1. => true, | |
| + Expr::Literal(ScalarValue::Float64(Some(v)), _) if *v == 1. => true, | |
| + Expr::Literal(ScalarValue::Decimal128(Some(v), _p, s), _) => { | |
| *s >= 0 | |
| && POWS_OF_TEN | |
| .get(*s as usize) | |
| pub fn is_one(s: &Expr) -> bool { | |
| pub fn is_true(expr: &Expr) -> bool { | |
| match expr { | |
| - Expr::Literal(ScalarValue::Boolean(Some(v))) => *v, | |
| + Expr::Literal(ScalarValue::Boolean(Some(v)), _) => *v, | |
| _ => false, | |
| } | |
| } | |
| pub fn is_true(expr: &Expr) -> bool { | |
| /// returns true if expr is a | |
| /// `Expr::Literal(ScalarValue::Boolean(v))` , false otherwise | |
| pub fn is_bool_lit(expr: &Expr) -> bool { | |
| - matches!(expr, Expr::Literal(ScalarValue::Boolean(_))) | |
| + matches!(expr, Expr::Literal(ScalarValue::Boolean(_), _)) | |
| } | |
| /// Return a literal NULL value of Boolean data type | |
| pub fn lit_bool_null() -> Expr { | |
| - Expr::Literal(ScalarValue::Boolean(None)) | |
| + Expr::Literal(ScalarValue::Boolean(None), None) | |
| } | |
| pub fn is_null(expr: &Expr) -> bool { | |
| match expr { | |
| - Expr::Literal(v) => v.is_null(), | |
| + Expr::Literal(v, _) => v.is_null(), | |
| _ => false, | |
| } | |
| } | |
| pub fn is_false(expr: &Expr) -> bool { | |
| match expr { | |
| - Expr::Literal(ScalarValue::Boolean(Some(v))) => !(*v), | |
| + Expr::Literal(ScalarValue::Boolean(Some(v)), _) => !(*v), | |
| _ => false, | |
| } | |
| } | |
| pub fn is_negative_of(not_expr: &Expr, expr: &Expr) -> bool { | |
| /// `Expr::Literal(ScalarValue::Boolean(v))`. | |
| pub fn as_bool_lit(expr: &Expr) -> Result<Option<bool>> { | |
| match expr { | |
| - Expr::Literal(ScalarValue::Boolean(v)) => Ok(*v), | |
| + Expr::Literal(ScalarValue::Boolean(v), _) => Ok(*v), | |
| _ => internal_err!("Expected boolean literal, got {expr:?}"), | |
| } | |
| } | |
| diff --git a/datafusion/optimizer/src/utils.rs b/datafusion/optimizer/src/utils.rs | |
| index 135f37dd9..0aa0bf3ea 100644 | |
| --- a/datafusion/optimizer/src/utils.rs | |
| +++ b/datafusion/optimizer/src/utils.rs | |
| mod tests { | |
| (Expr::IsNotNull(Box::new(col("a"))), true), | |
| // a = NULL | |
| ( | |
| - binary_expr(col("a"), Operator::Eq, Expr::Literal(ScalarValue::Null)), | |
| + binary_expr( | |
| + col("a"), | |
| + Operator::Eq, | |
| + Expr::Literal(ScalarValue::Null, None), | |
| + ), | |
| true, | |
| ), | |
| // a > 8 | |
| mod tests { | |
| ), | |
| // a IN (NULL) | |
| ( | |
| - in_list(col("a"), vec![Expr::Literal(ScalarValue::Null)], false), | |
| + in_list( | |
| + col("a"), | |
| + vec![Expr::Literal(ScalarValue::Null, None)], | |
| + false, | |
| + ), | |
| true, | |
| ), | |
| // a NOT IN (NULL) | |
| ( | |
| - in_list(col("a"), vec![Expr::Literal(ScalarValue::Null)], true), | |
| + in_list(col("a"), vec![Expr::Literal(ScalarValue::Null, None)], true), | |
| true, | |
| ), | |
| ]; | |
| diff --git a/datafusion/physical-expr/src/expressions/dynamic_filters.rs b/datafusion/physical-expr/src/expressions/dynamic_filters.rs | |
| index 9785203a7..756fb638a 100644 | |
| --- a/datafusion/physical-expr/src/expressions/dynamic_filters.rs | |
| +++ b/datafusion/physical-expr/src/expressions/dynamic_filters.rs | |
| mod test { | |
| ) | |
| .unwrap(); | |
| let snap = dynamic_filter_1.snapshot().unwrap().unwrap(); | |
| - insta::assert_snapshot!(format!("{snap:?}"), @r#"BinaryExpr { left: Column { name: "a", index: 0 }, op: Eq, right: Literal { value: Int32(42) }, fail_on_overflow: false }"#); | |
| + insta::assert_snapshot!(format!("{snap:?}"), @r#"BinaryExpr { left: Column { name: "a", index: 0 }, op: Eq, right: Literal { value: Int32(42), field: Field { name: "42", data_type: Int32, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} } }, fail_on_overflow: false }"#); | |
| let dynamic_filter_2 = reassign_predicate_columns( | |
| Arc::clone(&dynamic_filter) as Arc<dyn PhysicalExpr>, | |
| &filter_schema_2, | |
| mod test { | |
| ) | |
| .unwrap(); | |
| let snap = dynamic_filter_2.snapshot().unwrap().unwrap(); | |
| - insta::assert_snapshot!(format!("{snap:?}"), @r#"BinaryExpr { left: Column { name: "a", index: 1 }, op: Eq, right: Literal { value: Int32(42) }, fail_on_overflow: false }"#); | |
| + insta::assert_snapshot!(format!("{snap:?}"), @r#"BinaryExpr { left: Column { name: "a", index: 1 }, op: Eq, right: Literal { value: Int32(42), field: Field { name: "42", data_type: Int32, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} } }, fail_on_overflow: false }"#); | |
| // Both filters allow evaluating the same expression | |
| let batch_1 = RecordBatch::try_new( | |
| Arc::clone(&filter_schema_1), | |
| diff --git a/datafusion/physical-expr/src/expressions/in_list.rs b/datafusion/physical-expr/src/expressions/in_list.rs | |
| index 469f7bbee..a1a14b2f3 100644 | |
| --- a/datafusion/physical-expr/src/expressions/in_list.rs | |
| +++ b/datafusion/physical-expr/src/expressions/in_list.rs | |
| mod tests { | |
| let sql_string = fmt_sql(expr.as_ref()).to_string(); | |
| let display_string = expr.to_string(); | |
| assert_eq!(sql_string, "a IN (a, b)"); | |
| - assert_eq!(display_string, "Use a@0 IN (SET) ([Literal { value: Utf8(\"a\") }, Literal { value: Utf8(\"b\") }])"); | |
| + assert_eq!(display_string, "Use a@0 IN (SET) ([Literal { value: Utf8(\"a\"), field: Field { name: \"a\", data_type: Utf8, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} } }, Literal { value: Utf8(\"b\"), field: Field { name: \"b\", data_type: Utf8, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} } }])"); | |
| // Test: a NOT IN ('a', 'b') | |
| let list = vec![lit("a"), lit("b")]; | |
| mod tests { | |
| let sql_string = fmt_sql(expr.as_ref()).to_string(); | |
| let display_string = expr.to_string(); | |
| assert_eq!(sql_string, "a NOT IN (a, b)"); | |
| - assert_eq!(display_string, "a@0 NOT IN (SET) ([Literal { value: Utf8(\"a\") }, Literal { value: Utf8(\"b\") }])"); | |
| + assert_eq!(display_string, "a@0 NOT IN (SET) ([Literal { value: Utf8(\"a\"), field: Field { name: \"a\", data_type: Utf8, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} } }, Literal { value: Utf8(\"b\"), field: Field { name: \"b\", data_type: Utf8, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} } }])"); | |
| // Test: a IN ('a', 'b', NULL) | |
| let list = vec![lit("a"), lit("b"), lit(ScalarValue::Utf8(None))]; | |
| mod tests { | |
| let sql_string = fmt_sql(expr.as_ref()).to_string(); | |
| let display_string = expr.to_string(); | |
| assert_eq!(sql_string, "a IN (a, b, NULL)"); | |
| - assert_eq!(display_string, "Use a@0 IN (SET) ([Literal { value: Utf8(\"a\") }, Literal { value: Utf8(\"b\") }, Literal { value: Utf8(NULL) }])"); | |
| + assert_eq!(display_string, "Use a@0 IN (SET) ([Literal { value: Utf8(\"a\"), field: Field { name: \"a\", data_type: Utf8, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} } }, Literal { value: Utf8(\"b\"), field: Field { name: \"b\", data_type: Utf8, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} } }, Literal { value: Utf8(NULL), field: Field { name: \"NULL\", data_type: Utf8, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} } }])"); | |
| // Test: a NOT IN ('a', 'b', NULL) | |
| let list = vec![lit("a"), lit("b"), lit(ScalarValue::Utf8(None))]; | |
| mod tests { | |
| let sql_string = fmt_sql(expr.as_ref()).to_string(); | |
| let display_string = expr.to_string(); | |
| assert_eq!(sql_string, "a NOT IN (a, b, NULL)"); | |
| - assert_eq!(display_string, "a@0 NOT IN (SET) ([Literal { value: Utf8(\"a\") }, Literal { value: Utf8(\"b\") }, Literal { value: Utf8(NULL) }])"); | |
| + assert_eq!(display_string, "a@0 NOT IN (SET) ([Literal { value: Utf8(\"a\"), field: Field { name: \"a\", data_type: Utf8, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} } }, Literal { value: Utf8(\"b\"), field: Field { name: \"b\", data_type: Utf8, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} } }, Literal { value: Utf8(NULL), field: Field { name: \"NULL\", data_type: Utf8, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} } }])"); | |
| Ok(()) | |
| } | |
| diff --git a/datafusion/physical-expr/src/expressions/literal.rs b/datafusion/physical-expr/src/expressions/literal.rs | |
| index 6f7caaea8..0d4d62ef4 100644 | |
| --- a/datafusion/physical-expr/src/expressions/literal.rs | |
| +++ b/datafusion/physical-expr/src/expressions/literal.rs | |
| //! Literal expressions for physical operations | |
| use std::any::Any; | |
| +use std::collections::HashMap; | |
| use std::hash::Hash; | |
| use std::sync::Arc; | |
| use crate::physical_expr::PhysicalExpr; | |
| +use arrow::datatypes::{Field, FieldRef}; | |
| use arrow::{ | |
| datatypes::{DataType, Schema}, | |
| record_batch::RecordBatch, | |
| use datafusion_expr_common::interval_arithmetic::Interval; | |
| use datafusion_expr_common::sort_properties::{ExprProperties, SortProperties}; | |
| /// Represents a literal value | |
| -#[derive(Debug, PartialEq, Eq, Hash)] | |
| +#[derive(Debug, PartialEq, Eq)] | |
| pub struct Literal { | |
| value: ScalarValue, | |
| + field: FieldRef, | |
| +} | |
| + | |
| +impl Hash for Literal { | |
| + fn hash<H: std::hash::Hasher>(&self, state: &mut H) { | |
| + self.value.hash(state); | |
| + let metadata = self.field.metadata(); | |
| + let mut keys = metadata.keys().collect::<Vec<_>>(); | |
| + keys.sort(); | |
| + for key in keys { | |
| + key.hash(state); | |
| + metadata.get(key).unwrap().hash(state); | |
| + } | |
| + } | |
| } | |
| impl Literal { | |
| /// Create a literal value expression | |
| pub fn new(value: ScalarValue) -> Self { | |
| - Self { value } | |
| + Self::new_with_metadata(value, None) | |
| + } | |
| + | |
| + /// Create a literal value expression | |
| + pub fn new_with_metadata( | |
| + value: ScalarValue, | |
| + metadata: impl Into<Option<HashMap<String, String>>>, | |
| + ) -> Self { | |
| + let metadata = metadata.into(); | |
| + let mut field = | |
| + Field::new(format!("{value}"), value.data_type(), value.is_null()); | |
| + | |
| + if let Some(metadata) = metadata { | |
| + field = field.with_metadata(metadata); | |
| + } | |
| + | |
| + Self { | |
| + value, | |
| + field: field.into(), | |
| + } | |
| } | |
| /// Get the scalar value | |
| impl PhysicalExpr for Literal { | |
| Ok(self.value.is_null()) | |
| } | |
| + fn return_field(&self, _input_schema: &Schema) -> Result<FieldRef> { | |
| + Ok(Arc::clone(&self.field)) | |
| + } | |
| + | |
| fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> { | |
| Ok(ColumnarValue::Scalar(self.value.clone())) | |
| } | |
| impl PhysicalExpr for Literal { | |
| /// Create a literal expression | |
| pub fn lit<T: datafusion_expr::Literal>(value: T) -> Arc<dyn PhysicalExpr> { | |
| match value.lit() { | |
| - Expr::Literal(v) => Arc::new(Literal::new(v)), | |
| + Expr::Literal(v, _) => Arc::new(Literal::new(v)), | |
| _ => unreachable!(), | |
| } | |
| } | |
| diff --git a/datafusion/physical-expr/src/planner.rs b/datafusion/physical-expr/src/planner.rs | |
| index 8660bff79..6f1417ec2 100644 | |
| --- a/datafusion/physical-expr/src/planner.rs | |
| +++ b/datafusion/physical-expr/src/planner.rs | |
| // specific language governing permissions and limitations | |
| // under the License. | |
| +use std::collections::HashMap; | |
| use std::sync::Arc; | |
| use crate::ScalarFunctionExpr; | |
| pub fn create_physical_expr( | |
| let input_schema: &Schema = &input_dfschema.into(); | |
| match e { | |
| - Expr::Alias(Alias { expr, .. }) => { | |
| - Ok(create_physical_expr(expr, input_dfschema, execution_props)?) | |
| + Expr::Alias(Alias { expr, metadata, .. }) => { | |
| + if let Expr::Literal(v, prior_metadata) = expr.as_ref() { | |
| + let mut new_metadata = prior_metadata | |
| + .as_ref() | |
| + .map(|m| { | |
| + m.iter() | |
| + .map(|(k, v)| (k.clone(), v.clone())) | |
| + .collect::<HashMap<String, String>>() | |
| + }) | |
| + .unwrap_or_default(); | |
| + if let Some(metadata) = metadata { | |
| + new_metadata.extend(metadata.clone()); | |
| + } | |
| + let new_metadata = match new_metadata.is_empty() { | |
| + true => None, | |
| + false => Some(new_metadata), | |
| + }; | |
| + | |
| + Ok(Arc::new(Literal::new_with_metadata( | |
| + v.clone(), | |
| + new_metadata, | |
| + ))) | |
| + } else { | |
| + Ok(create_physical_expr(expr, input_dfschema, execution_props)?) | |
| + } | |
| } | |
| Expr::Column(c) => { | |
| let idx = input_dfschema.index_of_column(c)?; | |
| Ok(Arc::new(Column::new(&c.name, idx))) | |
| } | |
| - Expr::Literal(value) => Ok(Arc::new(Literal::new(value.clone()))), | |
| + Expr::Literal(value, metadata) => Ok(Arc::new(Literal::new_with_metadata( | |
| + value.clone(), | |
| + metadata | |
| + .as_ref() | |
| + .map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()), | |
| + ))), | |
| Expr::ScalarVariable(_, variable_names) => { | |
| if is_system_variables(variable_names) { | |
| match execution_props.get_var_provider(VarType::System) { | |
| pub fn create_physical_expr( | |
| let binary_op = binary_expr( | |
| expr.as_ref().clone(), | |
| Operator::IsNotDistinctFrom, | |
| - Expr::Literal(ScalarValue::Boolean(None)), | |
| + Expr::Literal(ScalarValue::Boolean(None), None), | |
| ); | |
| create_physical_expr(&binary_op, input_dfschema, execution_props) | |
| } | |
| pub fn create_physical_expr( | |
| let binary_op = binary_expr( | |
| expr.as_ref().clone(), | |
| Operator::IsDistinctFrom, | |
| - Expr::Literal(ScalarValue::Boolean(None)), | |
| + Expr::Literal(ScalarValue::Boolean(None), None), | |
| ); | |
| create_physical_expr(&binary_op, input_dfschema, execution_props) | |
| } | |
| pub fn create_physical_expr( | |
| list, | |
| negated, | |
| }) => match expr.as_ref() { | |
| - Expr::Literal(ScalarValue::Utf8(None)) => { | |
| + Expr::Literal(ScalarValue::Utf8(None), _) => { | |
| Ok(expressions::lit(ScalarValue::Boolean(None))) | |
| } | |
| _ => { | |
| diff --git a/datafusion/proto/src/logical_plan/from_proto.rs b/datafusion/proto/src/logical_plan/from_proto.rs | |
| index 38546fa38..1b5527c14 100644 | |
| --- a/datafusion/proto/src/logical_plan/from_proto.rs | |
| +++ b/datafusion/proto/src/logical_plan/from_proto.rs | |
| pub fn parse_expr( | |
| ExprType::Column(column) => Ok(Expr::Column(column.into())), | |
| ExprType::Literal(literal) => { | |
| let scalar_value: ScalarValue = literal.try_into()?; | |
| - Ok(Expr::Literal(scalar_value)) | |
| + Ok(Expr::Literal(scalar_value, None)) | |
| } | |
| ExprType::WindowExpr(expr) => { | |
| let window_function = expr | |
| diff --git a/datafusion/proto/src/logical_plan/to_proto.rs b/datafusion/proto/src/logical_plan/to_proto.rs | |
| index 180735166..7f089b1c8 100644 | |
| --- a/datafusion/proto/src/logical_plan/to_proto.rs | |
| +++ b/datafusion/proto/src/logical_plan/to_proto.rs | |
| pub fn serialize_expr( | |
| expr_type: Some(ExprType::Alias(alias)), | |
| } | |
| } | |
| - Expr::Literal(value) => { | |
| + Expr::Literal(value, _) => { | |
| let pb_value: protobuf::ScalarValue = value.try_into()?; | |
| protobuf::LogicalExprNode { | |
| expr_type: Some(ExprType::Literal(pb_value)), | |
| diff --git a/datafusion/sql/src/expr/mod.rs b/datafusion/sql/src/expr/mod.rs | |
| index eadf66a91..e92869873 100644 | |
| --- a/datafusion/sql/src/expr/mod.rs | |
| +++ b/datafusion/sql/src/expr/mod.rs | |
| impl<S: ContextProvider> SqlToRel<'_, S> { | |
| } | |
| SQLExpr::Extract { field, expr, .. } => { | |
| let mut extract_args = vec![ | |
| - Expr::Literal(ScalarValue::from(format!("{field}"))), | |
| + Expr::Literal(ScalarValue::from(format!("{field}")), None), | |
| self.sql_expr_to_logical_expr(*expr, schema, planner_context)?, | |
| ]; | |
| diff --git a/datafusion/sql/src/expr/substring.rs b/datafusion/sql/src/expr/substring.rs | |
| index 59c78bc71..8f6e77e03 100644 | |
| --- a/datafusion/sql/src/expr/substring.rs | |
| +++ b/datafusion/sql/src/expr/substring.rs | |
| impl<S: ContextProvider> SqlToRel<'_, S> { | |
| (None, Some(for_expr)) => { | |
| let arg = | |
| self.sql_expr_to_logical_expr(*expr, schema, planner_context)?; | |
| - let from_logic = Expr::Literal(ScalarValue::Int64(Some(1))); | |
| + let from_logic = Expr::Literal(ScalarValue::Int64(Some(1)), None); | |
| let for_logic = | |
| self.sql_expr_to_logical_expr(*for_expr, schema, planner_context)?; | |
| vec![arg, from_logic, for_logic] | |
| diff --git a/datafusion/sql/src/expr/value.rs b/datafusion/sql/src/expr/value.rs | |
| index b77f5eaf4..7075a1afd 100644 | |
| --- a/datafusion/sql/src/expr/value.rs | |
| +++ b/datafusion/sql/src/expr/value.rs | |
| impl<S: ContextProvider> SqlToRel<'_, S> { | |
| match value { | |
| Value::Number(n, _) => self.parse_sql_number(&n, false), | |
| Value::SingleQuotedString(s) | Value::DoubleQuotedString(s) => Ok(lit(s)), | |
| - Value::Null => Ok(Expr::Literal(ScalarValue::Null)), | |
| + Value::Null => Ok(Expr::Literal(ScalarValue::Null, None)), | |
| Value::Boolean(n) => Ok(lit(n)), | |
| Value::Placeholder(param) => { | |
| Self::create_placeholder_expr(param, param_data_types) | |
| fn parse_decimal(unsigned_number: &str, negative: bool) -> Result<Expr> { | |
| int_val | |
| ) | |
| })?; | |
| - Ok(Expr::Literal(ScalarValue::Decimal128( | |
| - Some(val), | |
| - precision as u8, | |
| - scale as i8, | |
| - ))) | |
| + Ok(Expr::Literal( | |
| + ScalarValue::Decimal128(Some(val), precision as u8, scale as i8), | |
| + None, | |
| + )) | |
| } else if precision <= DECIMAL256_MAX_PRECISION as u64 { | |
| let val = bigint_to_i256(&int_val).ok_or_else(|| { | |
| // Failures are unexpected here as we have already checked the precision | |
| fn parse_decimal(unsigned_number: &str, negative: bool) -> Result<Expr> { | |
| int_val | |
| ) | |
| })?; | |
| - Ok(Expr::Literal(ScalarValue::Decimal256( | |
| - Some(val), | |
| - precision as u8, | |
| - scale as i8, | |
| - ))) | |
| + Ok(Expr::Literal( | |
| + ScalarValue::Decimal256(Some(val), precision as u8, scale as i8), | |
| + None, | |
| + )) | |
| } else { | |
| not_impl_err!( | |
| "Decimal precision {} exceeds the maximum supported precision: {}", | |
| mod tests { | |
| ]; | |
| for (input, expect) in cases { | |
| let output = parse_decimal(input, true).unwrap(); | |
| - assert_eq!(output, Expr::Literal(expect.arithmetic_negate().unwrap())); | |
| + assert_eq!( | |
| + output, | |
| + Expr::Literal(expect.arithmetic_negate().unwrap(), None) | |
| + ); | |
| let output = parse_decimal(input, false).unwrap(); | |
| - assert_eq!(output, Expr::Literal(expect)); | |
| + assert_eq!(output, Expr::Literal(expect, None)); | |
| } | |
| // scale < i8::MIN | |
| diff --git a/datafusion/sql/src/statement.rs b/datafusion/sql/src/statement.rs | |
| index 458b3ac13..dafb03464 100644 | |
| --- a/datafusion/sql/src/statement.rs | |
| +++ b/datafusion/sql/src/statement.rs | |
| impl<S: ContextProvider> SqlToRel<'_, S> { | |
| .cloned() | |
| .unwrap_or_else(|| { | |
| // If there is no default for the column, then the default is NULL | |
| - Expr::Literal(ScalarValue::Null) | |
| + Expr::Literal(ScalarValue::Null, None) | |
| }) | |
| .cast_to(target_field.data_type(), &DFSchema::empty())?, | |
| }; | |
| diff --git a/datafusion/sql/src/unparser/expr.rs b/datafusion/sql/src/unparser/expr.rs | |
| index 661e8581a..cce14894a 100644 | |
| --- a/datafusion/sql/src/unparser/expr.rs | |
| +++ b/datafusion/sql/src/unparser/expr.rs | |
| impl Unparser<'_> { | |
| Expr::Cast(Cast { expr, data_type }) => { | |
| Ok(self.cast_to_sql(expr, data_type)?) | |
| } | |
| - Expr::Literal(value) => Ok(self.scalar_to_sql(value)?), | |
| + Expr::Literal(value, _) => Ok(self.scalar_to_sql(value)?), | |
| Expr::Alias(Alias { expr, name: _, .. }) => self.expr_to_sql_inner(expr), | |
| Expr::WindowFunction(window_fun) => { | |
| let WindowFunction { | |
| impl Unparser<'_> { | |
| .chunks_exact(2) | |
| .map(|chunk| { | |
| let key = match &chunk[0] { | |
| - Expr::Literal(ScalarValue::Utf8(Some(s))) => self.new_ident_quoted_if_needs(s.to_string()), | |
| + Expr::Literal(ScalarValue::Utf8(Some(s)), _) => self.new_ident_quoted_if_needs(s.to_string()), | |
| _ => return internal_err!("named_struct expects even arguments to be strings, but received: {:?}", &chunk[0]) | |
| }; | |
| impl Unparser<'_> { | |
| }; | |
| let field = match &args[1] { | |
| - Expr::Literal(lit) => self.new_ident_quoted_if_needs(lit.to_string()), | |
| + Expr::Literal(lit, _) => self.new_ident_quoted_if_needs(lit.to_string()), | |
| _ => { | |
| return internal_err!( | |
| "get_field expects second argument to be a string, but received: {:?}", | |
| mod tests { | |
| r#"a LIKE 'foo' ESCAPE 'o'"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::Date64(Some(0))), | |
| + Expr::Literal(ScalarValue::Date64(Some(0)), None), | |
| r#"CAST('1970-01-01 00:00:00' AS DATETIME)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::Date64(Some(10000))), | |
| + Expr::Literal(ScalarValue::Date64(Some(10000)), None), | |
| r#"CAST('1970-01-01 00:00:10' AS DATETIME)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::Date64(Some(-10000))), | |
| + Expr::Literal(ScalarValue::Date64(Some(-10000)), None), | |
| r#"CAST('1969-12-31 23:59:50' AS DATETIME)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::Date32(Some(0))), | |
| + Expr::Literal(ScalarValue::Date32(Some(0)), None), | |
| r#"CAST('1970-01-01' AS DATE)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::Date32(Some(10))), | |
| + Expr::Literal(ScalarValue::Date32(Some(10)), None), | |
| r#"CAST('1970-01-11' AS DATE)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::Date32(Some(-1))), | |
| + Expr::Literal(ScalarValue::Date32(Some(-1)), None), | |
| r#"CAST('1969-12-31' AS DATE)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::TimestampSecond(Some(10001), None)), | |
| + Expr::Literal(ScalarValue::TimestampSecond(Some(10001), None), None), | |
| r#"CAST('1970-01-01 02:46:41' AS TIMESTAMP)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::TimestampSecond( | |
| - Some(10001), | |
| - Some("+08:00".into()), | |
| - )), | |
| + Expr::Literal( | |
| + ScalarValue::TimestampSecond(Some(10001), Some("+08:00".into())), | |
| + None, | |
| + ), | |
| r#"CAST('1970-01-01 10:46:41 +08:00' AS TIMESTAMP)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::TimestampMillisecond(Some(10001), None)), | |
| + Expr::Literal(ScalarValue::TimestampMillisecond(Some(10001), None), None), | |
| r#"CAST('1970-01-01 00:00:10.001' AS TIMESTAMP)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::TimestampMillisecond( | |
| - Some(10001), | |
| - Some("+08:00".into()), | |
| - )), | |
| + Expr::Literal( | |
| + ScalarValue::TimestampMillisecond(Some(10001), Some("+08:00".into())), | |
| + None, | |
| + ), | |
| r#"CAST('1970-01-01 08:00:10.001 +08:00' AS TIMESTAMP)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::TimestampMicrosecond(Some(10001), None)), | |
| + Expr::Literal(ScalarValue::TimestampMicrosecond(Some(10001), None), None), | |
| r#"CAST('1970-01-01 00:00:00.010001' AS TIMESTAMP)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::TimestampMicrosecond( | |
| - Some(10001), | |
| - Some("+08:00".into()), | |
| - )), | |
| + Expr::Literal( | |
| + ScalarValue::TimestampMicrosecond(Some(10001), Some("+08:00".into())), | |
| + None, | |
| + ), | |
| r#"CAST('1970-01-01 08:00:00.010001 +08:00' AS TIMESTAMP)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::TimestampNanosecond(Some(10001), None)), | |
| + Expr::Literal(ScalarValue::TimestampNanosecond(Some(10001), None), None), | |
| r#"CAST('1970-01-01 00:00:00.000010001' AS TIMESTAMP)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::TimestampNanosecond( | |
| - Some(10001), | |
| - Some("+08:00".into()), | |
| - )), | |
| + Expr::Literal( | |
| + ScalarValue::TimestampNanosecond(Some(10001), Some("+08:00".into())), | |
| + None, | |
| + ), | |
| r#"CAST('1970-01-01 08:00:00.000010001 +08:00' AS TIMESTAMP)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::Time32Second(Some(10001))), | |
| + Expr::Literal(ScalarValue::Time32Second(Some(10001)), None), | |
| r#"CAST('02:46:41' AS TIME)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::Time32Millisecond(Some(10001))), | |
| + Expr::Literal(ScalarValue::Time32Millisecond(Some(10001)), None), | |
| r#"CAST('00:00:10.001' AS TIME)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::Time64Microsecond(Some(10001))), | |
| + Expr::Literal(ScalarValue::Time64Microsecond(Some(10001)), None), | |
| r#"CAST('00:00:00.010001' AS TIME)"#, | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::Time64Nanosecond(Some(10001))), | |
| + Expr::Literal(ScalarValue::Time64Nanosecond(Some(10001)), None), | |
| r#"CAST('00:00:00.000010001' AS TIME)"#, | |
| ), | |
| (sum(col("a")), r#"sum(a)"#), | |
| mod tests { | |
| (col("need quoted").eq(lit(1)), r#"("need quoted" = 1)"#), | |
| // See test_interval_scalar_to_expr for interval literals | |
| ( | |
| - (col("a") + col("b")).gt(Expr::Literal(ScalarValue::Decimal128( | |
| - Some(100123), | |
| - 28, | |
| - 3, | |
| - ))), | |
| + (col("a") + col("b")).gt(Expr::Literal( | |
| + ScalarValue::Decimal128(Some(100123), 28, 3), | |
| + None, | |
| + )), | |
| r#"((a + b) > 100.123)"#, | |
| ), | |
| ( | |
| - (col("a") + col("b")).gt(Expr::Literal(ScalarValue::Decimal256( | |
| - Some(100123.into()), | |
| - 28, | |
| - 3, | |
| - ))), | |
| + (col("a") + col("b")).gt(Expr::Literal( | |
| + ScalarValue::Decimal256(Some(100123.into()), 28, 3), | |
| + None, | |
| + )), | |
| r#"((a + b) > 100.123)"#, | |
| ), | |
| ( | |
| mod tests { | |
| "MAP {'a': 1, 'b': 2}", | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::Dictionary( | |
| - Box::new(DataType::Int32), | |
| - Box::new(ScalarValue::Utf8(Some("foo".into()))), | |
| - )), | |
| + Expr::Literal( | |
| + ScalarValue::Dictionary( | |
| + Box::new(DataType::Int32), | |
| + Box::new(ScalarValue::Utf8(Some("foo".into()))), | |
| + ), | |
| + None, | |
| + ), | |
| "'foo'", | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::List(Arc::new( | |
| - ListArray::from_iter_primitive::<Int32Type, _, _>(vec![Some(vec![ | |
| + Expr::Literal( | |
| + ScalarValue::List(Arc::new(ListArray::from_iter_primitive::< | |
| + Int32Type, | |
| + _, | |
| + _, | |
| + >(vec![Some(vec![ | |
| Some(1), | |
| Some(2), | |
| Some(3), | |
| - ])]), | |
| - ))), | |
| + ])]))), | |
| + None, | |
| + ), | |
| "[1, 2, 3]", | |
| ), | |
| ( | |
| - Expr::Literal(ScalarValue::LargeList(Arc::new( | |
| - LargeListArray::from_iter_primitive::<Int32Type, _, _>(vec![Some( | |
| - vec![Some(1), Some(2), Some(3)], | |
| - )]), | |
| - ))), | |
| + Expr::Literal( | |
| + ScalarValue::LargeList(Arc::new( | |
| + LargeListArray::from_iter_primitive::<Int32Type, _, _>(vec![ | |
| + Some(vec![Some(1), Some(2), Some(3)]), | |
| + ]), | |
| + )), | |
| + None, | |
| + ), | |
| "[1, 2, 3]", | |
| ), | |
| ( | |
| mod tests { | |
| #[test] | |
| fn test_float_scalar_to_expr() { | |
| let tests = [ | |
| - (Expr::Literal(ScalarValue::Float64(Some(3f64))), "3.0"), | |
| - (Expr::Literal(ScalarValue::Float64(Some(3.1f64))), "3.1"), | |
| - (Expr::Literal(ScalarValue::Float32(Some(-2f32))), "-2.0"), | |
| + (Expr::Literal(ScalarValue::Float64(Some(3f64)), None), "3.0"), | |
| ( | |
| - Expr::Literal(ScalarValue::Float32(Some(-2.989f32))), | |
| + Expr::Literal(ScalarValue::Float64(Some(3.1f64)), None), | |
| + "3.1", | |
| + ), | |
| + ( | |
| + Expr::Literal(ScalarValue::Float32(Some(-2f32)), None), | |
| + "-2.0", | |
| + ), | |
| + ( | |
| + Expr::Literal(ScalarValue::Float32(Some(-2.989f32)), None), | |
| "-2.989", | |
| ), | |
| ]; | |
| mod tests { | |
| let tests = [ | |
| ( | |
| Expr::Cast(Cast { | |
| - expr: Box::new(Expr::Literal(ScalarValue::Utf8(Some( | |
| - "blah".to_string(), | |
| - )))), | |
| + expr: Box::new(Expr::Literal( | |
| + ScalarValue::Utf8(Some("blah".to_string())), | |
| + None, | |
| + )), | |
| data_type: DataType::Binary, | |
| }), | |
| "'blah'", | |
| ), | |
| ( | |
| Expr::Cast(Cast { | |
| - expr: Box::new(Expr::Literal(ScalarValue::Utf8(Some( | |
| - "blah".to_string(), | |
| - )))), | |
| + expr: Box::new(Expr::Literal( | |
| + ScalarValue::Utf8(Some("blah".to_string())), | |
| + None, | |
| + )), | |
| data_type: DataType::BinaryView, | |
| }), | |
| "'blah'", | |
| mod tests { | |
| let expr = ScalarUDF::new_from_impl( | |
| datafusion_functions::datetime::date_part::DatePartFunc::new(), | |
| ) | |
| - .call(vec![Expr::Literal(ScalarValue::new_utf8(unit)), col("x")]); | |
| + .call(vec![ | |
| + Expr::Literal(ScalarValue::new_utf8(unit), None), | |
| + col("x"), | |
| + ]); | |
| let ast = unparser.expr_to_sql(&expr)?; | |
| let actual = format!("{ast}"); | |
| mod tests { | |
| (&mysql_dialect, "DATETIME"), | |
| ] { | |
| let unparser = Unparser::new(dialect); | |
| - let expr = Expr::Literal(ScalarValue::TimestampMillisecond( | |
| - Some(1738285549123), | |
| + let expr = Expr::Literal( | |
| + ScalarValue::TimestampMillisecond(Some(1738285549123), None), | |
| None, | |
| - )); | |
| + ); | |
| let ast = unparser.expr_to_sql(&expr)?; | |
| let actual = format!("{ast}"); | |
| mod tests { | |
| fn test_cast_value_to_dict_expr() { | |
| let tests = [( | |
| Expr::Cast(Cast { | |
| - expr: Box::new(Expr::Literal(ScalarValue::Utf8(Some( | |
| - "variation".to_string(), | |
| - )))), | |
| + expr: Box::new(Expr::Literal( | |
| + ScalarValue::Utf8(Some("variation".to_string())), | |
| + None, | |
| + )), | |
| data_type: DataType::Dictionary(Box::new(Int8), Box::new(DataType::Utf8)), | |
| }), | |
| "'variation'", | |
| mod tests { | |
| expr: Box::new(col("a")), | |
| data_type: DataType::Float64, | |
| }), | |
| - Expr::Literal(ScalarValue::Int64(Some(2))), | |
| + Expr::Literal(ScalarValue::Int64(Some(2)), None), | |
| ], | |
| }); | |
| let ast = unparser.expr_to_sql(&expr)?; | |
| mod tests { | |
| datafusion_functions::datetime::date_trunc::DateTruncFunc::new(), | |
| )), | |
| args: vec![ | |
| - Expr::Literal(ScalarValue::Utf8(Some(precision.to_string()))), | |
| + Expr::Literal(ScalarValue::Utf8(Some(precision.to_string())), None), | |
| col("date_col"), | |
| ], | |
| }); | |
| diff --git a/datafusion/sql/src/unparser/plan.rs b/datafusion/sql/src/unparser/plan.rs | |
| index e89e25ddb..f66776170 100644 | |
| --- a/datafusion/sql/src/unparser/plan.rs | |
| +++ b/datafusion/sql/src/unparser/plan.rs | |
| impl Unparser<'_> { | |
| if project_vec.is_empty() { | |
| builder = builder.project(vec![Expr::Literal( | |
| ScalarValue::Int64(Some(1)), | |
| + None, | |
| )])?; | |
| } else { | |
| let project_columns = project_vec | |
| diff --git a/datafusion/sql/src/unparser/utils.rs b/datafusion/sql/src/unparser/utils.rs | |
| index c36ffbfe5..89fa392c1 100644 | |
| --- a/datafusion/sql/src/unparser/utils.rs | |
| +++ b/datafusion/sql/src/unparser/utils.rs | |
| pub(crate) fn date_part_to_sql( | |
| match (style, date_part_args.len()) { | |
| (DateFieldExtractStyle::Extract, 2) => { | |
| let date_expr = unparser.expr_to_sql(&date_part_args[1])?; | |
| - if let Expr::Literal(ScalarValue::Utf8(Some(field))) = &date_part_args[0] { | |
| + if let Expr::Literal(ScalarValue::Utf8(Some(field)), _) = &date_part_args[0] { | |
| let field = match field.to_lowercase().as_str() { | |
| "year" => ast::DateTimeField::Year, | |
| "month" => ast::DateTimeField::Month, | |
| pub(crate) fn date_part_to_sql( | |
| (DateFieldExtractStyle::Strftime, 2) => { | |
| let column = unparser.expr_to_sql(&date_part_args[1])?; | |
| - if let Expr::Literal(ScalarValue::Utf8(Some(field))) = &date_part_args[0] { | |
| + if let Expr::Literal(ScalarValue::Utf8(Some(field)), _) = &date_part_args[0] { | |
| let field = match field.to_lowercase().as_str() { | |
| "year" => "%Y", | |
| "month" => "%m", | |
| pub(crate) fn sqlite_from_unixtime_to_sql( | |
| "datetime", | |
| &[ | |
| from_unixtime_args[0].clone(), | |
| - Expr::Literal(ScalarValue::Utf8(Some("unixepoch".to_string()))), | |
| + Expr::Literal(ScalarValue::Utf8(Some("unixepoch".to_string())), None), | |
| ], | |
| )?)) | |
| } | |
| pub(crate) fn sqlite_date_trunc_to_sql( | |
| ); | |
| } | |
| - if let Expr::Literal(ScalarValue::Utf8(Some(unit))) = &date_trunc_args[0] { | |
| + if let Expr::Literal(ScalarValue::Utf8(Some(unit)), _) = &date_trunc_args[0] { | |
| let format = match unit.to_lowercase().as_str() { | |
| "year" => "%Y", | |
| "month" => "%Y-%m", | |
| pub(crate) fn sqlite_date_trunc_to_sql( | |
| return Ok(Some(unparser.scalar_function_to_sql( | |
| "strftime", | |
| &[ | |
| - Expr::Literal(ScalarValue::Utf8(Some(format.to_string()))), | |
| + Expr::Literal(ScalarValue::Utf8(Some(format.to_string())), None), | |
| date_trunc_args[1].clone(), | |
| ], | |
| )?)); | |
| diff --git a/datafusion/sql/src/utils.rs b/datafusion/sql/src/utils.rs | |
| index 067da40cf..52832e132 100644 | |
| --- a/datafusion/sql/src/utils.rs | |
| +++ b/datafusion/sql/src/utils.rs | |
| pub(crate) fn resolve_positions_to_exprs( | |
| match expr { | |
| // sql_expr_to_logical_expr maps number to i64 | |
| // https://github.com/apache/datafusion/blob/8d175c759e17190980f270b5894348dc4cff9bbf/datafusion/src/sql/planner.rs#L882-L887 | |
| - Expr::Literal(ScalarValue::Int64(Some(position))) | |
| + Expr::Literal(ScalarValue::Int64(Some(position)), _) | |
| if position > 0_i64 && position <= select_exprs.len() as i64 => | |
| { | |
| let index = (position - 1) as usize; | |
| pub(crate) fn resolve_positions_to_exprs( | |
| _ => select_expr.clone(), | |
| }) | |
| } | |
| - Expr::Literal(ScalarValue::Int64(Some(position))) => plan_err!( | |
| + Expr::Literal(ScalarValue::Int64(Some(position)), _) => plan_err!( | |
| "Cannot find column with position {} in SELECT clause. Valid columns: 1 to {}", | |
| position, select_exprs.len() | |
| ), | |
| diff --git a/datafusion/substrait/src/logical_plan/consumer/expr/aggregate_function.rs b/datafusion/substrait/src/logical_plan/consumer/expr/aggregate_function.rs | |
| index 7687d9f76..114fe1e7a 100644 | |
| --- a/datafusion/substrait/src/logical_plan/consumer/expr/aggregate_function.rs | |
| +++ b/datafusion/substrait/src/logical_plan/consumer/expr/aggregate_function.rs | |
| pub async fn from_substrait_agg_func( | |
| // we inject a dummy argument that does not affect the query, but allows | |
| // us to bypass this limitation. | |
| let args = if udaf.name() == "count" && args.is_empty() { | |
| - vec![Expr::Literal(ScalarValue::Int64(Some(1)))] | |
| + vec![Expr::Literal(ScalarValue::Int64(Some(1)), None)] | |
| } else { | |
| args | |
| }; | |
| diff --git a/datafusion/substrait/src/logical_plan/consumer/expr/literal.rs b/datafusion/substrait/src/logical_plan/consumer/expr/literal.rs | |
| index 5adc137d9..d054e5267 100644 | |
| --- a/datafusion/substrait/src/logical_plan/consumer/expr/literal.rs | |
| +++ b/datafusion/substrait/src/logical_plan/consumer/expr/literal.rs | |
| pub async fn from_literal( | |
| expr: &Literal, | |
| ) -> datafusion::common::Result<Expr> { | |
| let scalar_value = from_substrait_literal_without_names(consumer, expr)?; | |
| - Ok(Expr::Literal(scalar_value)) | |
| + Ok(Expr::Literal(scalar_value, None)) | |
| } | |
| pub(crate) fn from_substrait_literal_without_names( | |
| diff --git a/datafusion/substrait/src/logical_plan/consumer/expr/scalar_function.rs b/datafusion/substrait/src/logical_plan/consumer/expr/scalar_function.rs | |
| index 027b61124..7797c9352 100644 | |
| --- a/datafusion/substrait/src/logical_plan/consumer/expr/scalar_function.rs | |
| +++ b/datafusion/substrait/src/logical_plan/consumer/expr/scalar_function.rs | |
| impl BuiltinExprBuilder { | |
| .await?; | |
| match escape_char_expr { | |
| - Expr::Literal(ScalarValue::Utf8(escape_char_string)) => { | |
| + Expr::Literal(ScalarValue::Utf8(escape_char_string), _) => { | |
| // Convert Option<String> to Option<char> | |
| escape_char_string.and_then(|s| s.chars().next()) | |
| } | |
| mod tests { | |
| fn int64_literals(integers: &[i64]) -> Vec<Expr> { | |
| integers | |
| .iter() | |
| - .map(|value| Expr::Literal(ScalarValue::Int64(Some(*value)))) | |
| + .map(|value| Expr::Literal(ScalarValue::Int64(Some(*value)), None)) | |
| .collect() | |
| } | |
| diff --git a/datafusion/substrait/src/logical_plan/consumer/expr/window_function.rs b/datafusion/substrait/src/logical_plan/consumer/expr/window_function.rs | |
| index 4a7fde256..80b643a54 100644 | |
| --- a/datafusion/substrait/src/logical_plan/consumer/expr/window_function.rs | |
| +++ b/datafusion/substrait/src/logical_plan/consumer/expr/window_function.rs | |
| pub async fn from_window_function( | |
| // we inject a dummy argument that does not affect the query, but allows | |
| // us to bypass this limitation. | |
| let args = if fun.name() == "count" && window.arguments.is_empty() { | |
| - vec![Expr::Literal(ScalarValue::Int64(Some(1)))] | |
| + vec![Expr::Literal(ScalarValue::Int64(Some(1)), None)] | |
| } else { | |
| from_substrait_func_args(consumer, &window.arguments, input_schema).await? | |
| }; | |
| diff --git a/datafusion/substrait/src/logical_plan/consumer/rel/read_rel.rs b/datafusion/substrait/src/logical_plan/consumer/rel/read_rel.rs | |
| index 47af44c69..f1cbd16d2 100644 | |
| --- a/datafusion/substrait/src/logical_plan/consumer/rel/read_rel.rs | |
| +++ b/datafusion/substrait/src/logical_plan/consumer/rel/read_rel.rs | |
| pub async fn from_read_rel( | |
| lit, | |
| &named_struct.names, | |
| &mut name_idx, | |
| - )?)) | |
| + )?, None)) | |
| }) | |
| .collect::<datafusion::common::Result<_>>()?; | |
| if name_idx != named_struct.names.len() { | |
| diff --git a/datafusion/substrait/src/logical_plan/producer/expr/cast.rs b/datafusion/substrait/src/logical_plan/producer/expr/cast.rs | |
| index b69474f09..9741dcdd1 100644 | |
| --- a/datafusion/substrait/src/logical_plan/producer/expr/cast.rs | |
| +++ b/datafusion/substrait/src/logical_plan/producer/expr/cast.rs | |
| pub fn from_cast( | |
| ) -> datafusion::common::Result<Expression> { | |
| let Cast { expr, data_type } = cast; | |
| // since substrait Null must be typed, so if we see a cast(null, dt), we make it a typed null | |
| - if let Expr::Literal(lit) = expr.as_ref() { | |
| + if let Expr::Literal(lit, _) = expr.as_ref() { | |
| // only the untyped(a null scalar value) null literal need this special handling | |
| // since all other kind of nulls are already typed and can be handled by substrait | |
| // e.g. null::<Int32Type> or null::<Utf8Type> | |
| mod tests { | |
| let empty_schema = DFSchemaRef::new(DFSchema::empty()); | |
| let field = Field::new("out", DataType::Int32, false); | |
| - let expr = Expr::Literal(ScalarValue::Null) | |
| + let expr = Expr::Literal(ScalarValue::Null, None) | |
| .cast_to(&DataType::Int32, &empty_schema) | |
| .unwrap(); | |
| mod tests { | |
| } | |
| // a typed null should not be folded | |
| - let expr = Expr::Literal(ScalarValue::Int64(None)) | |
| + let expr = Expr::Literal(ScalarValue::Int64(None), None) | |
| .cast_to(&DataType::Int32, &empty_schema) | |
| .unwrap(); | |
| diff --git a/datafusion/substrait/src/logical_plan/producer/expr/mod.rs b/datafusion/substrait/src/logical_plan/producer/expr/mod.rs | |
| index fbc4d3754..42e1f962f 100644 | |
| --- a/datafusion/substrait/src/logical_plan/producer/expr/mod.rs | |
| +++ b/datafusion/substrait/src/logical_plan/producer/expr/mod.rs | |
| pub fn to_substrait_rex( | |
| Expr::ScalarVariable(_, _) => { | |
| not_impl_err!("Cannot convert {expr:?} to Substrait") | |
| } | |
| - Expr::Literal(expr) => producer.handle_literal(expr), | |
| + Expr::Literal(expr, _) => producer.handle_literal(expr), | |
| Expr::BinaryExpr(expr) => producer.handle_binary_expr(expr, schema), | |
| Expr::Like(expr) => producer.handle_like(expr, schema), | |
| Expr::SimilarTo(_) => not_impl_err!("Cannot convert {expr:?} to Substrait"), | |
| mod tests { | |
| let state = SessionStateBuilder::default().build(); | |
| // One expression, empty input schema | |
| - let expr = Expr::Literal(ScalarValue::Int32(Some(42))); | |
| + let expr = Expr::Literal(ScalarValue::Int32(Some(42)), None); | |
| let field = Field::new("out", DataType::Int32, false); | |
| let empty_schema = DFSchemaRef::new(DFSchema::empty()); | |
| let substrait = | |
| diff --git a/datafusion/substrait/src/logical_plan/producer/rel/read_rel.rs b/datafusion/substrait/src/logical_plan/producer/rel/read_rel.rs | |
| index e4e0ab11c..212874e79 100644 | |
| --- a/datafusion/substrait/src/logical_plan/producer/rel/read_rel.rs | |
| +++ b/datafusion/substrait/src/logical_plan/producer/rel/read_rel.rs | |
| pub fn from_values( | |
| let fields = row | |
| .iter() | |
| .map(|v| match v { | |
| - Expr::Literal(sv) => to_substrait_literal(producer, sv), | |
| + Expr::Literal(sv, _) => to_substrait_literal(producer, sv), | |
| Expr::Alias(alias) => match alias.expr.as_ref() { | |
| // The schema gives us the names, so we can skip aliases | |
| - Expr::Literal(sv) => to_substrait_literal(producer, sv), | |
| + Expr::Literal(sv, _) => to_substrait_literal(producer, sv), | |
| _ => Err(substrait_datafusion_err!( | |
| "Only literal types can be aliased in Virtual Tables, got: {}", alias.expr.variant_name() | |
| )), | |