1use std::collections::{BTreeSet, HashMap, HashSet};
8
9use crate::analyzer::type_coercion::TypeCoercionRewriter;
10use arrow::array::{Array, RecordBatch, new_null_array};
11use arrow::datatypes::{DataType, Field, Schema};
12use datafusion_common::TableReference;
13use datafusion_common::cast::as_boolean_array;
14use datafusion_common::tree_node::{TransformedResult, TreeNode, TreeNodeRecursion};
15use datafusion_common::{Column, DFSchema, Result, ScalarValue};
16use datafusion_expr::execution_props::ExecutionProps;
17use datafusion_expr::expr::{Exists, InSubquery, SetComparison};
18use datafusion_expr::expr_rewriter::replace_col;
19use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
20use datafusion_expr::{
21 ColumnarValue, DistinctHandling, Expr, WriteOp, logical_plan::LogicalPlan,
22};
23use datafusion_physical_expr::create_physical_expr;
24use log::{debug, trace};
25use std::sync::Arc;
26
27pub use datafusion_expr::expr_rewriter::NamePreserver;
30
31pub(crate) fn is_repeatable(expr: &Expr) -> bool {
35 !expr
36 .exists(|expr| {
37 Ok(expr.is_volatile_node()
38 || matches!(
39 expr,
40 Expr::Exists(_)
41 | Expr::InSubquery(_)
42 | Expr::SetComparison(_)
43 | Expr::ScalarSubquery(_)
44 ))
45 })
46 .expect("expression traversal is infallible")
47}
48
49pub(crate) fn is_duplicate_insensitive_aggregate(mut expr: &Expr) -> bool {
55 while let Expr::Alias(alias) = expr {
56 expr = &alias.expr;
57 }
58 let Expr::AggregateFunction(aggregate) = expr else {
59 return false;
60 };
61 let ignores_duplicates = match aggregate.func.distinct_handling() {
62 DistinctHandling::Insensitive => true,
63 DistinctHandling::Sensitive => aggregate.params.distinct,
64 _ => false,
68 };
69 ignores_duplicates && is_repeatable(expr)
70}
71
72pub(crate) fn merge_into_schema(plan: &LogicalPlan) -> Result<Option<DFSchema>> {
74 let LogicalPlan::Dml(dml) = plan else {
75 return Ok(None);
76 };
77 let WriteOp::MergeInto(_) = &dml.op else {
78 return Ok(None);
79 };
80 dml.merge_schema().map(Some)
81}
82
83pub(crate) fn for_each_referenced_index(
99 expr: &Expr,
100 schema: &DFSchema,
101 mut f: impl FnMut(usize),
102) -> Result<()> {
103 visit_referenced_indices(expr, schema, &mut f)
104}
105
106fn visit_referenced_indices(
107 expr: &Expr,
108 schema: &DFSchema,
109 f: &mut dyn FnMut(usize),
110) -> Result<()> {
111 expr.apply(|expr| {
112 match expr {
113 Expr::Column(column) | Expr::OuterReferenceColumn(_, column) => {
114 if let Some(idx) = schema.maybe_index_of_column(column) {
115 f(idx);
116 }
117 }
118 Expr::Exists(Exists { subquery, .. })
119 | Expr::InSubquery(InSubquery { subquery, .. })
120 | Expr::SetComparison(SetComparison { subquery, .. })
121 | Expr::ScalarSubquery(subquery) => {
122 for outer in &subquery.outer_ref_columns {
123 visit_referenced_indices(outer, schema, f)?;
124 }
125 }
126 _ => {}
127 }
128 Ok(TreeNodeRecursion::Continue)
129 })?;
130 Ok(())
131}
132
133pub(crate) fn has_all_column_refs(
135 expr: &Expr,
136 schema_cols: &HashSet<ColumnReference>,
137) -> bool {
138 let column_refs = expr.column_refs();
139 column_refs
141 .iter()
142 .filter(|c| {
143 schema_cols.contains(&ColumnReference::new(c.relation.as_ref(), c.name()))
144 })
145 .count()
146 == column_refs.len()
147}
148
149pub(crate) fn replace_qualified_name(
150 expr: Expr,
151 cols: &BTreeSet<Column>,
152 subquery_alias: &str,
153) -> Result<Expr> {
154 let alias_cols: Vec<Column> = cols
155 .iter()
156 .map(|col| Column::new(Some(subquery_alias), &col.name))
157 .collect();
158 let replace_map: HashMap<&Column, &Column> =
159 cols.iter().zip(alias_cols.iter()).collect();
160
161 replace_col(expr, &replace_map)
162}
163
164#[derive(PartialEq, Eq, Hash, Debug)]
166pub(crate) struct ColumnReference<'a> {
167 pub relation: Option<&'a TableReference>,
168 pub name: &'a str,
169}
170
171impl<'a> ColumnReference<'a> {
172 pub fn new(relation: Option<&'a TableReference>, name: &'a str) -> Self {
173 Self { relation, name }
174 }
175
176 pub fn new_unqualified(name: &'a str) -> Self {
177 Self {
178 relation: None,
179 name,
180 }
181 }
182}
183
184pub(crate) fn schema_columns(schema: &DFSchema) -> HashSet<ColumnReference<'_>> {
186 schema
187 .iter()
188 .flat_map(|(qualifier, field)| {
189 [
190 ColumnReference::new(qualifier, field.name()),
191 ColumnReference::new_unqualified(field.name()),
193 ]
194 })
195 .collect::<HashSet<_>>()
196}
197
198pub fn log_plan(description: &str, plan: &LogicalPlan) {
200 debug!("{description}:\n{}\n", plan.display_indent());
201 trace!("{description}::\n{}\n", plan.display_indent_schema());
202}
203
204pub fn is_restrict_null_predicate<'a>(
208 predicate: Expr,
209 join_cols_of_predicate: impl IntoIterator<Item = &'a Column>,
210) -> Result<bool> {
211 if matches!(predicate, Expr::Column(_)) {
212 return Ok(true);
213 }
214
215 Ok(
218 match evaluate_expr_with_null_column(predicate, join_cols_of_predicate)? {
219 ColumnarValue::Array(array) => {
220 if array.len() == 1 {
221 let boolean_array = as_boolean_array(&array)?;
222 boolean_array.is_null(0) || !boolean_array.value(0)
223 } else {
224 false
225 }
226 }
227 ColumnarValue::Scalar(scalar) => matches!(
228 scalar,
229 ScalarValue::Boolean(None) | ScalarValue::Boolean(Some(false))
230 ),
231 },
232 )
233}
234
235pub fn evaluates_to_null<'a>(
240 predicate: Expr,
241 null_columns: impl IntoIterator<Item = &'a Column>,
242) -> Result<bool> {
243 if matches!(predicate, Expr::Column(_)) {
244 return Ok(true);
245 }
246
247 Ok(
248 match evaluate_expr_with_null_column(predicate, null_columns)? {
249 ColumnarValue::Array(_) => false,
250 ColumnarValue::Scalar(scalar) => scalar.is_null(),
251 },
252 )
253}
254
255fn evaluate_expr_with_null_column<'a>(
256 predicate: Expr,
257 null_columns: impl IntoIterator<Item = &'a Column>,
258) -> Result<ColumnarValue> {
259 static DUMMY_COL_NAME: &str = "?";
260 let schema = Arc::new(Schema::new(vec![Field::new(
261 DUMMY_COL_NAME,
262 DataType::Null,
263 true,
264 )]));
265 let input_schema = DFSchema::try_from(Arc::clone(&schema))?;
266 let column = new_null_array(&DataType::Null, 1);
267 let input_batch = RecordBatch::try_new(schema, vec![column])?;
268 let execution_props = ExecutionProps::default();
269 let null_column = Column::from_name(DUMMY_COL_NAME);
270
271 let join_cols_to_replace = null_columns
272 .into_iter()
273 .map(|column| (column, &null_column))
274 .collect::<HashMap<_, _>>();
275
276 let replaced_predicate = replace_col(predicate, &join_cols_to_replace)?;
277 let coerced_predicate = coerce(replaced_predicate, &input_schema)?;
278 create_physical_expr(
279 &coerced_predicate,
280 &input_schema,
281 &execution_props,
282 &PhysicalPlanningContext::default(),
283 )?
284 .evaluate(&input_batch)
285}
286
287fn coerce(expr: Expr, schema: &DFSchema) -> Result<Expr> {
293 let mut expr_rewrite = TypeCoercionRewriter::new(schema);
294 expr.rewrite(&mut expr_rewrite).data()
295}
296
297#[cfg(test)]
298mod tests {
299 use super::*;
300 use crate::test::test_table_scan_with_name;
301 use datafusion_common::Spans;
302 use datafusion_expr::expr::SetQuantifier;
303 use datafusion_expr::logical_plan::builder::LogicalPlanBuilder;
304 use datafusion_expr::{
305 Operator, Subquery, binary_expr, case, col, in_list, is_null, lit,
306 };
307
308 #[test]
309 fn set_comparison_is_not_repeatable() {
310 let subquery = LogicalPlanBuilder::from(test_table_scan_with_name("t2").unwrap())
311 .project(vec![col("b")])
312 .unwrap()
313 .build()
314 .unwrap();
315 let expr = Expr::SetComparison(SetComparison::new(
316 Box::new(col("a")),
317 Subquery {
318 subquery: Arc::new(subquery),
319 outer_ref_columns: vec![],
320 spans: Spans::new(),
321 },
322 Operator::Gt,
323 SetQuantifier::Any,
324 ));
325
326 assert!(!is_repeatable(&expr));
327 }
328
329 #[test]
330 fn expr_is_restrict_null_predicate() -> Result<()> {
331 let test_cases = vec![
332 (col("a"), true),
334 (is_null(col("a")), false),
336 (Expr::IsNotNull(Box::new(col("a"))), true),
338 (
340 binary_expr(
341 col("a"),
342 Operator::Eq,
343 Expr::Literal(ScalarValue::Null, None),
344 ),
345 true,
346 ),
347 (binary_expr(col("a"), Operator::Gt, lit(8i64)), true),
349 (binary_expr(col("a"), Operator::LtEq, lit(8i32)), true),
351 (
353 case(col("a"))
354 .when(lit(1i64), lit(true))
355 .when(lit(0i64), lit(false))
356 .otherwise(lit(ScalarValue::Null))?,
357 true,
358 ),
359 (
361 case(col("a"))
362 .when(lit(1i64), lit(true))
363 .otherwise(lit(false))?,
364 true,
365 ),
366 (
368 case(col("a"))
369 .when(lit(0i64), lit(false))
370 .otherwise(lit(true))?,
371 false,
372 ),
373 (
375 binary_expr(
376 case(col("a"))
377 .when(lit(0i64), lit(false))
378 .otherwise(lit(true))?,
379 Operator::Or,
380 lit(false),
381 ),
382 false,
383 ),
384 (
386 binary_expr(
387 case(col("a"))
388 .when(lit(0i64), lit(true))
389 .otherwise(lit(false))?,
390 Operator::Or,
391 lit(false),
392 ),
393 true,
394 ),
395 (
397 in_list(col("a"), vec![lit(1i64), lit(2i64), lit(3i64)], false),
398 true,
399 ),
400 (
402 in_list(col("a"), vec![lit(1i64), lit(2i64), lit(3i64)], true),
403 true,
404 ),
405 (
407 in_list(
408 col("a"),
409 vec![Expr::Literal(ScalarValue::Null, None)],
410 false,
411 ),
412 true,
413 ),
414 (
416 in_list(col("a"), vec![Expr::Literal(ScalarValue::Null, None)], true),
417 true,
418 ),
419 ];
420
421 let column_a = Column::from_name("a");
422 for (predicate, expected) in test_cases {
423 let join_cols_of_predicate = std::iter::once(&column_a);
424 let actual =
425 is_restrict_null_predicate(predicate.clone(), join_cols_of_predicate)?;
426 assert_eq!(actual, expected, "{predicate}");
427 }
428
429 Ok(())
430 }
431}