1use std::borrow::Cow;
8use std::cmp::Ordering;
9use std::collections::HashSet;
10use std::fmt::{self, Display, Formatter, Write};
11use std::hash::{Hash, Hasher};
12use std::mem;
13use std::sync::Arc;
14
15use crate::expr_fn::binary_expr;
16use crate::function::WindowFunctionSimplification;
17use crate::higher_order_function::{HigherOrderUDF, resolve_lambda_variables};
18use crate::logical_plan::Subquery;
19use crate::type_coercion::functions::value_fields_with_higher_order_udf;
20use crate::{AggregateUDF, LambdaParametersProgress, ValueOrLambda, Volatility};
21use crate::{ExprSchemable, Operator, Signature, WindowFrame, WindowUDF};
22
23use arrow::datatypes::{DataType, Field, FieldRef, Metadata};
24use datafusion_common::cse::{HashNode, NormalizeEq, Normalizeable};
25use datafusion_common::datatype::DataTypeExt;
26use datafusion_common::metadata::format_type_and_metadata;
27use datafusion_common::tree_node::{
28 Transformed, TransformedResult, TreeNode, TreeNodeContainer, TreeNodeRecursion,
29};
30use datafusion_common::{
31 Column, DFSchema, ExprSchema, HashMap, Result, ScalarValue, Spans, TableReference,
32 plan_err,
33};
34use datafusion_expr_common::placement::ExpressionPlacement;
35use datafusion_functions_window_common::field::WindowUDFFieldArgs;
36#[cfg(feature = "sql")]
37pub use sqlparser::ast::{
38 ExceptSelectItem, ExcludeSelectItem, IlikeSelectItem, RenameSelectItem,
39 ReplaceSelectElement,
40};
41#[cfg(not(feature = "sql"))]
43pub use crate::sql::{
44 ExceptSelectItem, ExcludeSelectItem, IlikeSelectItem, RenameSelectItem,
45 ReplaceSelectElement,
46};
47
48pub use datafusion_common::metadata::FieldMetadata;
50use datafusion_common::metadata::ScalarAndMetadata;
51
52#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
55pub enum NullTreatment {
56 IgnoreNulls,
57 RespectNulls,
58}
59
60impl Display for NullTreatment {
61 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
62 f.write_str(match self {
63 NullTreatment::IgnoreNulls => "IGNORE NULLS",
64 NullTreatment::RespectNulls => "RESPECT NULLS",
65 })
66 }
67}
68
69#[cfg(feature = "sql")]
70impl From<sqlparser::ast::NullTreatment> for NullTreatment {
71 fn from(value: sqlparser::ast::NullTreatment) -> Self {
72 match value {
73 sqlparser::ast::NullTreatment::IgnoreNulls => Self::IgnoreNulls,
74 sqlparser::ast::NullTreatment::RespectNulls => Self::RespectNulls,
75 }
76 }
77}
78
79#[derive(Clone, PartialEq, PartialOrd, Eq, Debug, Hash)]
314pub enum Expr {
315 Alias(Alias),
317 Column(Column),
319 ScalarVariable(FieldRef, Vec<String>),
321 Literal(ScalarValue, Option<FieldMetadata>),
323 BinaryExpr(BinaryExpr),
325 Like(Like),
327 SimilarTo(Like),
329 Not(Box<Expr>),
331 IsNotNull(Box<Expr>),
333 IsNull(Box<Expr>),
335 IsTrue(Box<Expr>),
337 IsFalse(Box<Expr>),
339 IsUnknown(Box<Expr>),
341 IsNotTrue(Box<Expr>),
343 IsNotFalse(Box<Expr>),
345 IsNotUnknown(Box<Expr>),
347 Negative(Box<Expr>),
349 Between(Between),
351 Case(Case),
353 Cast(Cast),
356 TryCast(TryCast),
359 ScalarFunction(ScalarFunction),
361 AggregateFunction(AggregateFunction),
368 WindowFunction(Box<WindowFunction>),
370 InList(InList),
372 Exists(Exists),
374 InSubquery(InSubquery),
376 SetComparison(SetComparison),
378 ScalarSubquery(Subquery),
380 #[deprecated(
386 since = "46.0.0",
387 note = "A wildcard needs to be resolved to concrete expressions when constructing the logical plan. See https://github.com/apache/datafusion/issues/7765"
388 )]
389 Wildcard {
390 qualifier: Option<TableReference>,
391 options: Box<WildcardOptions>,
392 },
393 GroupingSet(GroupingSet),
396 Placeholder(Placeholder),
399 OuterReferenceColumn(FieldRef, Column),
402 Unnest(Unnest),
404 HigherOrderFunction(HigherOrderFunction),
418 Lambda(Lambda),
420 LambdaVariable(LambdaVariable),
422}
423
424#[derive(Clone, Eq, PartialOrd, Debug)]
426pub struct HigherOrderFunction {
427 pub func: Arc<HigherOrderUDF>,
429 pub args: Vec<Expr>,
431}
432
433impl HigherOrderFunction {
434 pub fn new(func: Arc<HigherOrderUDF>, args: Vec<Expr>) -> Self {
436 Self { func, args }
437 }
438
439 pub fn name(&self) -> &str {
440 self.func.name()
441 }
442
443 pub fn lambda_parameters(
451 &self,
452 schema: &dyn ExprSchema,
453 ) -> Result<Vec<Vec<FieldRef>>> {
454 let args = self
455 .args
456 .iter()
457 .map(|e| match e {
458 Expr::Lambda(lambda) => {
459 Ok(ValueOrLambda::Lambda(Some(lambda.body.to_field(schema)?.1)))
460 }
461 _ => Ok(ValueOrLambda::Value(e.to_field(schema)?.1)),
462 })
463 .collect::<Result<Vec<_>>>()?;
464
465 let coerced_fields =
466 value_fields_with_higher_order_udf(&args, self.func.as_ref())?;
467
468 match self.func.lambda_parameters(0, &coerced_fields)? {
469 LambdaParametersProgress::Partial(_) => plan_err!(
470 "{} lambda_parameters returned a partial result when the return type of all it's lambdas were provided",
471 self.name()
472 ),
473 LambdaParametersProgress::Complete(items) => Ok(items),
474 }
475 }
476}
477
478impl Hash for HigherOrderFunction {
479 fn hash<H: Hasher>(&self, state: &mut H) {
480 self.func.hash(state);
481 self.args.hash(state);
482 }
483}
484
485impl PartialEq for HigherOrderFunction {
486 fn eq(&self, other: &Self) -> bool {
487 self.func.as_ref() == other.func.as_ref() && self.args == other.args
488 }
489}
490
491#[derive(Clone, PartialEq, PartialOrd, Eq, Debug, Hash)]
507pub struct LambdaVariable {
508 pub name: String,
509 pub field: Option<FieldRef>,
510 pub spans: Spans,
511}
512
513impl LambdaVariable {
514 pub fn new(name: String, field: Option<FieldRef>) -> Self {
521 Self {
522 name,
523 field,
524 spans: Spans::new(),
525 }
526 }
527
528 pub fn spans_mut(&mut self) -> &mut Spans {
529 &mut self.spans
530 }
531}
532
533impl Default for Expr {
534 fn default() -> Self {
535 Expr::Literal(ScalarValue::Null, None)
536 }
537}
538
539impl AsRef<Expr> for Expr {
540 fn as_ref(&self) -> &Expr {
541 self
542 }
543}
544
545impl From<Column> for Expr {
547 fn from(value: Column) -> Self {
548 Expr::Column(value)
549 }
550}
551
552impl From<WindowFunction> for Expr {
554 fn from(value: WindowFunction) -> Self {
555 Expr::WindowFunction(Box::new(value))
556 }
557}
558
559impl From<ScalarAndMetadata> for Expr {
561 fn from(value: ScalarAndMetadata) -> Self {
562 let (value, metadata) = value.into_inner();
563 Expr::Literal(value, metadata)
564 }
565}
566
567impl<'a> From<(Option<&'a TableReference>, &'a FieldRef)> for Expr {
572 fn from(value: (Option<&'a TableReference>, &'a FieldRef)) -> Self {
573 Expr::from(Column::from(value))
574 }
575}
576
577impl<'a> TreeNodeContainer<'a, Self> for Expr {
578 fn apply_elements<F: FnMut(&'a Self) -> Result<TreeNodeRecursion>>(
579 &'a self,
580 mut f: F,
581 ) -> Result<TreeNodeRecursion> {
582 f(self)
583 }
584
585 fn map_elements<F: FnMut(Self) -> Result<Transformed<Self>>>(
586 self,
587 mut f: F,
588 ) -> Result<Transformed<Self>> {
589 f(self)
590 }
591}
592
593pub type SchemaFieldMetadata = Metadata;
614
615#[deprecated(
637 since = "56.0.0",
638 note = "UNION now merges metadata with `datafusion_common::metadata::merge_metadata_for_union`"
639)]
640pub fn intersect_metadata_for_union<'a>(
641 metadatas: impl IntoIterator<Item = &'a SchemaFieldMetadata>,
642) -> SchemaFieldMetadata {
643 let mut intersected: Option<SchemaFieldMetadata> = None;
644
645 for metadata in metadatas {
646 if metadata.is_empty() {
649 continue;
650 }
651 match &mut intersected {
652 None => {
653 intersected = Some(metadata.clone());
654 }
655 Some(current) => {
656 current.retain(|k, v| metadata.get(k) == Some(&*v));
658 }
659 }
660 }
661
662 intersected.unwrap_or_default()
663}
664
665#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
672pub struct Unnest {
673 pub expr: Box<Expr>,
674 pub outer: bool,
677}
678
679impl Unnest {
680 pub fn new(expr: Expr) -> Self {
682 Self {
683 expr: Box::new(expr),
684 outer: false,
685 }
686 }
687
688 pub fn new_boxed(boxed: Box<Expr>) -> Self {
690 Self {
691 expr: boxed,
692 outer: false,
693 }
694 }
695
696 pub fn new_outer(expr: Expr) -> Self {
699 Self {
700 expr: Box::new(expr),
701 outer: true,
702 }
703 }
704}
705
706#[derive(Clone, PartialEq, Eq, Debug)]
708pub struct Alias {
709 pub expr: Box<Expr>,
710 pub relation: Option<TableReference>,
711 pub name: String,
712 pub metadata: Option<FieldMetadata>,
713}
714
715impl Hash for Alias {
716 fn hash<H: Hasher>(&self, state: &mut H) {
717 self.expr.hash(state);
718 self.relation.hash(state);
719 self.name.hash(state);
720 }
721}
722
723impl PartialOrd for Alias {
724 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
725 let cmp = self.expr.partial_cmp(&other.expr);
726 let Some(Ordering::Equal) = cmp else {
727 return cmp;
728 };
729 let cmp = self.relation.partial_cmp(&other.relation);
730 let Some(Ordering::Equal) = cmp else {
731 return cmp;
732 };
733 self.name
734 .partial_cmp(&other.name)
735 .filter(|cmp| *cmp != Ordering::Equal || self == other)
737 }
738}
739
740impl Alias {
741 pub fn new(
743 expr: Expr,
744 relation: Option<impl Into<TableReference>>,
745 name: impl Into<String>,
746 ) -> Self {
747 Self {
748 expr: Box::new(expr),
749 relation: relation.map(|r| r.into()),
750 name: name.into(),
751 metadata: None,
752 }
753 }
754
755 pub fn with_metadata(mut self, metadata: Option<FieldMetadata>) -> Self {
756 self.metadata = metadata;
757 self
758 }
759
760 #[doc(hidden)]
761 pub fn with_expr(mut self, expr: Expr) -> Self {
762 self.expr = Box::new(expr);
763 self
764 }
765
766 #[doc(hidden)]
767 pub fn try_map_expr(self, f: impl FnOnce(Expr) -> Result<Expr>) -> Result<Expr> {
768 let Alias {
769 expr,
770 relation,
771 name,
772 metadata,
773 } = self;
774 Ok(Expr::Alias(Alias {
775 expr: Box::new(f(*expr)?),
776 relation,
777 name,
778 metadata,
779 }))
780 }
781}
782
783#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
785pub struct BinaryExpr {
786 pub left: Box<Expr>,
788 pub op: Operator,
790 pub right: Box<Expr>,
792}
793
794impl BinaryExpr {
795 pub fn new(left: Box<Expr>, op: Operator, right: Box<Expr>) -> Self {
797 Self { left, op, right }
798 }
799}
800
801impl Display for BinaryExpr {
802 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
803 fn write_child(
809 f: &mut Formatter<'_>,
810 expr: &Expr,
811 precedence: u8,
812 ) -> fmt::Result {
813 match expr {
814 Expr::BinaryExpr(child) => {
815 let p = child.op.precedence();
816 if p == 0 || p < precedence {
817 write!(f, "({child})")?;
818 } else {
819 write!(f, "{child}")?;
820 }
821 }
822 _ => write!(f, "{expr}")?,
823 }
824 Ok(())
825 }
826
827 let precedence = self.op.precedence();
828 write_child(f, self.left.as_ref(), precedence)?;
829 write!(f, " {} ", self.op)?;
830 write_child(f, self.right.as_ref(), precedence)
831 }
832}
833
834#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Hash)]
858pub struct Case {
859 pub expr: Option<Box<Expr>>,
861 pub when_then_expr: Vec<(Box<Expr>, Box<Expr>)>,
863 pub else_expr: Option<Box<Expr>>,
865}
866
867impl Case {
868 pub fn new(
870 expr: Option<Box<Expr>>,
871 when_then_expr: Vec<(Box<Expr>, Box<Expr>)>,
872 else_expr: Option<Box<Expr>>,
873 ) -> Self {
874 Self {
875 expr,
876 when_then_expr,
877 else_expr,
878 }
879 }
880}
881
882#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
884pub struct Like {
885 pub negated: bool,
886 pub expr: Box<Expr>,
887 pub pattern: Box<Expr>,
888 pub escape_char: Option<char>,
889 pub case_insensitive: bool,
891}
892
893impl Like {
894 pub fn new(
896 negated: bool,
897 expr: Box<Expr>,
898 pattern: Box<Expr>,
899 escape_char: Option<char>,
900 case_insensitive: bool,
901 ) -> Self {
902 Self {
903 negated,
904 expr,
905 pattern,
906 escape_char,
907 case_insensitive,
908 }
909 }
910}
911
912#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
914pub struct Between {
915 pub expr: Box<Expr>,
917 pub negated: bool,
919 pub low: Box<Expr>,
921 pub high: Box<Expr>,
923}
924
925impl Between {
926 pub fn new(expr: Box<Expr>, negated: bool, low: Box<Expr>, high: Box<Expr>) -> Self {
928 Self {
929 expr,
930 negated,
931 low,
932 high,
933 }
934 }
935}
936
937#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
941pub struct ScalarFunction {
942 pub func: Arc<crate::ScalarUDF>,
944 pub args: Vec<Expr>,
946}
947
948impl ScalarFunction {
949 pub fn name(&self) -> &str {
951 self.func.name()
952 }
953}
954
955impl ScalarFunction {
956 pub fn new_udf(udf: Arc<crate::ScalarUDF>, args: Vec<Expr>) -> Self {
960 Self { func: udf, args }
961 }
962}
963
964#[derive(Clone, PartialEq, Eq, Hash, Debug)]
966pub enum GetFieldAccess {
967 NamedStructField { name: ScalarValue },
969 ListIndex { key: Box<Expr> },
971 ListRange {
973 start: Box<Expr>,
974 stop: Box<Expr>,
975 stride: Box<Expr>,
976 },
977}
978
979#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
981pub struct Cast {
982 pub expr: Box<Expr>,
984 pub field: FieldRef,
986}
987
988impl Cast {
989 pub fn new(expr: Box<Expr>, data_type: DataType) -> Self {
991 Self {
992 expr,
993 field: data_type.into_nullable_field_ref(),
994 }
995 }
996
997 pub fn new_from_field(expr: Box<Expr>, field: FieldRef) -> Self {
998 Self { expr, field }
999 }
1000}
1001
1002#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1004pub struct TryCast {
1005 pub expr: Box<Expr>,
1007 pub field: FieldRef,
1009}
1010
1011impl TryCast {
1012 pub fn new(expr: Box<Expr>, data_type: DataType) -> Self {
1014 Self {
1015 expr,
1016 field: data_type.into_nullable_field_ref(),
1017 }
1018 }
1019
1020 pub fn new_from_field(expr: Box<Expr>, field: FieldRef) -> Self {
1021 Self { expr, field }
1022 }
1023}
1024
1025#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1027pub struct Sort {
1028 pub expr: Expr,
1030 pub asc: bool,
1032 pub nulls_first: bool,
1034}
1035
1036impl Sort {
1037 pub fn new(expr: Expr, asc: bool, nulls_first: bool) -> Self {
1039 Self {
1040 expr,
1041 asc,
1042 nulls_first,
1043 }
1044 }
1045
1046 pub fn reverse(&self) -> Self {
1048 Self {
1049 expr: self.expr.clone(),
1050 asc: !self.asc,
1051 nulls_first: !self.nulls_first,
1052 }
1053 }
1054
1055 pub fn with_expr(&self, expr: Expr) -> Self {
1057 Self {
1058 expr,
1059 asc: self.asc,
1060 nulls_first: self.nulls_first,
1061 }
1062 }
1063}
1064
1065impl Display for Sort {
1066 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1067 write!(f, "{}", self.expr)?;
1068 if self.asc {
1069 write!(f, " ASC")?;
1070 } else {
1071 write!(f, " DESC")?;
1072 }
1073 if self.nulls_first {
1074 write!(f, " NULLS FIRST")?;
1075 } else {
1076 write!(f, " NULLS LAST")?;
1077 }
1078 Ok(())
1079 }
1080}
1081
1082impl<'a> TreeNodeContainer<'a, Expr> for Sort {
1083 fn apply_elements<F: FnMut(&'a Expr) -> Result<TreeNodeRecursion>>(
1084 &'a self,
1085 f: F,
1086 ) -> Result<TreeNodeRecursion> {
1087 self.expr.apply_elements(f)
1088 }
1089
1090 fn map_elements<F: FnMut(Expr) -> Result<Transformed<Expr>>>(
1091 self,
1092 f: F,
1093 ) -> Result<Transformed<Self>> {
1094 self.expr
1095 .map_elements(f)?
1096 .map_data(|expr| Ok(Self { expr, ..self }))
1097 }
1098}
1099
1100#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1106pub struct AggregateFunction {
1107 pub func: Arc<AggregateUDF>,
1109 pub params: AggregateFunctionParams,
1110}
1111
1112#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1113pub struct AggregateFunctionParams {
1114 pub args: Vec<Expr>,
1115 pub distinct: bool,
1117 pub filter: Option<Box<Expr>>,
1119 pub order_by: Vec<Sort>,
1121 pub null_treatment: Option<NullTreatment>,
1122}
1123
1124impl AggregateFunction {
1125 pub fn new_udf(
1127 func: Arc<AggregateUDF>,
1128 args: Vec<Expr>,
1129 distinct: bool,
1130 filter: Option<Box<Expr>>,
1131 order_by: Vec<Sort>,
1132 null_treatment: Option<NullTreatment>,
1133 ) -> Self {
1134 Self {
1135 func,
1136 params: AggregateFunctionParams {
1137 args,
1138 distinct,
1139 filter,
1140 order_by,
1141 null_treatment,
1142 },
1143 }
1144 }
1145}
1146
1147#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
1153pub enum WindowFunctionDefinition {
1154 AggregateUDF(Arc<AggregateUDF>),
1156 WindowUDF(Arc<WindowUDF>),
1158}
1159
1160impl WindowFunctionDefinition {
1161 pub fn return_field(
1163 &self,
1164 input_expr_fields: &[FieldRef],
1165 display_name: &str,
1166 ) -> Result<FieldRef> {
1167 match self {
1168 WindowFunctionDefinition::AggregateUDF(fun) => {
1169 fun.return_field(input_expr_fields)
1170 }
1171 WindowFunctionDefinition::WindowUDF(fun) => {
1172 fun.field(WindowUDFFieldArgs::new(input_expr_fields, display_name))
1173 }
1174 }
1175 }
1176
1177 pub fn signature(&self) -> Signature {
1179 match self {
1180 WindowFunctionDefinition::AggregateUDF(fun) => fun.signature().clone(),
1181 WindowFunctionDefinition::WindowUDF(fun) => fun.signature().clone(),
1182 }
1183 }
1184
1185 pub fn name(&self) -> &str {
1187 match self {
1188 WindowFunctionDefinition::WindowUDF(fun) => fun.name(),
1189 WindowFunctionDefinition::AggregateUDF(fun) => fun.name(),
1190 }
1191 }
1192
1193 pub fn simplify(&self) -> Option<WindowFunctionSimplification> {
1197 match self {
1198 WindowFunctionDefinition::AggregateUDF(_) => None,
1199 WindowFunctionDefinition::WindowUDF(udwf) => udwf.simplify(),
1200 }
1201 }
1202}
1203
1204impl Display for WindowFunctionDefinition {
1205 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1206 match self {
1207 WindowFunctionDefinition::AggregateUDF(fun) => Display::fmt(fun, f),
1208 WindowFunctionDefinition::WindowUDF(fun) => Display::fmt(fun, f),
1209 }
1210 }
1211}
1212
1213impl From<Arc<AggregateUDF>> for WindowFunctionDefinition {
1214 fn from(value: Arc<AggregateUDF>) -> Self {
1215 Self::AggregateUDF(value)
1216 }
1217}
1218
1219impl From<Arc<WindowUDF>> for WindowFunctionDefinition {
1220 fn from(value: Arc<WindowUDF>) -> Self {
1221 Self::WindowUDF(value)
1222 }
1223}
1224
1225#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1238pub struct WindowFunction {
1239 pub fun: WindowFunctionDefinition,
1241 pub params: WindowFunctionParams,
1242}
1243
1244#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1245pub struct WindowFunctionParams {
1246 pub args: Vec<Expr>,
1248 pub partition_by: Vec<Expr>,
1250 pub order_by: Vec<Sort>,
1252 pub window_frame: WindowFrame,
1254 pub filter: Option<Box<Expr>>,
1256 pub null_treatment: Option<NullTreatment>,
1258 pub distinct: bool,
1260}
1261
1262impl WindowFunction {
1263 pub fn new(fun: impl Into<WindowFunctionDefinition>, args: Vec<Expr>) -> Self {
1266 Self {
1267 fun: fun.into(),
1268 params: WindowFunctionParams {
1269 args,
1270 partition_by: Vec::default(),
1271 order_by: Vec::default(),
1272 window_frame: WindowFrame::new(None),
1273 filter: None,
1274 null_treatment: None,
1275 distinct: false,
1276 },
1277 }
1278 }
1279
1280 pub fn simplify(&self) -> Option<WindowFunctionSimplification> {
1284 self.fun.simplify()
1285 }
1286}
1287
1288#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1290pub struct Exists {
1291 pub subquery: Subquery,
1293 pub negated: bool,
1295}
1296
1297impl Exists {
1298 pub fn new(subquery: Subquery, negated: bool) -> Self {
1300 Self { subquery, negated }
1301 }
1302}
1303
1304#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Hash, Debug)]
1306pub enum SetQuantifier {
1307 Any,
1309 All,
1311}
1312
1313impl Display for SetQuantifier {
1314 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1315 match self {
1316 SetQuantifier::Any => write!(f, "ANY"),
1317 SetQuantifier::All => write!(f, "ALL"),
1318 }
1319 }
1320}
1321
1322#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1324pub struct SetComparison {
1325 pub expr: Box<Expr>,
1327 pub subquery: Subquery,
1329 pub op: Operator,
1331 pub quantifier: SetQuantifier,
1333}
1334
1335impl SetComparison {
1336 pub fn new(
1338 expr: Box<Expr>,
1339 subquery: Subquery,
1340 op: Operator,
1341 quantifier: SetQuantifier,
1342 ) -> Self {
1343 Self {
1344 expr,
1345 subquery,
1346 op,
1347 quantifier,
1348 }
1349 }
1350}
1351
1352#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1354pub struct InList {
1355 pub expr: Box<Expr>,
1357 pub list: Vec<Expr>,
1359 pub negated: bool,
1361}
1362
1363impl InList {
1364 pub fn new(expr: Box<Expr>, list: Vec<Expr>, negated: bool) -> Self {
1366 Self {
1367 expr,
1368 list,
1369 negated,
1370 }
1371 }
1372}
1373
1374#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1376pub struct InSubquery {
1377 pub expr: Box<Expr>,
1379 pub subquery: Subquery,
1381 pub negated: bool,
1383}
1384
1385impl InSubquery {
1386 pub fn new(expr: Box<Expr>, subquery: Subquery, negated: bool) -> Self {
1388 Self {
1389 expr,
1390 subquery,
1391 negated,
1392 }
1393 }
1394}
1395
1396pub fn in_subquery_tuple_values<'a>(
1409 expr: &'a Expr,
1410 subquery: &crate::LogicalPlan,
1411) -> Result<Option<Cow<'a, [Expr]>>> {
1412 let num_columns = subquery.schema().fields().len();
1413 if num_columns <= 1 {
1414 return Ok(None);
1415 }
1416 let values = match expr {
1417 Expr::ScalarFunction(func) if func.func.name() == "struct" => {
1418 Cow::Borrowed(func.args.as_slice())
1419 }
1420 Expr::Literal(ScalarValue::Struct(array), _)
1421 if arrow::array::Array::is_valid(array.as_ref(), 0) =>
1422 {
1423 Cow::Owned(
1424 array
1425 .columns()
1426 .iter()
1427 .map(|column| {
1428 Ok(Expr::Literal(ScalarValue::try_from_array(column, 0)?, None))
1429 })
1430 .collect::<Result<_>>()?,
1431 )
1432 }
1433 _ => return Ok(None),
1434 };
1435 if values.len() != num_columns {
1436 return plan_err!(
1437 "The number of columns in the tuple ({}) must match the number of columns in the subquery ({num_columns})",
1438 values.len()
1439 );
1440 }
1441 Ok(Some(values))
1442}
1443
1444#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1449pub struct Placeholder {
1450 pub id: String,
1452 pub field: Option<FieldRef>,
1454}
1455
1456impl Placeholder {
1457 #[deprecated(since = "51.0.0", note = "Use new_with_field instead")]
1459 pub fn new(id: String, data_type: Option<DataType>) -> Self {
1460 Self {
1461 id,
1462 field: data_type.map(|dt| Arc::new(Field::new("", dt, true))),
1463 }
1464 }
1465
1466 pub fn new_with_field(id: String, field: Option<FieldRef>) -> Self {
1468 Self { id, field }
1469 }
1470}
1471
1472#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1479pub enum GroupingSet {
1480 Rollup(Vec<Expr>),
1482 Cube(Vec<Expr>),
1484 GroupingSets(Vec<Vec<Expr>>),
1486}
1487
1488impl GroupingSet {
1489 pub fn distinct_expr(&self) -> Vec<&Expr> {
1493 match self {
1494 GroupingSet::Rollup(exprs) | GroupingSet::Cube(exprs) => {
1495 exprs.iter().collect()
1496 }
1497 GroupingSet::GroupingSets(groups) => {
1498 let mut exprs: Vec<&Expr> = vec![];
1499 for exp in groups.iter().flatten() {
1500 if !exprs.contains(&exp) {
1501 exprs.push(exp);
1502 }
1503 }
1504 exprs
1505 }
1506 }
1507 }
1508}
1509
1510#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1512pub struct Lambda {
1513 pub params: Vec<String>,
1515 pub body: Box<Expr>,
1517}
1518
1519impl Lambda {
1520 pub fn new(params: Vec<String>, body: Expr) -> Self {
1522 Self {
1523 params,
1524 body: Box::new(body),
1525 }
1526 }
1527}
1528
1529pub fn display_comma_separated<T>(slice: &[T]) -> String
1530where
1531 T: Display,
1532{
1533 use itertools::Itertools;
1534 slice.iter().map(|v| format!("{v}")).join(", ")
1535}
1536
1537#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug, Default)]
1539pub struct WildcardOptions {
1540 pub ilike: Option<IlikeSelectItem>,
1543 pub exclude: Option<ExcludeSelectItem>,
1546 pub except: Option<ExceptSelectItem>,
1550 pub replace: Option<PlannedReplaceSelectItem>,
1555 pub rename: Option<RenameSelectItem>,
1558}
1559
1560impl WildcardOptions {
1561 pub fn with_replace(self, replace: PlannedReplaceSelectItem) -> Self {
1562 WildcardOptions {
1563 ilike: self.ilike,
1564 exclude: self.exclude,
1565 except: self.except,
1566 replace: Some(replace),
1567 rename: self.rename,
1568 }
1569 }
1570}
1571
1572impl Display for WildcardOptions {
1573 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1574 if let Some(ilike) = &self.ilike {
1575 write!(f, " {ilike}")?;
1576 }
1577 if let Some(exclude) = &self.exclude {
1578 write!(f, " {exclude}")?;
1579 }
1580 if let Some(except) = &self.except {
1581 write!(f, " {except}")?;
1582 }
1583 if let Some(replace) = &self.replace {
1584 write!(f, " {replace}")?;
1585 }
1586 if let Some(rename) = &self.rename {
1587 write!(f, " {rename}")?;
1588 }
1589 Ok(())
1590 }
1591}
1592
1593#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug, Default)]
1595pub struct PlannedReplaceSelectItem {
1596 pub items: Vec<ReplaceSelectElement>,
1598 pub planned_expressions: Vec<Expr>,
1600}
1601
1602impl Display for PlannedReplaceSelectItem {
1603 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1604 write!(f, "REPLACE")?;
1605 write!(f, " ({})", display_comma_separated(&self.items))?;
1606 Ok(())
1607 }
1608}
1609
1610impl PlannedReplaceSelectItem {
1611 pub fn items(&self) -> &[ReplaceSelectElement] {
1612 &self.items
1613 }
1614
1615 pub fn expressions(&self) -> &[Expr] {
1616 &self.planned_expressions
1617 }
1618}
1619
1620impl Expr {
1621 pub fn schema_name(&self) -> impl Display + '_ {
1644 SchemaDisplay(self)
1645 }
1646
1647 pub fn human_display(&self) -> impl Display + '_ {
1669 SqlDisplay(self)
1670 }
1671
1672 pub fn qualified_name(&self) -> (Option<TableReference>, String) {
1678 match self {
1679 Expr::Column(Column {
1680 relation,
1681 name,
1682 spans: _,
1683 }) => (relation.clone(), name.clone()),
1684 Expr::Alias(Alias { relation, name, .. }) => (relation.clone(), name.clone()),
1685 _ => (None, self.schema_name().to_string()),
1686 }
1687 }
1688
1689 pub fn placement(&self) -> ExpressionPlacement {
1694 match self {
1695 Expr::Column(_) => ExpressionPlacement::Column,
1696 Expr::Literal(_, _) => ExpressionPlacement::Literal,
1697 Expr::Alias(inner) => inner.expr.placement(),
1698 Expr::ScalarFunction(func) => {
1699 let arg_placements: Vec<_> =
1700 func.args.iter().map(|arg| arg.placement()).collect();
1701 func.func.placement(&arg_placements)
1702 }
1703 _ => ExpressionPlacement::KeepInPlace,
1704 }
1705 }
1706
1707 pub fn variant_name(&self) -> &str {
1710 match self {
1711 Expr::AggregateFunction { .. } => "AggregateFunction",
1712 Expr::Alias(..) => "Alias",
1713 Expr::Between { .. } => "Between",
1714 Expr::BinaryExpr { .. } => "BinaryExpr",
1715 Expr::Case { .. } => "Case",
1716 Expr::Cast { .. } => "Cast",
1717 Expr::Column(..) => "Column",
1718 Expr::OuterReferenceColumn(_, _) => "Outer",
1719 Expr::Exists { .. } => "Exists",
1720 Expr::GroupingSet(..) => "GroupingSet",
1721 Expr::InList { .. } => "InList",
1722 Expr::InSubquery(..) => "InSubquery",
1723 Expr::SetComparison(..) => "SetComparison",
1724 Expr::IsNotNull(..) => "IsNotNull",
1725 Expr::IsNull(..) => "IsNull",
1726 Expr::Like { .. } => "Like",
1727 Expr::SimilarTo { .. } => "RLike",
1728 Expr::IsTrue(..) => "IsTrue",
1729 Expr::IsFalse(..) => "IsFalse",
1730 Expr::IsUnknown(..) => "IsUnknown",
1731 Expr::IsNotTrue(..) => "IsNotTrue",
1732 Expr::IsNotFalse(..) => "IsNotFalse",
1733 Expr::IsNotUnknown(..) => "IsNotUnknown",
1734 Expr::Literal(..) => "Literal",
1735 Expr::Negative(..) => "Negative",
1736 Expr::Not(..) => "Not",
1737 Expr::Placeholder(_) => "Placeholder",
1738 Expr::ScalarFunction(..) => "ScalarFunction",
1739 Expr::ScalarSubquery { .. } => "ScalarSubquery",
1740 Expr::ScalarVariable(..) => "ScalarVariable",
1741 Expr::TryCast { .. } => "TryCast",
1742 Expr::WindowFunction { .. } => "WindowFunction",
1743 #[expect(deprecated)]
1744 Expr::Wildcard { .. } => "Wildcard",
1745 Expr::Unnest { .. } => "Unnest",
1746 Expr::HigherOrderFunction { .. } => "HigherOrderFunction",
1747 Expr::Lambda { .. } => "Lambda",
1748 Expr::LambdaVariable { .. } => "LambdaVariable",
1749 }
1750 }
1751
1752 pub fn eq(self, other: Expr) -> Expr {
1754 binary_expr(self, Operator::Eq, other)
1755 }
1756
1757 pub fn not_eq(self, other: Expr) -> Expr {
1759 binary_expr(self, Operator::NotEq, other)
1760 }
1761
1762 pub fn gt(self, other: Expr) -> Expr {
1764 binary_expr(self, Operator::Gt, other)
1765 }
1766
1767 pub fn gt_eq(self, other: Expr) -> Expr {
1769 binary_expr(self, Operator::GtEq, other)
1770 }
1771
1772 pub fn lt(self, other: Expr) -> Expr {
1774 binary_expr(self, Operator::Lt, other)
1775 }
1776
1777 pub fn lt_eq(self, other: Expr) -> Expr {
1779 binary_expr(self, Operator::LtEq, other)
1780 }
1781
1782 pub fn and(self, other: Expr) -> Expr {
1784 binary_expr(self, Operator::And, other)
1785 }
1786
1787 pub fn or(self, other: Expr) -> Expr {
1789 binary_expr(self, Operator::Or, other)
1790 }
1791
1792 pub fn like(self, other: Expr) -> Expr {
1794 Expr::Like(Like::new(
1795 false,
1796 Box::new(self),
1797 Box::new(other),
1798 None,
1799 false,
1800 ))
1801 }
1802
1803 pub fn not_like(self, other: Expr) -> Expr {
1805 Expr::Like(Like::new(
1806 true,
1807 Box::new(self),
1808 Box::new(other),
1809 None,
1810 false,
1811 ))
1812 }
1813
1814 pub fn ilike(self, other: Expr) -> Expr {
1816 Expr::Like(Like::new(
1817 false,
1818 Box::new(self),
1819 Box::new(other),
1820 None,
1821 true,
1822 ))
1823 }
1824
1825 pub fn not_ilike(self, other: Expr) -> Expr {
1827 Expr::Like(Like::new(true, Box::new(self), Box::new(other), None, true))
1828 }
1829
1830 pub fn name_for_alias(&self) -> Result<String> {
1832 Ok(self.schema_name().to_string())
1833 }
1834
1835 pub fn alias_if_changed(self, original_name: String) -> Result<Expr> {
1838 let new_name = self.name_for_alias()?;
1839 if new_name == original_name {
1840 return Ok(self);
1841 }
1842
1843 Ok(self.alias(original_name))
1844 }
1845
1846 pub fn alias(self, name: impl Into<String>) -> Expr {
1848 Expr::Alias(Alias::new(self, None::<&str>, name.into()))
1849 }
1850
1851 pub fn alias_with_metadata(
1866 self,
1867 name: impl Into<String>,
1868 metadata: Option<FieldMetadata>,
1869 ) -> Expr {
1870 Expr::Alias(Alias::new(self, None::<&str>, name.into()).with_metadata(metadata))
1871 }
1872
1873 pub fn alias_qualified(
1875 self,
1876 relation: Option<impl Into<TableReference>>,
1877 name: impl Into<String>,
1878 ) -> Expr {
1879 Expr::Alias(Alias::new(self, relation, name.into()))
1880 }
1881
1882 pub fn alias_qualified_with_metadata(
1898 self,
1899 relation: Option<impl Into<TableReference>>,
1900 name: impl Into<String>,
1901 metadata: Option<FieldMetadata>,
1902 ) -> Expr {
1903 Expr::Alias(Alias::new(self, relation, name.into()).with_metadata(metadata))
1904 }
1905
1906 pub fn unalias(self) -> Expr {
1927 match self {
1928 Expr::Alias(alias) => *alias.expr,
1929 _ => self,
1930 }
1931 }
1932
1933 pub fn unalias_nested(self) -> Transformed<Expr> {
1954 self.transform_down_up(
1955 |expr| {
1956 let recursion = if matches!(
1958 expr,
1959 Expr::Exists { .. } | Expr::ScalarSubquery(_) | Expr::InSubquery(_)
1960 ) {
1961 TreeNodeRecursion::Jump
1963 } else {
1964 TreeNodeRecursion::Continue
1965 };
1966 Ok(Transformed::new(expr, false, recursion))
1967 },
1968 |expr| {
1969 if let Expr::Alias(alias) = expr {
1972 match alias
1973 .metadata
1974 .as_ref()
1975 .map(|h| h.is_empty())
1976 .unwrap_or(true)
1977 {
1978 true => Ok(Transformed::yes(*alias.expr)),
1979 false => Ok(Transformed::no(Expr::Alias(alias))),
1980 }
1981 } else {
1982 Ok(Transformed::no(expr))
1983 }
1984 },
1985 )
1986 .unwrap()
1988 }
1989
1990 pub fn in_list(self, list: Vec<Expr>, negated: bool) -> Expr {
1993 Expr::InList(InList::new(Box::new(self), list, negated))
1994 }
1995
1996 pub fn is_null(self) -> Expr {
1998 Expr::IsNull(Box::new(self))
1999 }
2000
2001 pub fn is_not_null(self) -> Expr {
2003 Expr::IsNotNull(Box::new(self))
2004 }
2005
2006 pub fn sort(self, asc: bool, nulls_first: bool) -> Sort {
2013 Sort::new(self, asc, nulls_first)
2014 }
2015
2016 pub fn is_true(self) -> Expr {
2018 Expr::IsTrue(Box::new(self))
2019 }
2020
2021 pub fn is_not_true(self) -> Expr {
2023 Expr::IsNotTrue(Box::new(self))
2024 }
2025
2026 pub fn is_false(self) -> Expr {
2028 Expr::IsFalse(Box::new(self))
2029 }
2030
2031 pub fn is_not_false(self) -> Expr {
2033 Expr::IsNotFalse(Box::new(self))
2034 }
2035
2036 pub fn is_unknown(self) -> Expr {
2038 Expr::IsUnknown(Box::new(self))
2039 }
2040
2041 pub fn is_not_unknown(self) -> Expr {
2043 Expr::IsNotUnknown(Box::new(self))
2044 }
2045
2046 pub fn between(self, low: Expr, high: Expr) -> Expr {
2048 Expr::Between(Between::new(
2049 Box::new(self),
2050 false,
2051 Box::new(low),
2052 Box::new(high),
2053 ))
2054 }
2055
2056 pub fn not_between(self, low: Expr, high: Expr) -> Expr {
2058 Expr::Between(Between::new(
2059 Box::new(self),
2060 true,
2061 Box::new(low),
2062 Box::new(high),
2063 ))
2064 }
2065 pub fn try_as_col(&self) -> Option<&Column> {
2083 if let Expr::Column(it) = self {
2084 Some(it)
2085 } else {
2086 None
2087 }
2088 }
2089
2090 pub fn get_as_join_column(&self) -> Option<&Column> {
2097 match self {
2098 Expr::Column(c) => Some(c),
2099 Expr::Cast(Cast { expr, .. }) => match &**expr {
2100 Expr::Column(c) => Some(c),
2101 _ => None,
2102 },
2103 _ => None,
2104 }
2105 }
2106
2107 pub fn column_refs(&self) -> HashSet<&Column> {
2123 let mut using_columns = HashSet::new();
2124 self.add_column_refs(&mut using_columns);
2125 using_columns
2126 }
2127
2128 pub fn add_column_refs<'a>(&'a self, set: &mut HashSet<&'a Column>) {
2132 self.apply(|expr| {
2133 if let Expr::Column(col) = expr {
2134 set.insert(col);
2135 }
2136 Ok(TreeNodeRecursion::Continue)
2137 })
2138 .expect("traversal is infallible");
2139 }
2140
2141 pub fn column_refs_counts(&self) -> HashMap<&Column, usize> {
2157 let mut map = HashMap::new();
2158 self.add_column_ref_counts(&mut map);
2159 map
2160 }
2161
2162 pub fn add_column_ref_counts<'a>(&'a self, map: &mut HashMap<&'a Column, usize>) {
2167 self.apply(|expr| {
2168 if let Expr::Column(col) = expr {
2169 *map.entry(col).or_default() += 1;
2170 }
2171 Ok(TreeNodeRecursion::Continue)
2172 })
2173 .expect("traversal is infallible");
2174 }
2175
2176 pub fn any_column_refs(&self) -> bool {
2178 self.exists(|expr| Ok(matches!(expr, Expr::Column(_))))
2179 .expect("exists closure is infallible")
2180 }
2181
2182 pub fn contains_outer(&self) -> bool {
2184 self.exists(|expr| Ok(matches!(expr, Expr::OuterReferenceColumn { .. })))
2185 .expect("exists closure is infallible")
2186 }
2187
2188 pub fn contains_scalar_subquery(&self) -> bool {
2190 self.exists(|expr| Ok(matches!(expr, Expr::ScalarSubquery(_))))
2191 .expect("exists closure is infallible")
2192 }
2193
2194 pub fn is_volatile_node(&self) -> bool {
2200 let volatility = match self {
2201 Expr::ScalarFunction(func) => func.func.signature().volatility,
2202 Expr::AggregateFunction(func) => func.func.signature().volatility,
2203 Expr::WindowFunction(func) => match &func.fun {
2204 WindowFunctionDefinition::AggregateUDF(func) => {
2205 func.signature().volatility
2206 }
2207 WindowFunctionDefinition::WindowUDF(func) => func.signature().volatility,
2208 },
2209 Expr::HigherOrderFunction(func) => func.func.signature().volatility,
2210 _ => return false,
2211 };
2212 volatility == Volatility::Volatile
2213 }
2214
2215 pub fn is_volatile(&self) -> bool {
2223 self.exists(|expr| Ok(expr.is_volatile_node()))
2224 .expect("exists closure is infallible")
2225 }
2226
2227 pub fn infer_placeholder_types(self, schema: &DFSchema) -> Result<(Expr, bool)> {
2236 let mut has_placeholder = false;
2237 self.transform(|mut expr| {
2238 match &mut expr {
2239 Expr::BinaryExpr(BinaryExpr { left, op: _, right }) => {
2241 rewrite_placeholder(left.as_mut(), right.as_ref(), schema)?;
2242 rewrite_placeholder(right.as_mut(), left.as_ref(), schema)?;
2243 }
2244 Expr::Between(Between {
2245 expr,
2246 negated: _,
2247 low,
2248 high,
2249 }) => {
2250 rewrite_placeholder(low.as_mut(), expr.as_ref(), schema)?;
2251 rewrite_placeholder(high.as_mut(), expr.as_ref(), schema)?;
2252 }
2253 Expr::InList(InList {
2254 expr,
2255 list,
2256 negated: _,
2257 }) => {
2258 for item in list.iter_mut() {
2259 rewrite_placeholder(item, expr.as_ref(), schema)?;
2260 }
2261 }
2262 Expr::InSubquery(InSubquery {
2263 expr,
2264 subquery,
2265 negated: _,
2266 }) => {
2267 let subquery_schema = subquery.subquery.schema();
2271 let is_tuple =
2272 in_subquery_tuple_values(expr.as_ref(), &subquery.subquery)?
2273 .is_some();
2274 match expr.as_mut() {
2275 Expr::ScalarFunction(func) if is_tuple => {
2276 for (i, arg) in func.args.iter_mut().enumerate() {
2277 let column = Expr::Column(Column::from(
2280 subquery_schema.qualified_field(i),
2281 ));
2282 rewrite_placeholder(arg, &column, subquery_schema)?;
2283 }
2284 }
2285 _ if is_tuple => {}
2287 expr => rewrite_placeholder_from_subquery(
2288 "InSubquery",
2289 expr,
2290 subquery,
2291 )?,
2292 }
2293 }
2294 Expr::SetComparison(SetComparison {
2295 expr,
2296 subquery,
2297 op: _,
2298 quantifier: _,
2299 }) => {
2300 rewrite_placeholder_from_subquery(
2301 "SetComparison",
2302 expr.as_mut(),
2303 subquery,
2304 )?;
2305 }
2306 Expr::Like(Like { expr, pattern, .. })
2307 | Expr::SimilarTo(Like { expr, pattern, .. }) => {
2308 rewrite_placeholder(pattern.as_mut(), expr.as_ref(), schema)?;
2309 }
2310 Expr::Placeholder(_) => {
2311 has_placeholder = true;
2312 }
2313 _ => {}
2314 }
2315 Ok(Transformed::yes(expr))
2316 })
2317 .data()
2318 .map(|data| (data, has_placeholder))
2319 }
2320
2321 pub fn short_circuits(&self) -> bool {
2324 match self {
2325 Expr::ScalarFunction(ScalarFunction { func, .. }) => func.short_circuits(),
2326 Expr::HigherOrderFunction(HigherOrderFunction { func, .. }) => {
2327 func.short_circuits()
2328 }
2329 Expr::BinaryExpr(BinaryExpr { op, .. }) => {
2330 matches!(op, Operator::And | Operator::Or)
2331 }
2332 Expr::Case { .. } => true,
2333 #[expect(deprecated)]
2338 Expr::AggregateFunction(..)
2339 | Expr::Alias(..)
2340 | Expr::Between(..)
2341 | Expr::Cast(..)
2342 | Expr::Column(..)
2343 | Expr::Exists(..)
2344 | Expr::GroupingSet(..)
2345 | Expr::InList(..)
2346 | Expr::InSubquery(..)
2347 | Expr::SetComparison(..)
2348 | Expr::IsFalse(..)
2349 | Expr::IsNotFalse(..)
2350 | Expr::IsNotNull(..)
2351 | Expr::IsNotTrue(..)
2352 | Expr::IsNotUnknown(..)
2353 | Expr::IsNull(..)
2354 | Expr::IsTrue(..)
2355 | Expr::IsUnknown(..)
2356 | Expr::Like(..)
2357 | Expr::ScalarSubquery(..)
2358 | Expr::ScalarVariable(_, _)
2359 | Expr::SimilarTo(..)
2360 | Expr::Not(..)
2361 | Expr::Negative(..)
2362 | Expr::OuterReferenceColumn(_, _)
2363 | Expr::TryCast(..)
2364 | Expr::Unnest(..)
2365 | Expr::Wildcard { .. }
2366 | Expr::WindowFunction(..)
2367 | Expr::Literal(..)
2368 | Expr::Placeholder(..)
2369 | Expr::Lambda(..)
2370 | Expr::LambdaVariable(..) => false,
2371 }
2372 }
2373
2374 pub fn spans(&self) -> Option<&Spans> {
2378 match self {
2379 Expr::Column(col) => Some(&col.spans),
2380 Expr::Not(inner) | Expr::Negative(inner) => inner.spans(),
2381 _ => None,
2382 }
2383 }
2384
2385 pub fn as_literal(&self) -> Option<&ScalarValue> {
2387 if let Expr::Literal(lit, _) = self {
2388 Some(lit)
2389 } else {
2390 None
2391 }
2392 }
2393
2394 pub fn resolve_lambda_variables(
2398 self,
2399 schema: &DFSchema,
2400 ) -> Result<Transformed<Expr>> {
2401 resolve_lambda_variables(self, schema, &mut HashMap::new())
2402 }
2403}
2404
2405impl Normalizeable for Expr {
2406 fn can_normalize(&self) -> bool {
2407 #[expect(clippy::match_like_matches_macro)]
2408 match self {
2409 Expr::BinaryExpr(BinaryExpr {
2410 op:
2411 _op @ (Operator::Plus
2412 | Operator::Multiply
2413 | Operator::BitwiseAnd
2414 | Operator::BitwiseOr
2415 | Operator::BitwiseXor
2416 | Operator::Eq
2417 | Operator::NotEq),
2418 ..
2419 }) => true,
2420 _ => false,
2421 }
2422 }
2423}
2424
2425impl NormalizeEq for Expr {
2426 fn normalize_eq(&self, other: &Self) -> bool {
2427 match (self, other) {
2428 (
2429 Expr::BinaryExpr(BinaryExpr {
2430 left: self_left,
2431 op: self_op,
2432 right: self_right,
2433 }),
2434 Expr::BinaryExpr(BinaryExpr {
2435 left: other_left,
2436 op: other_op,
2437 right: other_right,
2438 }),
2439 ) => {
2440 if self_op != other_op {
2441 return false;
2442 }
2443
2444 if matches!(
2445 self_op,
2446 Operator::Plus
2447 | Operator::Multiply
2448 | Operator::BitwiseAnd
2449 | Operator::BitwiseOr
2450 | Operator::BitwiseXor
2451 | Operator::Eq
2452 | Operator::NotEq
2453 ) {
2454 (self_left.normalize_eq(other_left)
2455 && self_right.normalize_eq(other_right))
2456 || (self_left.normalize_eq(other_right)
2457 && self_right.normalize_eq(other_left))
2458 } else {
2459 self_left.normalize_eq(other_left)
2460 && self_right.normalize_eq(other_right)
2461 }
2462 }
2463 (
2464 Expr::Alias(Alias {
2465 expr: self_expr,
2466 relation: self_relation,
2467 name: self_name,
2468 ..
2469 }),
2470 Expr::Alias(Alias {
2471 expr: other_expr,
2472 relation: other_relation,
2473 name: other_name,
2474 ..
2475 }),
2476 ) => {
2477 self_name == other_name
2478 && self_relation == other_relation
2479 && self_expr.normalize_eq(other_expr)
2480 }
2481 (
2482 Expr::Like(Like {
2483 negated: self_negated,
2484 expr: self_expr,
2485 pattern: self_pattern,
2486 escape_char: self_escape_char,
2487 case_insensitive: self_case_insensitive,
2488 }),
2489 Expr::Like(Like {
2490 negated: other_negated,
2491 expr: other_expr,
2492 pattern: other_pattern,
2493 escape_char: other_escape_char,
2494 case_insensitive: other_case_insensitive,
2495 }),
2496 )
2497 | (
2498 Expr::SimilarTo(Like {
2499 negated: self_negated,
2500 expr: self_expr,
2501 pattern: self_pattern,
2502 escape_char: self_escape_char,
2503 case_insensitive: self_case_insensitive,
2504 }),
2505 Expr::SimilarTo(Like {
2506 negated: other_negated,
2507 expr: other_expr,
2508 pattern: other_pattern,
2509 escape_char: other_escape_char,
2510 case_insensitive: other_case_insensitive,
2511 }),
2512 ) => {
2513 self_negated == other_negated
2514 && self_escape_char == other_escape_char
2515 && self_case_insensitive == other_case_insensitive
2516 && self_expr.normalize_eq(other_expr)
2517 && self_pattern.normalize_eq(other_pattern)
2518 }
2519 (Expr::Not(self_expr), Expr::Not(other_expr))
2520 | (Expr::IsNull(self_expr), Expr::IsNull(other_expr))
2521 | (Expr::IsTrue(self_expr), Expr::IsTrue(other_expr))
2522 | (Expr::IsFalse(self_expr), Expr::IsFalse(other_expr))
2523 | (Expr::IsUnknown(self_expr), Expr::IsUnknown(other_expr))
2524 | (Expr::IsNotNull(self_expr), Expr::IsNotNull(other_expr))
2525 | (Expr::IsNotTrue(self_expr), Expr::IsNotTrue(other_expr))
2526 | (Expr::IsNotFalse(self_expr), Expr::IsNotFalse(other_expr))
2527 | (Expr::IsNotUnknown(self_expr), Expr::IsNotUnknown(other_expr))
2528 | (Expr::Negative(self_expr), Expr::Negative(other_expr)) => {
2529 self_expr.normalize_eq(other_expr)
2530 }
2531 (
2532 Expr::Unnest(Unnest {
2533 expr: self_expr,
2534 outer: self_outer,
2535 }),
2536 Expr::Unnest(Unnest {
2537 expr: other_expr,
2538 outer: other_outer,
2539 }),
2540 ) => self_outer == other_outer && self_expr.normalize_eq(other_expr),
2541 (
2542 Expr::Between(Between {
2543 expr: self_expr,
2544 negated: self_negated,
2545 low: self_low,
2546 high: self_high,
2547 }),
2548 Expr::Between(Between {
2549 expr: other_expr,
2550 negated: other_negated,
2551 low: other_low,
2552 high: other_high,
2553 }),
2554 ) => {
2555 self_negated == other_negated
2556 && self_expr.normalize_eq(other_expr)
2557 && self_low.normalize_eq(other_low)
2558 && self_high.normalize_eq(other_high)
2559 }
2560 (
2561 Expr::Cast(Cast {
2562 expr: self_expr,
2563 field: self_field,
2564 }),
2565 Expr::Cast(Cast {
2566 expr: other_expr,
2567 field: other_field,
2568 }),
2569 )
2570 | (
2571 Expr::TryCast(TryCast {
2572 expr: self_expr,
2573 field: self_field,
2574 }),
2575 Expr::TryCast(TryCast {
2576 expr: other_expr,
2577 field: other_field,
2578 }),
2579 ) => self_field == other_field && self_expr.normalize_eq(other_expr),
2580 (
2581 Expr::ScalarFunction(ScalarFunction {
2582 func: self_func,
2583 args: self_args,
2584 }),
2585 Expr::ScalarFunction(ScalarFunction {
2586 func: other_func,
2587 args: other_args,
2588 }),
2589 ) => {
2590 self_func == other_func
2591 && self_args.len() == other_args.len()
2592 && self_args
2593 .iter()
2594 .zip(other_args.iter())
2595 .all(|(a, b)| a.normalize_eq(b))
2596 }
2597 (
2598 Expr::AggregateFunction(AggregateFunction {
2599 func: self_func,
2600 params:
2601 AggregateFunctionParams {
2602 args: self_args,
2603 distinct: self_distinct,
2604 filter: self_filter,
2605 order_by: self_order_by,
2606 null_treatment: self_null_treatment,
2607 },
2608 }),
2609 Expr::AggregateFunction(AggregateFunction {
2610 func: other_func,
2611 params:
2612 AggregateFunctionParams {
2613 args: other_args,
2614 distinct: other_distinct,
2615 filter: other_filter,
2616 order_by: other_order_by,
2617 null_treatment: other_null_treatment,
2618 },
2619 }),
2620 ) => {
2621 self_func == other_func
2622 && self_distinct == other_distinct
2623 && self_null_treatment == other_null_treatment
2624 && self_args.len() == other_args.len()
2625 && self_args
2626 .iter()
2627 .zip(other_args.iter())
2628 .all(|(a, b)| a.normalize_eq(b))
2629 && match (self_filter, other_filter) {
2630 (Some(self_filter), Some(other_filter)) => {
2631 self_filter.normalize_eq(other_filter)
2632 }
2633 (None, None) => true,
2634 _ => false,
2635 }
2636 && self_order_by
2637 .iter()
2638 .zip(other_order_by.iter())
2639 .all(|(a, b)| {
2640 a.asc == b.asc
2641 && a.nulls_first == b.nulls_first
2642 && a.expr.normalize_eq(&b.expr)
2643 })
2644 && self_order_by.len() == other_order_by.len()
2645 }
2646 (Expr::WindowFunction(left), Expr::WindowFunction(other)) => {
2647 let WindowFunction {
2648 fun: self_fun,
2649 params:
2650 WindowFunctionParams {
2651 args: self_args,
2652 window_frame: self_window_frame,
2653 partition_by: self_partition_by,
2654 order_by: self_order_by,
2655 filter: self_filter,
2656 null_treatment: self_null_treatment,
2657 distinct: self_distinct,
2658 },
2659 } = left.as_ref();
2660 let WindowFunction {
2661 fun: other_fun,
2662 params:
2663 WindowFunctionParams {
2664 args: other_args,
2665 window_frame: other_window_frame,
2666 partition_by: other_partition_by,
2667 order_by: other_order_by,
2668 filter: other_filter,
2669 null_treatment: other_null_treatment,
2670 distinct: other_distinct,
2671 },
2672 } = other.as_ref();
2673
2674 self_fun == other_fun
2675 && self_window_frame == other_window_frame
2676 && match (self_filter, other_filter) {
2677 (Some(a), Some(b)) => a.normalize_eq(b),
2678 (None, None) => true,
2679 _ => false,
2680 }
2681 && self_null_treatment == other_null_treatment
2682 && self_args.len() == other_args.len()
2683 && self_args
2684 .iter()
2685 .zip(other_args.iter())
2686 .all(|(a, b)| a.normalize_eq(b))
2687 && self_partition_by.len() == other_partition_by.len()
2688 && self_partition_by
2689 .iter()
2690 .zip(other_partition_by.iter())
2691 .all(|(a, b)| a.normalize_eq(b))
2692 && self_order_by.len() == other_order_by.len()
2693 && self_order_by
2694 .iter()
2695 .zip(other_order_by.iter())
2696 .all(|(a, b)| {
2697 a.asc == b.asc
2698 && a.nulls_first == b.nulls_first
2699 && a.expr.normalize_eq(&b.expr)
2700 })
2701 && self_distinct == other_distinct
2702 }
2703 (
2704 Expr::Exists(Exists {
2705 subquery: self_subquery,
2706 negated: self_negated,
2707 }),
2708 Expr::Exists(Exists {
2709 subquery: other_subquery,
2710 negated: other_negated,
2711 }),
2712 ) => {
2713 self_negated == other_negated
2714 && self_subquery.normalize_eq(other_subquery)
2715 }
2716 (
2717 Expr::InSubquery(InSubquery {
2718 expr: self_expr,
2719 subquery: self_subquery,
2720 negated: self_negated,
2721 }),
2722 Expr::InSubquery(InSubquery {
2723 expr: other_expr,
2724 subquery: other_subquery,
2725 negated: other_negated,
2726 }),
2727 ) => {
2728 self_negated == other_negated
2729 && self_expr.normalize_eq(other_expr)
2730 && self_subquery.normalize_eq(other_subquery)
2731 }
2732 (
2733 Expr::ScalarSubquery(self_subquery),
2734 Expr::ScalarSubquery(other_subquery),
2735 ) => self_subquery.normalize_eq(other_subquery),
2736 (
2737 Expr::GroupingSet(GroupingSet::Rollup(self_exprs)),
2738 Expr::GroupingSet(GroupingSet::Rollup(other_exprs)),
2739 )
2740 | (
2741 Expr::GroupingSet(GroupingSet::Cube(self_exprs)),
2742 Expr::GroupingSet(GroupingSet::Cube(other_exprs)),
2743 ) => {
2744 self_exprs.len() == other_exprs.len()
2745 && self_exprs
2746 .iter()
2747 .zip(other_exprs.iter())
2748 .all(|(a, b)| a.normalize_eq(b))
2749 }
2750 (
2751 Expr::GroupingSet(GroupingSet::GroupingSets(self_exprs)),
2752 Expr::GroupingSet(GroupingSet::GroupingSets(other_exprs)),
2753 ) => {
2754 self_exprs.len() == other_exprs.len()
2755 && self_exprs.iter().zip(other_exprs.iter()).all(|(a, b)| {
2756 a.len() == b.len()
2757 && a.iter().zip(b.iter()).all(|(x, y)| x.normalize_eq(y))
2758 })
2759 }
2760 (
2761 Expr::InList(InList {
2762 expr: self_expr,
2763 list: self_list,
2764 negated: self_negated,
2765 }),
2766 Expr::InList(InList {
2767 expr: other_expr,
2768 list: other_list,
2769 negated: other_negated,
2770 }),
2771 ) => {
2772 self_negated == other_negated
2774 && self_expr.normalize_eq(other_expr)
2775 && self_list.len() == other_list.len()
2776 && self_list
2777 .iter()
2778 .zip(other_list.iter())
2779 .all(|(a, b)| a.normalize_eq(b))
2780 }
2781 (
2782 Expr::Case(Case {
2783 expr: self_expr,
2784 when_then_expr: self_when_then_expr,
2785 else_expr: self_else_expr,
2786 }),
2787 Expr::Case(Case {
2788 expr: other_expr,
2789 when_then_expr: other_when_then_expr,
2790 else_expr: other_else_expr,
2791 }),
2792 ) => {
2793 self_when_then_expr.len() == other_when_then_expr.len()
2796 && self_when_then_expr
2797 .iter()
2798 .zip(other_when_then_expr.iter())
2799 .all(|((self_when, self_then), (other_when, other_then))| {
2800 self_when.normalize_eq(other_when)
2801 && self_then.normalize_eq(other_then)
2802 })
2803 && match (self_expr, other_expr) {
2804 (Some(self_expr), Some(other_expr)) => {
2805 self_expr.normalize_eq(other_expr)
2806 }
2807 (None, None) => true,
2808 (_, _) => false,
2809 }
2810 && match (self_else_expr, other_else_expr) {
2811 (Some(self_else_expr), Some(other_else_expr)) => {
2812 self_else_expr.normalize_eq(other_else_expr)
2813 }
2814 (None, None) => true,
2815 (_, _) => false,
2816 }
2817 }
2818 (_, _) => self == other,
2819 }
2820 }
2821}
2822
2823impl HashNode for Expr {
2824 fn hash_node<H: Hasher>(&self, state: &mut H) {
2828 mem::discriminant(self).hash(state);
2829 match self {
2830 Expr::Alias(Alias {
2831 expr: _expr,
2832 relation,
2833 name,
2834 ..
2835 }) => {
2836 relation.hash(state);
2837 name.hash(state);
2838 }
2839 Expr::Column(column) => {
2840 column.hash(state);
2841 }
2842 Expr::ScalarVariable(field, name) => {
2843 field.hash(state);
2844 name.hash(state);
2845 }
2846 Expr::Literal(scalar_value, _) => {
2847 scalar_value.hash(state);
2848 }
2849 Expr::BinaryExpr(BinaryExpr {
2850 left: _left,
2851 op,
2852 right: _right,
2853 }) => {
2854 op.hash(state);
2855 }
2856 Expr::Like(Like {
2857 negated,
2858 expr: _expr,
2859 pattern: _pattern,
2860 escape_char,
2861 case_insensitive,
2862 })
2863 | Expr::SimilarTo(Like {
2864 negated,
2865 expr: _expr,
2866 pattern: _pattern,
2867 escape_char,
2868 case_insensitive,
2869 }) => {
2870 negated.hash(state);
2871 escape_char.hash(state);
2872 case_insensitive.hash(state);
2873 }
2874 Expr::Not(_expr)
2875 | Expr::IsNotNull(_expr)
2876 | Expr::IsNull(_expr)
2877 | Expr::IsTrue(_expr)
2878 | Expr::IsFalse(_expr)
2879 | Expr::IsUnknown(_expr)
2880 | Expr::IsNotTrue(_expr)
2881 | Expr::IsNotFalse(_expr)
2882 | Expr::IsNotUnknown(_expr)
2883 | Expr::Negative(_expr) => {}
2884 Expr::Between(Between {
2885 expr: _expr,
2886 negated,
2887 low: _low,
2888 high: _high,
2889 }) => {
2890 negated.hash(state);
2891 }
2892 Expr::Case(Case {
2893 expr: _expr,
2894 when_then_expr: _when_then_expr,
2895 else_expr: _else_expr,
2896 }) => {}
2897 Expr::Cast(Cast { expr: _expr, field })
2898 | Expr::TryCast(TryCast { expr: _expr, field }) => {
2899 field.hash(state);
2900 }
2901 Expr::ScalarFunction(ScalarFunction { func, args: _args }) => {
2902 func.hash(state);
2903 }
2904 Expr::AggregateFunction(AggregateFunction {
2905 func,
2906 params:
2907 AggregateFunctionParams {
2908 args: _args,
2909 distinct,
2910 filter: _,
2911 order_by: _,
2912 null_treatment,
2913 },
2914 }) => {
2915 func.hash(state);
2916 distinct.hash(state);
2917 null_treatment.hash(state);
2918 }
2919 Expr::WindowFunction(window_fun) => {
2920 let WindowFunction {
2921 fun,
2922 params:
2923 WindowFunctionParams {
2924 args: _args,
2925 partition_by: _,
2926 order_by: _,
2927 window_frame,
2928 filter,
2929 null_treatment,
2930 distinct,
2931 },
2932 } = window_fun.as_ref();
2933 fun.hash(state);
2934 window_frame.hash(state);
2935 filter.hash(state);
2936 null_treatment.hash(state);
2937 distinct.hash(state);
2938 }
2939 Expr::InList(InList {
2940 expr: _expr,
2941 list: _list,
2942 negated,
2943 }) => {
2944 negated.hash(state);
2945 }
2946 Expr::Exists(Exists { subquery, negated }) => {
2947 subquery.hash(state);
2948 negated.hash(state);
2949 }
2950 Expr::InSubquery(InSubquery {
2951 expr: _expr,
2952 subquery,
2953 negated,
2954 }) => {
2955 subquery.hash(state);
2956 negated.hash(state);
2957 }
2958 Expr::SetComparison(SetComparison {
2959 expr: _,
2960 subquery,
2961 op,
2962 quantifier,
2963 }) => {
2964 subquery.hash(state);
2965 op.hash(state);
2966 quantifier.hash(state);
2967 }
2968 Expr::ScalarSubquery(subquery) => {
2969 subquery.hash(state);
2970 }
2971 #[expect(deprecated)]
2972 Expr::Wildcard { qualifier, options } => {
2973 qualifier.hash(state);
2974 options.hash(state);
2975 }
2976 Expr::GroupingSet(grouping_set) => {
2977 mem::discriminant(grouping_set).hash(state);
2978 match grouping_set {
2979 GroupingSet::Rollup(_exprs) | GroupingSet::Cube(_exprs) => {}
2980 GroupingSet::GroupingSets(_exprs) => {}
2981 }
2982 }
2983 Expr::Placeholder(place_holder) => {
2984 place_holder.hash(state);
2985 }
2986 Expr::OuterReferenceColumn(field, column) => {
2987 field.hash(state);
2988 column.hash(state);
2989 }
2990 Expr::Unnest(Unnest { expr: _expr, outer }) => {
2991 outer.hash(state);
2992 }
2993 Expr::HigherOrderFunction(HigherOrderFunction { func, args: _args }) => {
2994 func.hash(state);
2995 }
2996 Expr::Lambda(Lambda { params, body: _ }) => {
2997 params.hash(state);
2998 }
2999 Expr::LambdaVariable(LambdaVariable {
3000 name,
3001 field,
3002 spans: _,
3003 }) => {
3004 name.hash(state);
3005 field.hash(state);
3006 }
3007 }
3008 }
3009}
3010
3011fn rewrite_placeholder(expr: &mut Expr, other: &Expr, schema: &DFSchema) -> Result<()> {
3014 if let Expr::Placeholder(Placeholder { id: _, field }) = expr
3015 && field.is_none()
3016 {
3017 let other_field = other.to_field(schema);
3018 match other_field {
3019 Err(e) => {
3020 Err(e.context(format!(
3021 "Can not find type of {other} needed to infer type of {expr}"
3022 )))?;
3023 }
3024 Ok((_, other_field)) => {
3025 *field = Some(other_field.as_ref().clone().with_nullable(true).into());
3028 }
3029 }
3030 }
3031 Ok(())
3032}
3033
3034#[macro_export]
3035macro_rules! expr_vec_fmt {
3036 ( $ARRAY:expr ) => {{
3037 $ARRAY
3038 .iter()
3039 .map(|e| format!("{e}"))
3040 .collect::<Vec<String>>()
3041 .join(", ")
3042 }};
3043}
3044fn rewrite_placeholder_from_subquery(
3046 kind: &str,
3047 expr: &mut Expr,
3048 subquery: &Subquery,
3049) -> Result<()> {
3050 let subquery_schema = subquery.subquery.schema();
3051 match &subquery_schema.fields()[..] {
3052 [subquery_field] => {
3053 let column =
3054 Expr::Column(Column::new_unqualified(subquery_field.name().clone()));
3055 rewrite_placeholder(expr, &column, subquery_schema)
3056 }
3057 _ => plan_err!(
3058 "{kind} should only return one column, but found {}: {}",
3059 subquery_schema.fields().len(),
3060 subquery_schema.field_names().join(", ")
3061 ),
3062 }
3063}
3064
3065struct SchemaDisplay<'a>(&'a Expr);
3066impl Display for SchemaDisplay<'_> {
3067 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
3068 match self.0 {
3069 #[expect(deprecated)]
3072 Expr::Column(_)
3073 | Expr::Literal(_, _)
3074 | Expr::ScalarVariable(..)
3075 | Expr::OuterReferenceColumn(..)
3076 | Expr::Placeholder(_)
3077 | Expr::Wildcard { .. } => write!(f, "{}", self.0),
3078 Expr::AggregateFunction(AggregateFunction { func, params }) => {
3079 match func.schema_name(params) {
3080 Ok(name) => {
3081 write!(f, "{name}")
3082 }
3083 Err(e) => {
3084 write!(f, "got error from schema_name {e}")
3085 }
3086 }
3087 }
3088 Expr::Alias(Alias {
3090 name,
3091 relation: Some(relation),
3092 ..
3093 }) => write!(f, "{relation}.{name}"),
3094 Expr::Alias(Alias { name, .. }) => write!(f, "{name}"),
3095 Expr::Between(Between {
3096 expr,
3097 negated,
3098 low,
3099 high,
3100 }) => {
3101 let not = if *negated { "NOT " } else { "" };
3102 write!(
3103 f,
3104 "{} {not}BETWEEN {} AND {}",
3105 SchemaDisplay(expr),
3106 SchemaDisplay(low),
3107 SchemaDisplay(high),
3108 )
3109 }
3110 Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
3111 write!(f, "{} {op} {}", SchemaDisplay(left), SchemaDisplay(right))
3112 }
3113 Expr::Case(Case {
3114 expr,
3115 when_then_expr,
3116 else_expr,
3117 }) => {
3118 write!(f, "CASE ")?;
3119
3120 if let Some(e) = expr {
3121 write!(f, "{} ", SchemaDisplay(e))?;
3122 }
3123
3124 for (when, then) in when_then_expr {
3125 write!(
3126 f,
3127 "WHEN {} THEN {} ",
3128 SchemaDisplay(when),
3129 SchemaDisplay(then),
3130 )?;
3131 }
3132
3133 if let Some(e) = else_expr {
3134 write!(f, "ELSE {} ", SchemaDisplay(e))?;
3135 }
3136
3137 write!(f, "END")
3138 }
3139 Expr::Cast(Cast { expr, .. }) | Expr::TryCast(TryCast { expr, .. }) => {
3141 write!(f, "{}", SchemaDisplay(expr))
3142 }
3143 Expr::InList(InList {
3144 expr,
3145 list,
3146 negated,
3147 }) => {
3148 let inlist_name = schema_name_from_exprs(list)?;
3149
3150 if *negated {
3151 write!(f, "{} NOT IN {}", SchemaDisplay(expr), inlist_name)
3152 } else {
3153 write!(f, "{} IN {}", SchemaDisplay(expr), inlist_name)
3154 }
3155 }
3156 Expr::Exists(Exists { negated: true, .. }) => write!(f, "NOT EXISTS"),
3157 Expr::Exists(Exists { negated: false, .. }) => write!(f, "EXISTS"),
3158 Expr::GroupingSet(GroupingSet::Cube(exprs)) => {
3159 write!(f, "ROLLUP ({})", schema_name_from_exprs(exprs)?)
3160 }
3161 Expr::GroupingSet(GroupingSet::GroupingSets(lists_of_exprs)) => {
3162 write!(f, "GROUPING SETS (")?;
3163 for exprs in lists_of_exprs.iter() {
3164 write!(f, "({})", schema_name_from_exprs(exprs)?)?;
3165 }
3166 write!(f, ")")
3167 }
3168 Expr::GroupingSet(GroupingSet::Rollup(exprs)) => {
3169 write!(f, "ROLLUP ({})", schema_name_from_exprs(exprs)?)
3170 }
3171 Expr::IsNull(expr) => write!(f, "{} IS NULL", SchemaDisplay(expr)),
3172 Expr::IsNotNull(expr) => {
3173 write!(f, "{} IS NOT NULL", SchemaDisplay(expr))
3174 }
3175 Expr::IsUnknown(expr) => {
3176 write!(f, "{} IS UNKNOWN", SchemaDisplay(expr))
3177 }
3178 Expr::IsNotUnknown(expr) => {
3179 write!(f, "{} IS NOT UNKNOWN", SchemaDisplay(expr))
3180 }
3181 Expr::InSubquery(InSubquery { negated: true, .. }) => {
3182 write!(f, "NOT IN")
3183 }
3184 Expr::InSubquery(InSubquery { negated: false, .. }) => write!(f, "IN"),
3185 Expr::SetComparison(SetComparison {
3186 expr,
3187 op,
3188 quantifier,
3189 ..
3190 }) => write!(f, "{} {op} {quantifier}", SchemaDisplay(expr.as_ref())),
3191 Expr::IsTrue(expr) => write!(f, "{} IS TRUE", SchemaDisplay(expr)),
3192 Expr::IsFalse(expr) => write!(f, "{} IS FALSE", SchemaDisplay(expr)),
3193 Expr::IsNotTrue(expr) => {
3194 write!(f, "{} IS NOT TRUE", SchemaDisplay(expr))
3195 }
3196 Expr::IsNotFalse(expr) => {
3197 write!(f, "{} IS NOT FALSE", SchemaDisplay(expr))
3198 }
3199 Expr::Like(Like {
3200 negated,
3201 expr,
3202 pattern,
3203 escape_char,
3204 case_insensitive,
3205 }) => {
3206 write!(
3207 f,
3208 "{} {}{} {}",
3209 SchemaDisplay(expr),
3210 if *negated { "NOT " } else { "" },
3211 if *case_insensitive { "ILIKE" } else { "LIKE" },
3212 SchemaDisplay(pattern),
3213 )?;
3214
3215 if let Some(char) = escape_char {
3216 write!(f, " CHAR '{char}'")?;
3217 }
3218
3219 Ok(())
3220 }
3221 Expr::Negative(expr) => write!(f, "(- {})", SchemaDisplay(expr)),
3222 Expr::Not(expr) => write!(f, "NOT {}", SchemaDisplay(expr)),
3223 Expr::Unnest(Unnest { expr, outer }) => {
3224 let name = if *outer { "UNNEST_OUTER" } else { "UNNEST" };
3225 write!(f, "{name}({})", SchemaDisplay(expr))
3226 }
3227 Expr::ScalarFunction(ScalarFunction { func, args }) => {
3228 match func.schema_name(args) {
3229 Ok(name) => {
3230 write!(f, "{name}")
3231 }
3232 Err(e) => {
3233 write!(f, "got error from schema_name {e}")
3234 }
3235 }
3236 }
3237 Expr::ScalarSubquery(Subquery { subquery, .. }) => {
3238 write!(f, "{}", subquery.schema().field(0).name())
3239 }
3240 Expr::SimilarTo(Like {
3241 negated,
3242 expr,
3243 pattern,
3244 escape_char,
3245 ..
3246 }) => {
3247 write!(
3248 f,
3249 "{} {} {}",
3250 SchemaDisplay(expr),
3251 if *negated {
3252 "NOT SIMILAR TO"
3253 } else {
3254 "SIMILAR TO"
3255 },
3256 SchemaDisplay(pattern),
3257 )?;
3258 if let Some(char) = escape_char {
3259 write!(f, " CHAR '{char}'")?;
3260 }
3261
3262 Ok(())
3263 }
3264 Expr::WindowFunction(window_fun) => {
3265 let WindowFunction { fun, params } = window_fun.as_ref();
3266 match fun {
3267 WindowFunctionDefinition::AggregateUDF(fun) => {
3268 match fun.window_function_schema_name(params) {
3269 Ok(name) => {
3270 write!(f, "{name}")
3271 }
3272 Err(e) => {
3273 write!(
3274 f,
3275 "got error from window_function_schema_name {e}"
3276 )
3277 }
3278 }
3279 }
3280 _ => {
3281 let WindowFunctionParams {
3282 args,
3283 partition_by,
3284 order_by,
3285 window_frame,
3286 filter,
3287 null_treatment,
3288 distinct,
3289 } = params;
3290
3291 write!(f, "{fun}(")?;
3293
3294 if *distinct {
3296 write!(f, "DISTINCT ")?;
3297 }
3298
3299 write!(
3301 f,
3302 "{}",
3303 schema_name_from_exprs_comma_separated_without_space(args)?
3304 )?;
3305
3306 write!(f, ")")?;
3308
3309 if let Some(null_treatment) = null_treatment {
3310 write!(f, " {null_treatment}")?;
3311 }
3312
3313 if let Some(filter) = filter {
3314 write!(f, " FILTER (WHERE {filter})")?;
3315 }
3316
3317 if !partition_by.is_empty() {
3318 write!(
3319 f,
3320 " PARTITION BY [{}]",
3321 schema_name_from_exprs(partition_by)?
3322 )?;
3323 }
3324
3325 if !order_by.is_empty() {
3326 write!(
3327 f,
3328 " ORDER BY [{}]",
3329 schema_name_from_sorts(order_by)?
3330 )?;
3331 }
3332
3333 write!(f, " {window_frame}")
3334 }
3335 }
3336 }
3337 Expr::HigherOrderFunction(HigherOrderFunction { func, args }) => {
3338 match func.schema_name(args) {
3339 Ok(name) => {
3340 write!(f, "{name}")
3341 }
3342 Err(e) => {
3343 write!(f, "got error from schema_name {e}")
3344 }
3345 }
3346 }
3347 Expr::Lambda(Lambda { params, body }) => {
3348 write!(
3349 f,
3350 "({}) -> {}",
3351 display_comma_separated(params),
3352 SchemaDisplay(body)
3353 )
3354 }
3355 Expr::LambdaVariable(c) => f.write_str(&c.name),
3356 }
3357 }
3358}
3359
3360struct SqlDisplay<'a>(&'a Expr);
3362
3363impl Display for SqlDisplay<'_> {
3364 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
3365 match self.0 {
3366 Expr::Literal(scalar, _) => scalar.fmt(f),
3367 Expr::Alias(Alias { name, .. }) => write!(f, "{name}"),
3368 Expr::Between(Between {
3369 expr,
3370 negated,
3371 low,
3372 high,
3373 }) => {
3374 let not = if *negated { "NOT " } else { "" };
3375 write!(
3376 f,
3377 "{} {not}BETWEEN {} AND {}",
3378 SqlDisplay(expr),
3379 SqlDisplay(low),
3380 SqlDisplay(high),
3381 )
3382 }
3383 Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
3384 write!(f, "{} {op} {}", SqlDisplay(left), SqlDisplay(right))
3385 }
3386 Expr::Case(Case {
3387 expr,
3388 when_then_expr,
3389 else_expr,
3390 }) => {
3391 write!(f, "CASE ")?;
3392
3393 if let Some(e) = expr {
3394 write!(f, "{} ", SqlDisplay(e))?;
3395 }
3396
3397 for (when, then) in when_then_expr {
3398 write!(f, "WHEN {} THEN {} ", SqlDisplay(when), SqlDisplay(then))?;
3399 }
3400
3401 if let Some(e) = else_expr {
3402 write!(f, "ELSE {} ", SqlDisplay(e))?;
3403 }
3404
3405 write!(f, "END")
3406 }
3407 Expr::Cast(Cast { expr, .. }) | Expr::TryCast(TryCast { expr, .. }) => {
3408 write!(f, "{}", SqlDisplay(expr))
3409 }
3410 Expr::InList(InList {
3411 expr,
3412 list,
3413 negated,
3414 }) => {
3415 write!(
3416 f,
3417 "{}{} IN {}",
3418 SqlDisplay(expr),
3419 if *negated { " NOT" } else { "" },
3420 ExprListDisplay::comma_separated(list.as_slice())
3421 )
3422 }
3423 Expr::GroupingSet(GroupingSet::Cube(exprs)) => {
3424 write!(
3425 f,
3426 "ROLLUP ({})",
3427 ExprListDisplay::comma_separated(exprs.as_slice())
3428 )
3429 }
3430 Expr::GroupingSet(GroupingSet::GroupingSets(lists_of_exprs)) => {
3431 write!(f, "GROUPING SETS (")?;
3432 for exprs in lists_of_exprs.iter() {
3433 write!(
3434 f,
3435 "({})",
3436 ExprListDisplay::comma_separated(exprs.as_slice())
3437 )?;
3438 }
3439 write!(f, ")")
3440 }
3441 Expr::GroupingSet(GroupingSet::Rollup(exprs)) => {
3442 write!(
3443 f,
3444 "ROLLUP ({})",
3445 ExprListDisplay::comma_separated(exprs.as_slice())
3446 )
3447 }
3448 Expr::IsNull(expr) => write!(f, "{} IS NULL", SqlDisplay(expr)),
3449 Expr::IsNotNull(expr) => {
3450 write!(f, "{} IS NOT NULL", SqlDisplay(expr))
3451 }
3452 Expr::IsUnknown(expr) => {
3453 write!(f, "{} IS UNKNOWN", SqlDisplay(expr))
3454 }
3455 Expr::IsNotUnknown(expr) => {
3456 write!(f, "{} IS NOT UNKNOWN", SqlDisplay(expr))
3457 }
3458 Expr::IsTrue(expr) => write!(f, "{} IS TRUE", SqlDisplay(expr)),
3459 Expr::IsFalse(expr) => write!(f, "{} IS FALSE", SqlDisplay(expr)),
3460 Expr::IsNotTrue(expr) => {
3461 write!(f, "{} IS NOT TRUE", SqlDisplay(expr))
3462 }
3463 Expr::IsNotFalse(expr) => {
3464 write!(f, "{} IS NOT FALSE", SqlDisplay(expr))
3465 }
3466 Expr::Like(Like {
3467 negated,
3468 expr,
3469 pattern,
3470 escape_char,
3471 case_insensitive,
3472 }) => {
3473 write!(
3474 f,
3475 "{} {}{} {}",
3476 SqlDisplay(expr),
3477 if *negated { "NOT " } else { "" },
3478 if *case_insensitive { "ILIKE" } else { "LIKE" },
3479 SqlDisplay(pattern),
3480 )?;
3481
3482 if let Some(char) = escape_char {
3483 write!(f, " CHAR '{char}'")?;
3484 }
3485
3486 Ok(())
3487 }
3488 Expr::Negative(expr) => write!(f, "(- {})", SqlDisplay(expr)),
3489 Expr::Not(expr) => write!(f, "NOT {}", SqlDisplay(expr)),
3490 Expr::Unnest(Unnest { expr, outer }) => {
3491 let name = if *outer { "UNNEST_OUTER" } else { "UNNEST" };
3492 write!(f, "{name}({})", SqlDisplay(expr))
3493 }
3494 Expr::SimilarTo(Like {
3495 negated,
3496 expr,
3497 pattern,
3498 escape_char,
3499 ..
3500 }) => {
3501 write!(
3502 f,
3503 "{} {} {}",
3504 SqlDisplay(expr),
3505 if *negated {
3506 "NOT SIMILAR TO"
3507 } else {
3508 "SIMILAR TO"
3509 },
3510 SqlDisplay(pattern),
3511 )?;
3512 if let Some(char) = escape_char {
3513 write!(f, " CHAR '{char}'")?;
3514 }
3515
3516 Ok(())
3517 }
3518 Expr::AggregateFunction(AggregateFunction { func, params }) => {
3519 match func.human_display(params) {
3520 Ok(name) => {
3521 write!(f, "{name}")
3522 }
3523 Err(e) => {
3524 write!(f, "got error from schema_name {e}")
3525 }
3526 }
3527 }
3528 Expr::Lambda(Lambda { params, body }) => {
3529 write!(f, "({}) -> {}", params.join(", "), SchemaDisplay(body))
3530 }
3531 _ => write!(f, "{}", self.0),
3532 }
3533 }
3534}
3535
3536pub(crate) fn schema_name_from_exprs_comma_separated_without_space(
3542 exprs: &[Expr],
3543) -> Result<String, fmt::Error> {
3544 schema_name_from_exprs_inner(exprs, ",")
3545}
3546
3547pub struct ExprListDisplay<'a> {
3549 exprs: &'a [Expr],
3550 sep: &'a str,
3551}
3552
3553impl<'a> ExprListDisplay<'a> {
3554 pub fn new(exprs: &'a [Expr], sep: &'a str) -> Self {
3556 Self { exprs, sep }
3557 }
3558
3559 pub fn comma_separated(exprs: &'a [Expr]) -> Self {
3561 Self::new(exprs, ", ")
3562 }
3563}
3564
3565impl Display for ExprListDisplay<'_> {
3566 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
3567 let mut first = true;
3568 for expr in self.exprs {
3569 if !first {
3570 write!(f, "{}", self.sep)?;
3571 }
3572 write!(f, "{}", SqlDisplay(expr))?;
3573 first = false;
3574 }
3575 Ok(())
3576 }
3577}
3578
3579pub fn schema_name_from_exprs(exprs: &[Expr]) -> Result<String, fmt::Error> {
3581 schema_name_from_exprs_inner(exprs, ", ")
3582}
3583
3584fn schema_name_from_exprs_inner(exprs: &[Expr], sep: &str) -> Result<String, fmt::Error> {
3585 let mut s = String::new();
3586 for (i, e) in exprs.iter().enumerate() {
3587 if i > 0 {
3588 write!(&mut s, "{sep}")?;
3589 }
3590 write!(&mut s, "{}", SchemaDisplay(e))?;
3591 }
3592
3593 Ok(s)
3594}
3595
3596pub fn schema_name_from_sorts(sorts: &[Sort]) -> Result<String, fmt::Error> {
3597 let mut s = String::new();
3598 for (i, e) in sorts.iter().enumerate() {
3599 if i > 0 {
3600 write!(&mut s, ", ")?;
3601 }
3602 let ordering = if e.asc { "ASC" } else { "DESC" };
3603 let nulls_ordering = if e.nulls_first {
3604 "NULLS FIRST"
3605 } else {
3606 "NULLS LAST"
3607 };
3608 write!(&mut s, "{} {} {}", e.expr, ordering, nulls_ordering)?;
3609 }
3610
3611 Ok(s)
3612}
3613
3614pub const OUTER_REFERENCE_COLUMN_PREFIX: &str = "outer_ref";
3615pub const UNNEST_COLUMN_PREFIX: &str = "UNNEST";
3616
3617impl Display for Expr {
3620 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
3621 match self {
3622 Expr::Alias(Alias { expr, name, .. }) => write!(f, "{expr} AS {name}"),
3623 Expr::Column(c) => write!(f, "{c}"),
3624 Expr::OuterReferenceColumn(_, c) => {
3625 write!(f, "{OUTER_REFERENCE_COLUMN_PREFIX}({c})")
3626 }
3627 Expr::ScalarVariable(_, var_names) => write!(f, "{}", var_names.join(".")),
3628 Expr::Literal(v, metadata) => {
3629 match metadata.as_ref().map(|m| m.is_empty()).unwrap_or(true) {
3630 false => write!(f, "{v:?} {:?}", metadata.as_ref().unwrap()),
3631 true => write!(f, "{v:?}"),
3632 }
3633 }
3634 Expr::Case(case) => {
3635 write!(f, "CASE ")?;
3636 if let Some(e) = &case.expr {
3637 write!(f, "{e} ")?;
3638 }
3639 for (w, t) in &case.when_then_expr {
3640 write!(f, "WHEN {w} THEN {t} ")?;
3641 }
3642 if let Some(e) = &case.else_expr {
3643 write!(f, "ELSE {e} ")?;
3644 }
3645 write!(f, "END")
3646 }
3647 Expr::Cast(Cast { expr, field }) => {
3648 let formatted =
3649 format_type_and_metadata(field.data_type(), Some(field.metadata()));
3650 write!(f, "CAST({expr} AS {formatted})")
3651 }
3652 Expr::TryCast(TryCast { expr, field }) => {
3653 let formatted =
3654 format_type_and_metadata(field.data_type(), Some(field.metadata()));
3655 write!(f, "TRY_CAST({expr} AS {formatted})")
3656 }
3657 Expr::Not(expr) => write!(f, "NOT {expr}"),
3658 Expr::Negative(expr) => write!(f, "(- {expr})"),
3659 Expr::IsNull(expr) => write!(f, "{expr} IS NULL"),
3660 Expr::IsNotNull(expr) => write!(f, "{expr} IS NOT NULL"),
3661 Expr::IsTrue(expr) => write!(f, "{expr} IS TRUE"),
3662 Expr::IsFalse(expr) => write!(f, "{expr} IS FALSE"),
3663 Expr::IsUnknown(expr) => write!(f, "{expr} IS UNKNOWN"),
3664 Expr::IsNotTrue(expr) => write!(f, "{expr} IS NOT TRUE"),
3665 Expr::IsNotFalse(expr) => write!(f, "{expr} IS NOT FALSE"),
3666 Expr::IsNotUnknown(expr) => write!(f, "{expr} IS NOT UNKNOWN"),
3667 Expr::Exists(Exists {
3668 subquery,
3669 negated: true,
3670 }) => write!(f, "NOT EXISTS ({subquery:?})"),
3671 Expr::Exists(Exists {
3672 subquery,
3673 negated: false,
3674 }) => write!(f, "EXISTS ({subquery:?})"),
3675 Expr::InSubquery(InSubquery {
3676 expr,
3677 subquery,
3678 negated: true,
3679 }) => write!(f, "{expr} NOT IN ({subquery:?})"),
3680 Expr::InSubquery(InSubquery {
3681 expr,
3682 subquery,
3683 negated: false,
3684 }) => write!(f, "{expr} IN ({subquery:?})"),
3685 Expr::SetComparison(SetComparison {
3686 expr,
3687 subquery,
3688 op,
3689 quantifier,
3690 }) => write!(f, "{expr} {op} {quantifier} ({subquery:?})"),
3691 Expr::ScalarSubquery(subquery) => write!(f, "({subquery:?})"),
3692 Expr::BinaryExpr(expr) => write!(f, "{expr}"),
3693 Expr::ScalarFunction(fun) => {
3694 fmt_function(f, fun.name(), false, &fun.args, true)
3695 }
3696 Expr::WindowFunction(window_fun) => {
3697 let WindowFunction { fun, params } = window_fun.as_ref();
3698 match fun {
3699 WindowFunctionDefinition::AggregateUDF(fun) => {
3700 match fun.window_function_display_name(params) {
3701 Ok(name) => {
3702 write!(f, "{name}")
3703 }
3704 Err(e) => {
3705 write!(
3706 f,
3707 "got error from window_function_display_name {e}"
3708 )
3709 }
3710 }
3711 }
3712 WindowFunctionDefinition::WindowUDF(fun) => {
3713 let WindowFunctionParams {
3714 args,
3715 partition_by,
3716 order_by,
3717 window_frame,
3718 filter,
3719 null_treatment,
3720 distinct,
3721 } = params;
3722
3723 fmt_function(f, &fun.to_string(), *distinct, args, true)?;
3724
3725 if let Some(nt) = null_treatment {
3726 write!(f, "{nt}")?;
3727 }
3728
3729 if let Some(fe) = filter {
3730 write!(f, " FILTER (WHERE {fe})")?;
3731 }
3732
3733 if !partition_by.is_empty() {
3734 write!(f, " PARTITION BY [{}]", expr_vec_fmt!(partition_by))?;
3735 }
3736 if !order_by.is_empty() {
3737 write!(f, " ORDER BY [{}]", expr_vec_fmt!(order_by))?;
3738 }
3739 write!(
3740 f,
3741 " {} BETWEEN {} AND {}",
3742 window_frame.units,
3743 window_frame.start_bound,
3744 window_frame.end_bound
3745 )
3746 }
3747 }
3748 }
3749 Expr::AggregateFunction(AggregateFunction { func, params }) => {
3750 match func.display_name(params) {
3751 Ok(name) => {
3752 write!(f, "{name}")
3753 }
3754 Err(e) => {
3755 write!(f, "got error from display_name {e}")
3756 }
3757 }
3758 }
3759 Expr::Between(Between {
3760 expr,
3761 negated,
3762 low,
3763 high,
3764 }) => {
3765 if *negated {
3766 write!(f, "{expr} NOT BETWEEN {low} AND {high}")
3767 } else {
3768 write!(f, "{expr} BETWEEN {low} AND {high}")
3769 }
3770 }
3771 Expr::Like(Like {
3772 negated,
3773 expr,
3774 pattern,
3775 escape_char,
3776 case_insensitive,
3777 }) => {
3778 write!(f, "{expr}")?;
3779 let op_name = if *case_insensitive { "ILIKE" } else { "LIKE" };
3780 if *negated {
3781 write!(f, " NOT")?;
3782 }
3783 if let Some(char) = escape_char {
3784 write!(f, " {op_name} {pattern} ESCAPE '{char}'")
3785 } else {
3786 write!(f, " {op_name} {pattern}")
3787 }
3788 }
3789 Expr::SimilarTo(Like {
3790 negated,
3791 expr,
3792 pattern,
3793 escape_char,
3794 case_insensitive: _,
3795 }) => {
3796 write!(f, "{expr}")?;
3797 if *negated {
3798 write!(f, " NOT")?;
3799 }
3800 if let Some(char) = escape_char {
3801 write!(f, " SIMILAR TO {pattern} ESCAPE '{char}'")
3802 } else {
3803 write!(f, " SIMILAR TO {pattern}")
3804 }
3805 }
3806 Expr::InList(InList {
3807 expr,
3808 list,
3809 negated,
3810 }) => {
3811 if *negated {
3812 write!(f, "{expr} NOT IN ([{}])", expr_vec_fmt!(list))
3813 } else {
3814 write!(f, "{expr} IN ([{}])", expr_vec_fmt!(list))
3815 }
3816 }
3817 #[expect(deprecated)]
3818 Expr::Wildcard { qualifier, options } => match qualifier {
3819 Some(qualifier) => write!(f, "{qualifier}.*{options}"),
3820 None => write!(f, "*{options}"),
3821 },
3822 Expr::GroupingSet(grouping_sets) => match grouping_sets {
3823 GroupingSet::Rollup(exprs) => {
3824 write!(f, "ROLLUP ({})", expr_vec_fmt!(exprs))
3826 }
3827 GroupingSet::Cube(exprs) => {
3828 write!(f, "CUBE ({})", expr_vec_fmt!(exprs))
3830 }
3831 GroupingSet::GroupingSets(lists_of_exprs) => {
3832 write!(
3834 f,
3835 "GROUPING SETS ({})",
3836 lists_of_exprs
3837 .iter()
3838 .map(|exprs| format!("({})", expr_vec_fmt!(exprs)))
3839 .collect::<Vec<String>>()
3840 .join(", ")
3841 )
3842 }
3843 },
3844 Expr::Placeholder(Placeholder { id, .. }) => write!(f, "{id}"),
3845 Expr::Unnest(Unnest { expr, .. }) => {
3846 write!(f, "{UNNEST_COLUMN_PREFIX}({expr})")
3847 }
3848 Expr::HigherOrderFunction(fun) => {
3849 fmt_function(f, fun.name(), false, &fun.args, true)
3850 }
3851 Expr::Lambda(Lambda { params, body }) => {
3852 write!(f, "({}) -> {body}", params.join(", "))
3853 }
3854 Expr::LambdaVariable(c) => f.write_str(&c.name),
3855 }
3856 }
3857}
3858
3859fn fmt_function(
3860 f: &mut Formatter,
3861 fun: &str,
3862 distinct: bool,
3863 args: &[Expr],
3864 display: bool,
3865) -> fmt::Result {
3866 let args: Vec<String> = match display {
3867 true => args.iter().map(|arg| format!("{arg}")).collect(),
3868 false => args.iter().map(|arg| format!("{arg:?}")).collect(),
3869 };
3870
3871 let distinct_str = match distinct {
3872 true => "DISTINCT ",
3873 false => "",
3874 };
3875 write!(f, "{}({}{})", fun, distinct_str, args.join(", "))
3876}
3877
3878pub fn physical_name(expr: &Expr) -> Result<String> {
3881 match expr {
3882 Expr::Column(col) => Ok(col.name.clone()),
3883 Expr::Alias(alias) => Ok(alias.name.clone()),
3884 _ => Ok(expr.schema_name().to_string()),
3885 }
3886}
3887
3888#[cfg(test)]
3889mod test {
3890 use crate::expr_fn::col;
3891 use crate::test::function_stub::max_udaf;
3892 use crate::{
3893 ColumnarValue, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Volatility, case,
3894 lit, placeholder, qualified_wildcard, wildcard, wildcard_with_options,
3895 };
3896 use arrow::datatypes::{Field, Schema};
3897 use sqlparser::ast;
3898 use sqlparser::ast::{Ident, IdentWithAlias};
3899
3900 #[test]
3901 fn infer_placeholder_in_clause() {
3902 let column = col("department_id");
3904 let param_placeholders = vec![
3905 Expr::Placeholder(Placeholder {
3906 id: "$1".to_string(),
3907 field: None,
3908 }),
3909 Expr::Placeholder(Placeholder {
3910 id: "$2".to_string(),
3911 field: None,
3912 }),
3913 Expr::Placeholder(Placeholder {
3914 id: "$3".to_string(),
3915 field: None,
3916 }),
3917 ];
3918 let in_list = Expr::InList(InList {
3919 expr: Box::new(column),
3920 list: param_placeholders,
3921 negated: false,
3922 });
3923
3924 let schema = Arc::new(Schema::new(vec![
3925 Field::new("name", DataType::Utf8, true),
3926 Field::new("department_id", DataType::Int32, true),
3927 ]));
3928 let df_schema = DFSchema::try_from(schema).unwrap();
3929
3930 let (inferred_expr, contains_placeholder) =
3931 in_list.infer_placeholder_types(&df_schema).unwrap();
3932
3933 assert!(contains_placeholder);
3934
3935 match inferred_expr {
3936 Expr::InList(in_list) => {
3937 for expr in in_list.list {
3938 match expr {
3939 Expr::Placeholder(placeholder) => {
3940 assert_eq!(
3941 placeholder.field.unwrap().data_type(),
3942 &DataType::Int32,
3943 "Placeholder {} should infer Int32",
3944 placeholder.id
3945 );
3946 }
3947 _ => panic!("Expected Placeholder expression"),
3948 }
3949 }
3950 }
3951 _ => panic!("Expected InList expression"),
3952 }
3953 }
3954
3955 #[test]
3956 fn infer_placeholder_in_subquery() {
3957 let subquery_field = Field::new("a", DataType::Int32, false);
3959 let subquery_schema = Arc::new(
3960 DFSchema::from_unqualified_fields(
3961 vec![subquery_field].into(),
3962 Metadata::new(),
3963 )
3964 .unwrap(),
3965 );
3966 let subquery = Subquery {
3967 subquery: Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
3968 produce_one_row: false,
3969 schema: subquery_schema,
3970 })),
3971 outer_ref_columns: vec![],
3972 spans: Spans::new(),
3973 };
3974
3975 let in_subquery = Expr::InSubquery(InSubquery {
3976 expr: Box::new(Expr::Placeholder(Placeholder {
3977 id: "$1".to_string(),
3978 field: None,
3979 })),
3980 subquery,
3981 negated: false,
3982 });
3983
3984 let outer_schema = DFSchema::empty();
3985 let (inferred_expr, contains_placeholder) =
3986 in_subquery.infer_placeholder_types(&outer_schema).unwrap();
3987
3988 assert!(contains_placeholder);
3989
3990 match inferred_expr {
3991 Expr::InSubquery(in_subquery) => match *in_subquery.expr {
3992 Expr::Placeholder(placeholder) => {
3993 let inferred = placeholder.field.expect("placeholder field");
3994 assert_eq!(inferred.data_type(), &DataType::Int32);
3995 assert!(inferred.is_nullable());
3996 }
3997 _ => panic!("Expected Placeholder expression in InSubquery"),
3998 },
3999 _ => panic!("Expected InSubquery expression"),
4000 }
4001 }
4002
4003 #[test]
4004 fn infer_placeholder_not_in_subquery() {
4005 let subquery_field = Field::new("a", DataType::Int32, false);
4007 let subquery_schema = Arc::new(
4008 DFSchema::from_unqualified_fields(
4009 vec![subquery_field].into(),
4010 Metadata::new(),
4011 )
4012 .unwrap(),
4013 );
4014 let subquery = Subquery {
4015 subquery: Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
4016 produce_one_row: false,
4017 schema: subquery_schema,
4018 })),
4019 outer_ref_columns: vec![],
4020 spans: Spans::new(),
4021 };
4022
4023 let not_in_subquery = Expr::InSubquery(InSubquery {
4024 expr: Box::new(Expr::Placeholder(Placeholder {
4025 id: "$1".to_string(),
4026 field: None,
4027 })),
4028 subquery,
4029 negated: true,
4030 });
4031
4032 let outer_schema = DFSchema::empty();
4033 let (inferred_expr, contains_placeholder) = not_in_subquery
4034 .infer_placeholder_types(&outer_schema)
4035 .unwrap();
4036
4037 assert!(contains_placeholder);
4038
4039 match inferred_expr {
4040 Expr::InSubquery(in_subquery) => {
4041 assert!(in_subquery.negated, "negated flag must be preserved");
4042 match *in_subquery.expr {
4043 Expr::Placeholder(placeholder) => {
4044 let inferred = placeholder.field.expect("placeholder field");
4045 assert_eq!(inferred.data_type(), &DataType::Int32);
4046 assert!(inferred.is_nullable());
4047 }
4048 _ => {
4049 panic!("Expected Placeholder expression in InSubquery")
4050 }
4051 }
4052 }
4053 _ => panic!("Expected InSubquery expression"),
4054 }
4055 }
4056
4057 #[test]
4058 fn infer_placeholder_set_comparison_any() {
4059 let subquery_field = Field::new("a", DataType::Int32, false);
4061 let subquery_schema = Arc::new(
4062 DFSchema::from_unqualified_fields(
4063 vec![subquery_field].into(),
4064 Metadata::new(),
4065 )
4066 .unwrap(),
4067 );
4068 let subquery = Subquery {
4069 subquery: Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
4070 produce_one_row: false,
4071 schema: subquery_schema,
4072 })),
4073 outer_ref_columns: vec![],
4074 spans: Spans::new(),
4075 };
4076
4077 let set_cmp = Expr::SetComparison(SetComparison {
4078 expr: Box::new(Expr::Placeholder(Placeholder {
4079 id: "$1".to_string(),
4080 field: None,
4081 })),
4082 subquery,
4083 op: Operator::Eq,
4084 quantifier: SetQuantifier::Any,
4085 });
4086
4087 let outer_schema = DFSchema::empty();
4088 let (inferred_expr, contains_placeholder) =
4089 set_cmp.infer_placeholder_types(&outer_schema).unwrap();
4090
4091 assert!(contains_placeholder);
4092
4093 match inferred_expr {
4094 Expr::SetComparison(sc) => {
4095 assert_eq!(sc.quantifier, SetQuantifier::Any);
4096 match *sc.expr {
4097 Expr::Placeholder(p) => {
4098 let inferred =
4099 p.field.expect("placeholder field should be Int32");
4100 assert_eq!(inferred.data_type(), &DataType::Int32);
4101 assert!(inferred.is_nullable());
4102 }
4103 _ => panic!("Expected Placeholder expression in SetComparison"),
4104 }
4105 }
4106 _ => panic!("Expected SetComparison expression"),
4107 }
4108 }
4109
4110 #[test]
4111 fn infer_placeholder_set_comparison_all() {
4112 let subquery_field = Field::new("a", DataType::Int32, false);
4114 let subquery_schema = Arc::new(
4115 DFSchema::from_unqualified_fields(
4116 vec![subquery_field].into(),
4117 Metadata::new(),
4118 )
4119 .unwrap(),
4120 );
4121 let subquery = Subquery {
4122 subquery: Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
4123 produce_one_row: false,
4124 schema: subquery_schema,
4125 })),
4126 outer_ref_columns: vec![],
4127 spans: Spans::new(),
4128 };
4129
4130 let set_cmp = Expr::SetComparison(SetComparison {
4131 expr: Box::new(Expr::Placeholder(Placeholder {
4132 id: "$1".to_string(),
4133 field: None,
4134 })),
4135 subquery,
4136 op: Operator::NotEq,
4137 quantifier: SetQuantifier::All,
4138 });
4139
4140 let outer_schema = DFSchema::empty();
4141 let (inferred_expr, contains_placeholder) =
4142 set_cmp.infer_placeholder_types(&outer_schema).unwrap();
4143
4144 assert!(contains_placeholder);
4145
4146 match inferred_expr {
4147 Expr::SetComparison(sc) => {
4148 assert_eq!(sc.quantifier, SetQuantifier::All);
4149 match *sc.expr {
4150 Expr::Placeholder(p) => {
4151 let inferred =
4152 p.field.expect("placeholder field should be Int32");
4153 assert_eq!(inferred.data_type(), &DataType::Int32);
4154 assert!(inferred.is_nullable());
4155 }
4156 _ => panic!("Expected Placeholder expression in SetComparison"),
4157 }
4158 }
4159 _ => panic!("Expected SetComparison expression"),
4160 }
4161 }
4162
4163 #[test]
4164 fn infer_placeholder_like_and_similar_to() {
4165 let schema =
4167 Arc::new(Schema::new(vec![Field::new("name", DataType::Utf8, true)]));
4168 let df_schema = DFSchema::try_from(schema).unwrap();
4169
4170 let like = Like {
4171 expr: Box::new(col("name")),
4172 pattern: Box::new(Expr::Placeholder(Placeholder {
4173 id: "$1".to_string(),
4174 field: None,
4175 })),
4176 negated: false,
4177 case_insensitive: false,
4178 escape_char: None,
4179 };
4180
4181 let expr = Expr::Like(like.clone());
4182
4183 let (inferred_expr, _) = expr.infer_placeholder_types(&df_schema).unwrap();
4184 match inferred_expr {
4185 Expr::Like(like) => match *like.pattern {
4186 Expr::Placeholder(placeholder) => {
4187 assert_eq!(placeholder.field.unwrap().data_type(), &DataType::Utf8);
4188 }
4189 _ => panic!("Expected Placeholder"),
4190 },
4191 _ => panic!("Expected Like"),
4192 }
4193
4194 let expr = Expr::SimilarTo(like);
4196
4197 let (inferred_expr, _) = expr.infer_placeholder_types(&df_schema).unwrap();
4198 match inferred_expr {
4199 Expr::SimilarTo(like) => match *like.pattern {
4200 Expr::Placeholder(placeholder) => {
4201 assert_eq!(
4202 placeholder.field.unwrap().data_type(),
4203 &DataType::Utf8,
4204 "Placeholder {} should infer Utf8",
4205 placeholder.id
4206 );
4207 }
4208 _ => panic!("Expected Placeholder expression"),
4209 },
4210 _ => panic!("Expected SimilarTo expression"),
4211 }
4212 }
4213
4214 #[test]
4215 fn infer_placeholder_with_metadata() {
4216 let schema = Arc::new(Schema::new(vec![
4218 Field::new("name", DataType::Utf8, false)
4219 .with_metadata(Metadata::new().with("some_key", "some_value")),
4220 ]));
4221 let df_schema = DFSchema::try_from(schema).unwrap();
4222
4223 let expr = binary_expr(col("name"), Operator::Eq, placeholder("$1"));
4224
4225 let (inferred_expr, _) = expr.infer_placeholder_types(&df_schema).unwrap();
4226 match inferred_expr {
4227 Expr::BinaryExpr(BinaryExpr { right, .. }) => match *right {
4228 Expr::Placeholder(placeholder) => {
4229 assert_eq!(
4230 placeholder.field.as_ref().unwrap().data_type(),
4231 &DataType::Utf8
4232 );
4233 assert_eq!(
4234 placeholder.field.as_ref().unwrap().metadata(),
4235 df_schema.field(0).metadata()
4236 );
4237 assert!(placeholder.field.as_ref().unwrap().is_nullable());
4239 }
4240 _ => panic!("Expected Placeholder"),
4241 },
4242 _ => panic!("Expected BinaryExpr"),
4243 }
4244 }
4245
4246 #[test]
4247 fn format_case_when() -> Result<()> {
4248 let expr = case(col("a"))
4249 .when(lit(1), lit(true))
4250 .when(lit(0), lit(false))
4251 .otherwise(lit(ScalarValue::Null))?;
4252 let expected = "CASE a WHEN Int32(1) THEN Boolean(true) WHEN Int32(0) THEN Boolean(false) ELSE NULL END";
4253 assert_eq!(expected, format!("{expr}"));
4254 Ok(())
4255 }
4256
4257 #[test]
4258 fn format_cast() -> Result<()> {
4259 let expr = Expr::Cast(Cast {
4260 expr: Box::new(Expr::Literal(ScalarValue::Float32(Some(1.23)), None)),
4261 field: DataType::Utf8.into_nullable_field_ref(),
4262 });
4263 let expected_canonical = "CAST(Float32(1.23) AS Utf8)";
4264 assert_eq!(expected_canonical, format!("{expr}"));
4265 assert_eq!("Float32(1.23)", expr.schema_name().to_string());
4268 Ok(())
4269 }
4270
4271 #[test]
4272 fn format_decimal_literal() {
4273 let expr = lit(ScalarValue::Decimal128(Some(1), 1, 1));
4274 assert_eq!("Decimal128(0.1,1,1)", format!("{expr}"));
4275 assert_eq!("Decimal128(0.1,1,1)", expr.schema_name().to_string());
4276 assert_eq!("0.1", expr.human_display().to_string());
4277
4278 let expr = lit(ScalarValue::Decimal128(Some(120), 3, 2));
4279 assert_eq!("Decimal128(1.20,3,2)", format!("{expr}"));
4280 assert_eq!("Decimal128(1.20,3,2)", expr.schema_name().to_string());
4281 assert_eq!("1.20", expr.human_display().to_string());
4282
4283 let null_expr = lit(ScalarValue::Decimal128(None, 10, 2));
4284 assert_eq!("Decimal128(NULL,10,2)", format!("{null_expr}"));
4285 assert_eq!("Decimal128(NULL,10,2)", null_expr.schema_name().to_string());
4286 assert_eq!("NULL", null_expr.human_display().to_string());
4287 }
4288
4289 #[test]
4290 fn test_partial_ord() {
4291 let exp1 = col("a") + lit(1);
4294 let exp2 = col("a") + lit(2);
4295 let exp3 = !(col("a") + lit(2));
4296
4297 assert!(exp1 < exp2);
4298 assert!(exp3 > exp2);
4299 assert!(exp1 < exp3)
4300 }
4301
4302 #[test]
4303 fn test_collect_expr() -> Result<()> {
4304 {
4306 let expr = &Expr::Cast(Cast::new(Box::new(col("a")), DataType::Float64));
4307 let columns = expr.column_refs();
4308 assert_eq!(1, columns.len());
4309 assert!(columns.contains(&Column::from_name("a")));
4310 }
4311
4312 {
4314 let expr = col("a") + col("b") + lit(1);
4315 let columns = expr.column_refs();
4316 assert_eq!(2, columns.len());
4317 assert!(columns.contains(&Column::from_name("a")));
4318 assert!(columns.contains(&Column::from_name("b")));
4319 }
4320
4321 Ok(())
4322 }
4323
4324 #[test]
4325 fn test_logical_ops() {
4326 assert_eq!(
4327 format!("{}", lit(1u32).eq(lit(2u32))),
4328 "UInt32(1) = UInt32(2)"
4329 );
4330 assert_eq!(
4331 format!("{}", lit(1u32).not_eq(lit(2u32))),
4332 "UInt32(1) != UInt32(2)"
4333 );
4334 assert_eq!(
4335 format!("{}", lit(1u32).gt(lit(2u32))),
4336 "UInt32(1) > UInt32(2)"
4337 );
4338 assert_eq!(
4339 format!("{}", lit(1u32).gt_eq(lit(2u32))),
4340 "UInt32(1) >= UInt32(2)"
4341 );
4342 assert_eq!(
4343 format!("{}", lit(1u32).lt(lit(2u32))),
4344 "UInt32(1) < UInt32(2)"
4345 );
4346 assert_eq!(
4347 format!("{}", lit(1u32).lt_eq(lit(2u32))),
4348 "UInt32(1) <= UInt32(2)"
4349 );
4350 assert_eq!(
4351 format!("{}", lit(1u32).and(lit(2u32))),
4352 "UInt32(1) AND UInt32(2)"
4353 );
4354 assert_eq!(
4355 format!("{}", lit(1u32).or(lit(2u32))),
4356 "UInt32(1) OR UInt32(2)"
4357 );
4358 }
4359
4360 #[test]
4361 fn test_is_volatile_scalar_func() {
4362 #[derive(Debug, PartialEq, Eq, Hash)]
4364 struct TestScalarUDF {
4365 signature: Signature,
4366 }
4367 impl ScalarUDFImpl for TestScalarUDF {
4368 fn name(&self) -> &str {
4369 "TestScalarUDF"
4370 }
4371
4372 fn signature(&self) -> &Signature {
4373 &self.signature
4374 }
4375
4376 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
4377 Ok(DataType::Utf8)
4378 }
4379
4380 fn invoke_with_args(
4381 &self,
4382 _args: ScalarFunctionArgs,
4383 ) -> Result<ColumnarValue> {
4384 Ok(ColumnarValue::Scalar(ScalarValue::from("a")))
4385 }
4386 }
4387 let udf = Arc::new(ScalarUDF::from(TestScalarUDF {
4388 signature: Signature::uniform(1, vec![DataType::Float32], Volatility::Stable),
4389 }));
4390 assert_ne!(udf.signature().volatility, Volatility::Volatile);
4391
4392 let udf = Arc::new(ScalarUDF::from(TestScalarUDF {
4393 signature: Signature::uniform(
4394 1,
4395 vec![DataType::Float32],
4396 Volatility::Volatile,
4397 ),
4398 }));
4399 assert_eq!(udf.signature().volatility, Volatility::Volatile);
4400 }
4401
4402 use super::*;
4403 use crate::logical_plan::{EmptyRelation, LogicalPlan};
4404
4405 #[test]
4406 fn normalize_eq_window_function_over_clause_lengths() {
4407 let window = |partition_by: Vec<Expr>, order_by: Vec<Sort>| {
4408 let mut window = WindowFunction::new(max_udaf(), vec![col("value")]);
4409 window.params.partition_by = partition_by;
4410 window.params.order_by = order_by;
4411 Expr::from(window)
4412 };
4413 let base = window(vec![col("a")], vec![Sort::new(col("a"), true, true)]);
4414
4415 let extra_partition = window(
4416 vec![col("a"), col("b")],
4417 vec![Sort::new(col("a"), true, true)],
4418 );
4419 assert!(!base.normalize_eq(&extra_partition));
4420
4421 let extra_order = window(
4422 vec![col("a")],
4423 vec![
4424 Sort::new(col("a"), true, true),
4425 Sort::new(col("b"), true, true),
4426 ],
4427 );
4428 assert!(!base.normalize_eq(&extra_order));
4429 }
4430
4431 #[test]
4432 fn test_display_wildcard() {
4433 assert_eq!(format!("{}", wildcard()), "*");
4434 assert_eq!(format!("{}", qualified_wildcard("t1")), "t1.*");
4435 assert_eq!(
4436 format!(
4437 "{}",
4438 wildcard_with_options(wildcard_options(
4439 Some(IlikeSelectItem {
4440 pattern: "c1".to_string()
4441 }),
4442 None,
4443 None,
4444 None,
4445 None
4446 ))
4447 ),
4448 "* ILIKE 'c1'"
4449 );
4450 assert_eq!(
4451 format!(
4452 "{}",
4453 wildcard_with_options(wildcard_options(
4454 None,
4455 Some(ExcludeSelectItem::Multiple(vec![
4456 Ident::from("c1").into(),
4457 Ident::from("c2").into()
4458 ])),
4459 None,
4460 None,
4461 None
4462 ))
4463 ),
4464 "* EXCLUDE (c1, c2)"
4465 );
4466 assert_eq!(
4467 format!(
4468 "{}",
4469 wildcard_with_options(wildcard_options(
4470 None,
4471 None,
4472 Some(ExceptSelectItem {
4473 first_element: Ident::from("c1"),
4474 additional_elements: vec![Ident::from("c2")]
4475 }),
4476 None,
4477 None
4478 ))
4479 ),
4480 "* EXCEPT (c1, c2)"
4481 );
4482 assert_eq!(
4483 format!(
4484 "{}",
4485 wildcard_with_options(wildcard_options(
4486 None,
4487 None,
4488 None,
4489 Some(PlannedReplaceSelectItem {
4490 items: vec![ReplaceSelectElement {
4491 expr: ast::Expr::Identifier(Ident::from("c1")),
4492 column_name: Ident::from("a1"),
4493 as_keyword: false
4494 }],
4495 planned_expressions: vec![]
4496 }),
4497 None
4498 ))
4499 ),
4500 "* REPLACE (c1 a1)"
4501 );
4502 assert_eq!(
4503 format!(
4504 "{}",
4505 wildcard_with_options(wildcard_options(
4506 None,
4507 None,
4508 None,
4509 None,
4510 Some(RenameSelectItem::Multiple(vec![IdentWithAlias {
4511 ident: Ident::from("c1"),
4512 alias: Ident::from("a1")
4513 }]))
4514 ))
4515 ),
4516 "* RENAME (c1 AS a1)"
4517 )
4518 }
4519
4520 #[test]
4521 fn test_display_set_comparison() {
4522 let subquery = Subquery {
4523 subquery: Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
4524 produce_one_row: false,
4525 schema: Arc::new(DFSchema::empty()),
4526 })),
4527 outer_ref_columns: vec![],
4528 spans: Spans::new(),
4529 };
4530
4531 let expr = Expr::SetComparison(SetComparison::new(
4532 Box::new(Expr::Column(Column::from_name("a"))),
4533 subquery,
4534 Operator::Gt,
4535 SetQuantifier::Any,
4536 ));
4537
4538 assert_eq!(format!("{expr}"), "a > ANY (<subquery>)");
4539 assert_eq!(format!("{}", expr.human_display()), "a > ANY (<subquery>)");
4540 }
4541
4542 #[test]
4543 fn test_schema_display_alias_with_relation() {
4544 assert_eq!(
4545 format!(
4546 "{}",
4547 SchemaDisplay(
4548 &lit(1).alias_qualified("table_name".into(), "column_name")
4549 )
4550 ),
4551 "table_name.column_name"
4552 );
4553 }
4554
4555 #[test]
4556 fn test_schema_display_alias_without_relation() {
4557 assert_eq!(
4558 format!(
4559 "{}",
4560 SchemaDisplay(&lit(1).alias_qualified(None::<&str>, "column_name"))
4561 ),
4562 "column_name"
4563 );
4564 }
4565
4566 #[test]
4567 fn test_unalias_nested_respects_user_metadata() {
4568 use std::collections::HashMap;
4569
4570 let base_expr = col("id");
4571
4572 let no_metadata = base_expr.clone().alias("alias");
4573 assert_eq!(no_metadata.unalias_nested().data, base_expr);
4574
4575 let Expr::Alias(empty_metadata_alias) = base_expr.clone().alias("alias") else {
4576 unreachable!();
4577 };
4578 let empty_metadata_alias = Expr::Alias(
4579 empty_metadata_alias.with_metadata(Some(FieldMetadata::default())),
4580 );
4581 assert_eq!(empty_metadata_alias.unalias_nested().data, base_expr);
4582
4583 let user_metadata = FieldMetadata::from(HashMap::from([(
4584 "some_key".to_string(),
4585 "some_value".to_string(),
4586 )]));
4587
4588 let Expr::Alias(user_alias) = base_expr.clone().alias("alias") else {
4589 unreachable!();
4590 };
4591 let user_alias =
4592 Expr::Alias(user_alias.with_metadata(Some(user_metadata.clone())));
4593 assert_eq!(user_alias.clone().unalias_nested().data, user_alias);
4594 }
4595
4596 fn wildcard_options(
4597 opt_ilike: Option<IlikeSelectItem>,
4598 opt_exclude: Option<ExcludeSelectItem>,
4599 opt_except: Option<ExceptSelectItem>,
4600 opt_replace: Option<PlannedReplaceSelectItem>,
4601 opt_rename: Option<RenameSelectItem>,
4602 ) -> WildcardOptions {
4603 WildcardOptions {
4604 ilike: opt_ilike,
4605 exclude: opt_exclude,
4606 except: opt_except,
4607 replace: opt_replace,
4608 rename: opt_rename,
4609 }
4610 }
4611
4612 #[test]
4613 fn test_size_of_expr() {
4614 assert_eq!(size_of::<Expr>(), 112);
4621 assert_eq!(size_of::<ScalarValue>(), 64);
4622 assert_eq!(size_of::<DataType>(), 24); assert_eq!(size_of::<Vec<Expr>>(), 24);
4624 assert_eq!(size_of::<Arc<Expr>>(), 8);
4625 }
4626
4627 #[test]
4628 fn test_accept_exprs() {
4629 fn accept_exprs<E: AsRef<Expr>>(_: &[E]) {}
4630
4631 let expr = || -> Expr { lit(1) };
4632
4633 let owned_exprs = vec![expr(), expr()];
4635 accept_exprs(&owned_exprs);
4636
4637 let udf = Expr::ScalarFunction(ScalarFunction {
4639 func: Arc::new(ScalarUDF::new_from_impl(TestUDF {})),
4640 args: vec![expr(), expr()],
4641 });
4642 let Expr::ScalarFunction(scalar) = &udf else {
4643 unreachable!()
4644 };
4645 accept_exprs(&scalar.args);
4646
4647 let mut collected_refs: Vec<&Expr> = scalar.args.iter().collect();
4649 collected_refs.extend(&owned_exprs);
4650 accept_exprs(&collected_refs);
4651
4652 #[derive(Debug, PartialEq, Eq, Hash)]
4654 struct TestUDF {}
4655 impl ScalarUDFImpl for TestUDF {
4656 fn name(&self) -> &str {
4657 unimplemented!()
4658 }
4659
4660 fn signature(&self) -> &Signature {
4661 unimplemented!()
4662 }
4663
4664 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
4665 unimplemented!()
4666 }
4667
4668 fn invoke_with_args(
4669 &self,
4670 _args: ScalarFunctionArgs,
4671 ) -> Result<ColumnarValue> {
4672 unimplemented!()
4673 }
4674 }
4675 }
4676
4677 #[expect(deprecated)]
4678 mod intersect_metadata_tests {
4679 use super::super::intersect_metadata_for_union;
4680 use arrow::datatypes::Metadata;
4681
4682 #[test]
4683 fn all_branches_same_metadata() {
4684 let m1 = Metadata::new().with("key", "val");
4685 let m2 = Metadata::new().with("key", "val");
4686 let result = intersect_metadata_for_union([&m1, &m2]);
4687 assert_eq!(result, Metadata::new().with("key", "val"));
4688 }
4689
4690 #[test]
4691 fn conflicting_metadata_dropped() {
4692 let m1 = Metadata::new().with("key", "a");
4693 let m2 = Metadata::new().with("key", "b");
4694 let result = intersect_metadata_for_union([&m1, &m2]);
4695 assert!(result.is_empty());
4696 }
4697
4698 #[test]
4699 fn empty_metadata_branch_skipped() {
4700 let m1 = Metadata::new().with("key", "val");
4701 let m2 = Metadata::new(); let result = intersect_metadata_for_union([&m1, &m2]);
4703 assert_eq!(result, Metadata::new().with("key", "val"));
4704 }
4705
4706 #[test]
4707 fn empty_metadata_first_branch_skipped() {
4708 let m1 = Metadata::new();
4709 let m2 = Metadata::new().with("key", "val");
4710 let result = intersect_metadata_for_union([&m1, &m2]);
4711 assert_eq!(result, Metadata::new().with("key", "val"));
4712 }
4713
4714 #[test]
4715 fn all_branches_empty_metadata() {
4716 let m1 = Metadata::new();
4717 let m2 = Metadata::new();
4718 let result = intersect_metadata_for_union([&m1, &m2]);
4719 assert!(result.is_empty());
4720 }
4721
4722 #[test]
4723 fn mixed_empty_and_conflicting() {
4724 let m1 = Metadata::new().with("key", "a");
4725 let m2 = Metadata::new();
4726 let m3 = Metadata::new().with("key", "b");
4727 let result = intersect_metadata_for_union([&m1, &m2, &m3]);
4728 assert!(result.is_empty());
4730 }
4731
4732 #[test]
4733 fn no_inputs() {
4734 let result = intersect_metadata_for_union(std::iter::empty::<&Metadata>());
4735 assert!(result.is_empty());
4736 }
4737 }
4738}