Skip to main content

query/dist_plan/
predicate_extractor.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Predicate extraction for partition pruning.
16//!
17//! [`PredicateExtractor`] extract a list of [`PartitionExpr`] from given [`LogicalPlan`].
18
19use std::collections::HashSet;
20
21use common_telemetry::debug;
22use datafusion_common::Result as DfResult;
23use datafusion_expr::{Expr, LogicalPlan, Operator, utils::split_conjunction};
24use datatypes::value::Value;
25use partition::expr::{Operand, PartitionExpr, RestrictedOp};
26
27/// Extracts a list of [`PartitionExpr`] from given [`LogicalPlan`]
28pub struct PredicateExtractor;
29
30impl PredicateExtractor {
31    /// Extract partition expressions for partition columns from logical plan  
32    /// This method returns PartitionExpr objects suitable for ConstraintPruner
33    pub fn extract_partition_expressions(
34        plan: &LogicalPlan,
35        partition_columns: &[String],
36    ) -> DfResult<Vec<PartitionExpr>> {
37        // Collect all filter expressions from the logical plan
38        let mut filter_exprs = Vec::new();
39        Self::collect_filter_expressions(plan, &mut filter_exprs)?;
40
41        if filter_exprs.is_empty() {
42            return Ok(Vec::new());
43        }
44
45        // Convert each DataFusion filter expression to PartitionExpr
46        let mut partition_exprs = Vec::with_capacity(filter_exprs.len());
47        let partition_set: HashSet<String> = partition_columns.iter().cloned().collect();
48
49        for filter_expr in filter_exprs {
50            let partition_expr = match DataFusionExprConverter::convert(&filter_expr) {
51                Ok(expr) => Some(expr),
52                Err(err) => {
53                    debug!(
54                        "Failed to convert filter expression to PartitionExpr: {}, trying conjuncts",
55                        err
56                    );
57                    split_conjunction(&filter_expr)
58                        .into_iter()
59                        .filter_map(|conjunct| match DataFusionExprConverter::convert(conjunct) {
60                            Ok(expr) => Some(expr),
61                            Err(err) => {
62                                debug!(
63                                    "Failed to convert filter conjunct to PartitionExpr: {}, skipping",
64                                    err
65                                );
66                                None
67                            }
68                        })
69                        // Keep salvaged conjuncts in one AND expression, not as alternatives.
70                        .reduce(PartitionExpr::and)
71                }
72            };
73            let Some(partition_expr) = partition_expr else {
74                continue;
75            };
76
77            // Check expression for safe partition pruning
78            match ExpressionChecker::check_expression_for_pruning(&partition_expr, &partition_set) {
79                ExpressionCheckResult::UseAsIs(expr) => {
80                    partition_exprs.push(expr);
81                }
82                ExpressionCheckResult::UsePartial(exprs) => {
83                    partition_exprs.extend(exprs);
84                }
85                ExpressionCheckResult::Drop => {
86                    debug!(
87                        "Dropping mixed expression for correctness: {}",
88                        partition_expr
89                    );
90                }
91            }
92        }
93
94        debug!(
95            "Extracted {} partition expressions from logical plan for partition columns: {:?}",
96            partition_exprs.len(),
97            partition_columns
98        );
99
100        Ok(partition_exprs)
101    }
102
103    /// Extracts literal equalities that every matching row of a single scan must satisfy.
104    pub(crate) fn extract_scan_equalities(
105        plan: &LogicalPlan,
106        partition_columns: &[String],
107    ) -> Vec<PartitionExpr> {
108        Self::scan_filters(plan)
109            .into_iter()
110            .flat_map(split_conjunction)
111            .filter_map(|predicate| {
112                let Expr::BinaryExpr(binary) = predicate else {
113                    return None;
114                };
115                if binary.op != Operator::Eq {
116                    return None;
117                }
118                let expr = DataFusionExprConverter::convert(predicate).ok()?;
119                let (Operand::Column(column), Operand::Value(_)) = (expr.lhs(), expr.rhs()) else {
120                    return None;
121                };
122                partition_columns.contains(column).then_some(expr)
123            })
124            .collect()
125    }
126
127    /// Unlike [`Self::collect_filter_expressions`], this drops outer filters across projections
128    /// and limits: a projection can redefine a column, and a limit selects rows before the filter.
129    fn scan_filters(mut plan: &LogicalPlan) -> Vec<&Expr> {
130        let mut predicates = Vec::new();
131        loop {
132            match plan {
133                LogicalPlan::TableScan(scan) => {
134                    if scan.fetch.is_some() {
135                        predicates.clear();
136                    }
137                    predicates.extend(&scan.filters);
138                    return predicates;
139                }
140                LogicalPlan::Filter(filter) => {
141                    predicates.push(&filter.predicate);
142                    plan = &filter.input;
143                }
144                _ => {
145                    predicates.clear();
146                    let [input] = plan.inputs()[..] else {
147                        return Vec::new();
148                    };
149                    plan = input;
150                }
151            }
152        }
153    }
154
155    /// Collect all filter expressions from a logical plan.
156    ///
157    /// Besides explicit [`LogicalPlan::Filter`] nodes, this also collects
158    /// [`LogicalPlan::TableScan`] filters: the distributed planner runs
159    /// DataFusion's `PushDownFilter` before `MergeScan` wrapping, so partition
160    /// predicates may only exist there by the time region pruning runs.
161    fn collect_filter_expressions(plan: &LogicalPlan, expressions: &mut Vec<Expr>) -> DfResult<()> {
162        if let LogicalPlan::Filter(filter) = plan {
163            expressions.push(filter.predicate.clone());
164        }
165
166        // `TableScan.filters` is conjunctive, so keep it as one AND expression.
167        if let LogicalPlan::TableScan(table_scan) = plan
168            && let Some(expr) = Self::conjunction(table_scan.filters.iter().cloned())
169        {
170            expressions.push(expr);
171        }
172
173        // Recursively visit children
174        for child in plan.inputs() {
175            Self::collect_filter_expressions(child, expressions)?;
176        }
177
178        // TODO(ruihang): support plans involve multiple relations.
179        if plan.inputs().len() > 1 {
180            expressions.clear();
181        }
182
183        Ok(())
184    }
185
186    fn conjunction(mut expressions: impl Iterator<Item = Expr>) -> Option<Expr> {
187        let first = expressions.next()?;
188        Some(expressions.fold(first, |acc, expr| acc.and(expr)))
189    }
190}
191
192/// Result of analyzing an expression for partition pruning safety
193#[derive(Debug, Clone)]
194enum ExpressionCheckResult {
195    /// Expression is safe to use as-is for pruning (only involves partition columns)
196    UseAsIs(PartitionExpr),
197    /// Extract only these parts for AND expressions (mixed with non-partition columns)
198    UsePartial(Vec<PartitionExpr>),
199    /// Drop the entire expression (unsafe for pruning, e.g., OR with non-partition columns)
200    Drop,
201}
202
203/// Checks expressions to determine safe pruning strategies for mixed partition/non-partition expressions
204struct ExpressionChecker;
205
206impl ExpressionChecker {
207    /// Check a partition expression to determine how it should be handled for safe pruning
208    fn check_expression_for_pruning(
209        expr: &PartitionExpr,
210        partition_columns: &HashSet<String>,
211    ) -> ExpressionCheckResult {
212        match expr.op() {
213            RestrictedOp::And => {
214                // For AND expressions, we can extract only the partition-related parts
215                // because if any part fails, the entire AND fails
216                let mut partition_constraints = Vec::new();
217                Self::extract_and_constraints(expr, partition_columns, &mut partition_constraints);
218
219                if partition_constraints.is_empty() {
220                    ExpressionCheckResult::Drop
221                } else if Self::expr_only_involves_partition_columns(expr, partition_columns) {
222                    // If the entire expression only involves partition columns, use as-is
223                    ExpressionCheckResult::UseAsIs(expr.clone())
224                } else {
225                    // Mixed expression: return only the partition parts
226                    ExpressionCheckResult::UsePartial(partition_constraints)
227                }
228            }
229            RestrictedOp::Or => {
230                // For OR expressions, we can only use them if ALL branches involve only partition columns
231                // because if any branch involves non-partition columns, we cannot safely prune
232                if Self::expr_only_involves_partition_columns(expr, partition_columns) {
233                    ExpressionCheckResult::UseAsIs(expr.clone())
234                } else {
235                    // Mixed OR expression: must drop entirely for safety
236                    ExpressionCheckResult::Drop
237                }
238            }
239            _ => {
240                // For comparison operations (=, <, >, etc.), check if they only involve partition columns
241                if Self::expr_only_involves_partition_columns(expr, partition_columns) {
242                    ExpressionCheckResult::UseAsIs(expr.clone())
243                } else {
244                    ExpressionCheckResult::Drop
245                }
246            }
247        }
248    }
249
250    /// Extract partition-related constraints from AND expressions recursively
251    fn extract_and_constraints(
252        expr: &PartitionExpr,
253        partition_columns: &HashSet<String>,
254        result: &mut Vec<PartitionExpr>,
255    ) {
256        if let RestrictedOp::And = expr.op() {
257            // Recursively process both sides of AND
258            Self::extract_constraints_from_operand(expr.lhs(), partition_columns, result);
259            Self::extract_constraints_from_operand(expr.rhs(), partition_columns, result);
260        } else {
261            // Non-AND expression: check if it involves partition columns
262            if Self::expr_only_involves_partition_columns(expr, partition_columns) {
263                result.push(expr.clone());
264            }
265        }
266    }
267
268    /// Extract constraints from an operand (which might be a column, value, or nested expression)
269    fn extract_constraints_from_operand(
270        operand: &Operand,
271        partition_columns: &HashSet<String>,
272        result: &mut Vec<PartitionExpr>,
273    ) {
274        match operand {
275            Operand::Column(_) | Operand::Value(_) | Operand::IcebergHash(_) => {
276                // This shouldn't happen in well-formed expressions
277            }
278            Operand::Expr(expr) => {
279                Self::extract_and_constraints(expr, partition_columns, result);
280            }
281        }
282    }
283
284    /// Check if an expression involves ONLY partition columns
285    fn expr_only_involves_partition_columns(
286        expr: &PartitionExpr,
287        partition_columns: &HashSet<String>,
288    ) -> bool {
289        Self::operand_only_involves_partition_columns(expr.lhs(), partition_columns)
290            && Self::operand_only_involves_partition_columns(expr.rhs(), partition_columns)
291    }
292
293    /// Check if an operand involves ONLY partition columns or values
294    fn operand_only_involves_partition_columns(
295        operand: &Operand,
296        partition_columns: &HashSet<String>,
297    ) -> bool {
298        match operand {
299            Operand::Column(col) => partition_columns.contains(col),
300            Operand::IcebergHash(hash) => partition_columns.contains(hash.column()),
301            Operand::Value(_) => true, // Values are always safe
302            Operand::Expr(expr) => {
303                Self::expr_only_involves_partition_columns(expr, partition_columns)
304            }
305        }
306    }
307}
308
309/// Converts DataFusion expressions to PartitionExpr
310struct DataFusionExprConverter;
311
312impl DataFusionExprConverter {
313    /// Convert DataFusion Expr to PartitionExpr
314    pub fn convert(expr: &Expr) -> DfResult<PartitionExpr> {
315        match expr {
316            Expr::BinaryExpr(binary_expr) => {
317                let lhs = Self::convert_to_operand(&binary_expr.left)?;
318                let rhs = Self::convert_to_operand(&binary_expr.right)?;
319                let op = Self::convert_operator(&binary_expr.op)?;
320
321                Ok(PartitionExpr::new(lhs, op, rhs))
322            }
323            Expr::InList(inlist_expr) => {
324                // Convert col IN (val1, val2, val3) to col = val1 OR col = val2 OR col = val3
325                // Handle negation: col NOT IN (val1, val2) to col != val1 AND col != val2
326                let column_operand = Self::convert_to_operand(&inlist_expr.expr)?;
327
328                if inlist_expr.list.is_empty() {
329                    return Err(datafusion_common::DataFusionError::Plan(
330                        "InList with empty list is not supported".to_string(),
331                    ));
332                }
333
334                let op = if inlist_expr.negated {
335                    RestrictedOp::NotEq
336                } else {
337                    RestrictedOp::Eq
338                };
339
340                let connector_op = if inlist_expr.negated {
341                    RestrictedOp::And // NOT IN becomes col != val1 AND col != val2
342                } else {
343                    RestrictedOp::Or // IN becomes col = val1 OR col = val2
344                };
345
346                // Convert each value in the list to an equality/inequality expression
347                let mut expressions = Vec::new();
348                for value_expr in &inlist_expr.list {
349                    let value_operand = Self::convert_to_operand(value_expr)?;
350                    expressions.push(PartitionExpr::new(
351                        column_operand.clone(),
352                        op.clone(),
353                        value_operand,
354                    ));
355                }
356
357                // Chain expressions with OR/AND
358                let mut expr_iter = expressions.into_iter();
359                let mut result = expr_iter.next().unwrap();
360                for expr in expr_iter {
361                    result = PartitionExpr::new(
362                        Operand::Expr(result),
363                        connector_op.clone(),
364                        Operand::Expr(expr),
365                    );
366                }
367
368                Ok(result)
369            }
370            Expr::Between(between_expr) => {
371                // Convert col BETWEEN low AND high to col >= low AND col <= high
372                // Handle negation: col NOT BETWEEN low AND high to col < low OR col > high
373                let column_operand = Self::convert_to_operand(&between_expr.expr)?;
374                let low_operand = Self::convert_to_operand(&between_expr.low)?;
375                let high_operand = Self::convert_to_operand(&between_expr.high)?;
376
377                if between_expr.negated {
378                    // NOT BETWEEN: col < low OR col > high
379                    let left_expr =
380                        PartitionExpr::new(column_operand.clone(), RestrictedOp::Lt, low_operand);
381                    let right_expr =
382                        PartitionExpr::new(column_operand, RestrictedOp::Gt, high_operand);
383                    Ok(PartitionExpr::new(
384                        Operand::Expr(left_expr),
385                        RestrictedOp::Or,
386                        Operand::Expr(right_expr),
387                    ))
388                } else {
389                    // BETWEEN: col >= low AND col <= high
390                    let left_expr =
391                        PartitionExpr::new(column_operand.clone(), RestrictedOp::GtEq, low_operand);
392                    let right_expr =
393                        PartitionExpr::new(column_operand, RestrictedOp::LtEq, high_operand);
394                    Ok(PartitionExpr::new(
395                        Operand::Expr(left_expr),
396                        RestrictedOp::And,
397                        Operand::Expr(right_expr),
398                    ))
399                }
400            }
401            Expr::IsNull(expr) => {
402                // Convert col IS NULL to a PartitionExpr
403                let column_operand = Self::convert_to_operand(expr)?;
404                Ok(PartitionExpr::new(
405                    column_operand,
406                    RestrictedOp::Eq,
407                    Operand::Value(Value::Null),
408                ))
409            }
410            Expr::IsNotNull(expr) => {
411                // Convert col IS NOT NULL to a PartitionExpr
412                let column_operand = Self::convert_to_operand(expr)?;
413                Ok(PartitionExpr::new(
414                    column_operand,
415                    RestrictedOp::NotEq,
416                    Operand::Value(Value::Null),
417                ))
418            }
419            Expr::Not(expr) => {
420                // Handle NOT expressions by inverting the inner expression
421                match expr.as_ref() {
422                    Expr::BinaryExpr(binary_expr) => {
423                        let lhs = Self::convert_to_operand(&binary_expr.left)?;
424                        let rhs = Self::convert_to_operand(&binary_expr.right)?;
425                        let inverted_op = Self::invert_operator(&binary_expr.op)?;
426
427                        Ok(PartitionExpr::new(lhs, inverted_op, rhs))
428                    }
429                    Expr::IsNull(inner_expr) => {
430                        // NOT (col IS NULL) becomes col IS NOT NULL
431                        let column_operand = Self::convert_to_operand(inner_expr)?;
432                        Ok(PartitionExpr::new(
433                            column_operand,
434                            RestrictedOp::NotEq,
435                            Operand::Value(Value::Null),
436                        ))
437                    }
438                    Expr::IsNotNull(inner_expr) => {
439                        // NOT (col IS NOT NULL) becomes col IS NULL
440                        let column_operand = Self::convert_to_operand(inner_expr)?;
441                        Ok(PartitionExpr::new(
442                            column_operand,
443                            RestrictedOp::Eq,
444                            Operand::Value(Value::Null),
445                        ))
446                    }
447                    _ => {
448                        debug!(
449                            "Unsupported NOT expression for partition pruning: {:?}",
450                            expr
451                        );
452                        Err(datafusion_common::DataFusionError::Plan(format!(
453                            "NOT expression with inner type {:?} not supported for partition pruning",
454                            expr
455                        )))
456                    }
457                }
458            }
459            _ => Err(datafusion_common::DataFusionError::Plan(format!(
460                "Unsupported expression type for conversion: {:?}",
461                expr
462            ))),
463        }
464    }
465
466    /// Convert DataFusion Expr to Operand
467    fn convert_to_operand(expr: &Expr) -> DfResult<Operand> {
468        match expr {
469            Expr::Column(col) => {
470                // Handle qualified column names (table.column) by extracting just the column name
471                // For partition pruning, we typically only care about the column name itself
472                let column_name = if let Some(relation) = &col.relation {
473                    debug!(
474                        "Using qualified column reference: {}.{}",
475                        relation, col.name
476                    );
477                    col.name.clone()
478                } else {
479                    col.name.clone()
480                };
481                Ok(Operand::Column(column_name))
482            }
483            Expr::Literal(scalar_value, _) => {
484                let value = Value::try_from(scalar_value.clone()).map_err(|err| {
485                    datafusion_common::DataFusionError::Plan(format!(
486                        "Failed to convert literal for partition pruning: {err}"
487                    ))
488                })?;
489                Ok(Operand::Value(value))
490            }
491            Expr::Alias(alias_expr) => {
492                // Unwrap alias to get the actual expression
493                Self::convert_to_operand(&alias_expr.expr)
494            }
495            Expr::Cast(cast_expr) => {
496                // Column casts need input type/value equivalence proof; literals must use the actual cast value.
497                if let Expr::Literal(value, _) = cast_expr.expr.as_ref() {
498                    let value = value.cast_to(cast_expr.field.data_type())?;
499                    let value = Value::try_from(value).map_err(|err| {
500                        datafusion_common::DataFusionError::Plan(format!(
501                            "Failed to convert cast literal for partition pruning: {err}"
502                        ))
503                    })?;
504                    Ok(Operand::Value(value))
505                } else {
506                    debug!("Skipping cast expression for partition pruning: {:?}", expr);
507                    Err(datafusion_common::DataFusionError::Plan(
508                        "Cast expression not supported for partition pruning".to_string(),
509                    ))
510                }
511            }
512            other => {
513                let partition_expr = Self::convert(other)?;
514                Ok(Operand::Expr(partition_expr))
515            }
516        }
517    }
518
519    /// Convert DataFusion Operator to RestrictedOp
520    fn convert_operator(op: &Operator) -> DfResult<RestrictedOp> {
521        match op {
522            Operator::Eq => Ok(RestrictedOp::Eq),
523            Operator::NotEq => Ok(RestrictedOp::NotEq),
524            Operator::Lt => Ok(RestrictedOp::Lt),
525            Operator::LtEq => Ok(RestrictedOp::LtEq),
526            Operator::Gt => Ok(RestrictedOp::Gt),
527            Operator::GtEq => Ok(RestrictedOp::GtEq),
528            Operator::And => Ok(RestrictedOp::And),
529            Operator::Or => Ok(RestrictedOp::Or),
530            _ => Err(datafusion_common::DataFusionError::Plan(format!(
531                "Unsupported operator: {:?}",
532                op
533            ))),
534        }
535    }
536
537    /// Invert a DataFusion Operator for NOT expressions
538    fn invert_operator(op: &Operator) -> DfResult<RestrictedOp> {
539        let Some(negated) = op.negate() else {
540            return Err(datafusion_common::DataFusionError::Plan(format!(
541                "Cannot invert operator: {:?}",
542                op
543            )));
544        };
545        Self::convert_operator(&negated)
546    }
547}
548
549#[cfg(test)]
550mod tests {
551    use std::sync::Arc;
552
553    use datafusion::arrow::datatypes::{DataType, Field, Schema};
554    use datafusion::common::Column;
555    use datafusion::datasource::DefaultTableSource;
556    use datafusion_expr::{LogicalPlanBuilder, col, lit};
557    use datatypes::value::Value;
558    use partition::expr::{Operand, PartitionExpr, RestrictedOp};
559
560    use super::*;
561
562    fn create_test_table_scan() -> LogicalPlan {
563        let schema = Arc::new(Schema::new(vec![
564            Field::new(
565                "timestamp",
566                DataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Millisecond, None),
567                false,
568            ),
569            Field::new("user_id", DataType::Int64, false),
570            Field::new("value", DataType::Int64, false),
571        ]));
572
573        let empty_table = datafusion::datasource::empty::EmptyTable::new(schema);
574        let table_source = Arc::new(DefaultTableSource::new(Arc::new(empty_table)));
575
576        LogicalPlanBuilder::scan("test", table_source, None)
577            .unwrap()
578            .build()
579            .unwrap()
580    }
581
582    struct FilterTestCase {
583        name: &'static str,
584        filter_expr: Expr,
585        expected_partition_exprs: Vec<PartitionExpr>,
586        partition_columns: Vec<&'static str>,
587    }
588
589    impl FilterTestCase {
590        fn new(
591            name: &'static str,
592            filter_expr: Expr,
593            expected_partition_exprs: Vec<PartitionExpr>,
594            partition_columns: Vec<&'static str>,
595        ) -> Self {
596            Self {
597                name,
598                filter_expr,
599                expected_partition_exprs,
600                partition_columns,
601            }
602        }
603    }
604
605    /// Helper to check partition expressions for a set of test cases.
606    fn check_partition_expressions(cases: Vec<FilterTestCase>) {
607        for case in cases {
608            let table_scan = create_test_table_scan();
609            let filter = case.filter_expr.clone();
610
611            let plan = LogicalPlanBuilder::from(table_scan)
612                .filter(filter)
613                .unwrap()
614                .build()
615                .unwrap();
616
617            let partition_columns: Vec<String> = case
618                .partition_columns
619                .iter()
620                .map(|s| s.to_string())
621                .collect();
622            let partition_exprs =
623                PredicateExtractor::extract_partition_expressions(&plan, &partition_columns)
624                    .unwrap();
625            let expected = case.expected_partition_exprs.clone();
626            assert_eq!(
627                partition_exprs, expected,
628                "Test case '{}': expected partition expressions {:?}, got {:?}",
629                case.name, expected, partition_exprs
630            );
631        }
632    }
633
634    #[test]
635    fn test_extracts_table_scan_filters() {
636        let table_scan = create_test_table_scan();
637        let filter = col("user_id").gt_eq(lit(100i64));
638        let LogicalPlan::TableScan(scan) = table_scan else {
639            panic!("expected test table scan");
640        };
641        let plan = LogicalPlan::TableScan(datafusion_expr::logical_plan::TableScan {
642            filters: vec![filter],
643            ..scan
644        });
645
646        let partition_exprs =
647            PredicateExtractor::extract_partition_expressions(&plan, &["user_id".to_string()])
648                .unwrap();
649
650        assert_eq!(
651            partition_exprs,
652            vec![PartitionExpr::new(
653                Operand::Column("user_id".to_string()),
654                RestrictedOp::GtEq,
655                Operand::Value(Value::Int64(100)),
656            )]
657        );
658    }
659
660    #[test]
661    fn test_dictionary_cast_preserves_partition_constraint() {
662        let dictionary_type =
663            DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8));
664        let filter = col("tag").eq(Expr::Cast(datafusion_expr::Cast::new(
665            Box::new(lit("b")),
666            dictionary_type,
667        )));
668
669        let partition_expr = DataFusionExprConverter::convert(&filter).unwrap();
670        assert_eq!(
671            partition_expr,
672            PartitionExpr::new(
673                Operand::Column("tag".to_string()),
674                RestrictedOp::Eq,
675                Operand::Value(Value::String("b".into())),
676            )
677        );
678    }
679
680    #[test]
681    fn test_cast_literals_are_evaluated_and_column_casts_are_skipped() {
682        let casts = [
683            (DataType::Int64, lit(1i64)),
684            (DataType::Float32, lit(1.0f32)),
685            (DataType::Utf8, lit("1")),
686            (DataType::Date32, lit(1i32)),
687            (
688                DataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Nanosecond, None),
689                lit(1i64),
690            ),
691        ];
692        for (data_type, value) in casts {
693            let cast = Expr::Cast(datafusion_expr::Cast::new(
694                Box::new(col("user_id")),
695                data_type,
696            ));
697            assert!(DataFusionExprConverter::convert(&cast.eq(value)).is_err());
698        }
699
700        let chain = Expr::Cast(datafusion_expr::Cast::new(
701            Box::new(Expr::Cast(datafusion_expr::Cast::new(
702                Box::new(col("user_id")),
703                DataType::Float64,
704            ))),
705            DataType::Int64,
706        ));
707        assert!(DataFusionExprConverter::convert(&chain.eq(lit(1i64))).is_err());
708
709        let cast_int = Expr::Cast(datafusion_expr::Cast::new(
710            Box::new(lit(1.5f64)),
711            DataType::Int64,
712        ));
713        assert_eq!(
714            DataFusionExprConverter::convert(&col("user_id").eq(cast_int))
715                .unwrap()
716                .rhs(),
717            &Operand::Value(Value::Int64(1))
718        );
719
720        let cast_string = Expr::Cast(datafusion_expr::Cast::new(
721            Box::new(lit("12")),
722            DataType::Int64,
723        ));
724        assert_eq!(
725            DataFusionExprConverter::convert(&col("user_id").eq(cast_string))
726                .unwrap()
727                .rhs(),
728            &Operand::Value(Value::Int64(12))
729        );
730
731        let unsupported = Expr::Cast(datafusion_expr::Cast::new(
732            Box::new(lit(1i64)),
733            DataType::Decimal256(10, 2),
734        ));
735        assert!(DataFusionExprConverter::convert_to_operand(&unsupported).is_err());
736    }
737
738    #[test]
739    fn test_cast_predicates_are_skipped_in_and_and_or() {
740        let cast = Expr::Cast(datafusion_expr::Cast::new(
741            Box::new(col("user_id")),
742            DataType::Float32,
743        ));
744        let lower = PartitionExpr::new(
745            Operand::Column("user_id".to_string()),
746            RestrictedOp::GtEq,
747            Operand::Value(Value::Int64(1)),
748        );
749        let upper = PartitionExpr::new(
750            Operand::Column("user_id".to_string()),
751            RestrictedOp::Lt,
752            Operand::Value(Value::Int64(10)),
753        );
754        let bounds = PartitionExpr::new(
755            Operand::Expr(lower.clone()),
756            RestrictedOp::And,
757            Operand::Expr(upper.clone()),
758        );
759        check_partition_expressions(vec![
760            FilterTestCase::new(
761                "cast_in_and_preserves_partition_bound",
762                col("user_id")
763                    .eq(lit(1i64))
764                    .and(cast.clone().eq(lit(1.0f32))),
765                vec![PartitionExpr::new(
766                    Operand::Column("user_id".to_string()),
767                    RestrictedOp::Eq,
768                    Operand::Value(Value::Int64(1)),
769                )],
770                vec!["user_id"],
771            ),
772            FilterTestCase::new(
773                "cast_between_two_bounds_preserves_both",
774                col("user_id")
775                    .gt_eq(lit(1i64))
776                    .and(col("user_id").lt(lit(10i64)))
777                    .and(cast.clone().eq(lit(1.0f32))),
778                vec![bounds.clone()],
779                vec!["user_id"],
780            ),
781            FilterTestCase::new(
782                "cast_left_of_bounds_preserves_both",
783                cast.clone()
784                    .eq(lit(1.0f32))
785                    .and(col("user_id").gt_eq(lit(1i64)))
786                    .and(col("user_id").lt(lit(10i64))),
787                vec![bounds.clone()],
788                vec!["user_id"],
789            ),
790            FilterTestCase::new(
791                "cast_between_bounds_preserves_both",
792                col("user_id")
793                    .gt_eq(lit(1i64))
794                    .and(cast.clone().eq(lit(1.0f32)))
795                    .and(col("user_id").lt(lit(10i64))),
796                vec![bounds],
797                vec!["user_id"],
798            ),
799            FilterTestCase::new(
800                "is_not_null_cast_preserves_partition_bound",
801                col("user_id").eq(lit(1i64)).and(
802                    Expr::Cast(datafusion_expr::Cast::new(
803                        Box::new(col("value")),
804                        DataType::Int32,
805                    ))
806                    .is_not_null(),
807                ),
808                vec![PartitionExpr::new(
809                    Operand::Column("user_id".to_string()),
810                    RestrictedOp::Eq,
811                    Operand::Value(Value::Int64(1)),
812                )],
813                vec!["user_id"],
814            ),
815            FilterTestCase::new(
816                "all_unsupported_conjunction_is_dropped",
817                Expr::Cast(datafusion_expr::Cast::new(
818                    Box::new(col("value")),
819                    DataType::Int32,
820                ))
821                .eq(lit(1i32))
822                .and(
823                    Expr::Cast(datafusion_expr::Cast::new(
824                        Box::new(col("timestamp")),
825                        DataType::Float32,
826                    ))
827                    .eq(lit(1.0f32)),
828                ),
829                vec![],
830                vec!["user_id"],
831            ),
832            FilterTestCase::new(
833                "nested_and_with_or_side_preserves_bound",
834                col("user_id").eq(lit(1i64)).and(
835                    col("user_id")
836                        .eq(lit(2i64))
837                        .or(cast.clone().eq(lit(1.0f32))),
838                ),
839                vec![PartitionExpr::new(
840                    Operand::Column("user_id".to_string()),
841                    RestrictedOp::Eq,
842                    Operand::Value(Value::Int64(1)),
843                )],
844                vec!["user_id"],
845            ),
846            FilterTestCase::new(
847                "or_with_nested_and_cast_drops_whole_expression",
848                col("user_id")
849                    .eq(lit(1i64))
850                    .and(cast.clone().eq(lit(1.0f32)))
851                    .or(col("user_id").eq(lit(2i64))),
852                vec![],
853                vec!["user_id"],
854            ),
855            FilterTestCase::new(
856                "cast_in_or_drops_entire_predicate",
857                col("user_id").eq(lit(1i64)).or(cast.eq(lit(1.0f32))),
858                vec![],
859                vec!["user_id"],
860            ),
861        ]);
862    }
863
864    #[test]
865    fn test_combines_table_scan_filters_as_conjunction() {
866        let table_scan = create_test_table_scan();
867        let filter_a = col("user_id").eq(lit(10i64));
868        let filter_b = col("value").eq(lit(20i64));
869        let LogicalPlan::TableScan(scan) = table_scan else {
870            panic!("expected test table scan");
871        };
872        let plan = LogicalPlan::TableScan(datafusion_expr::logical_plan::TableScan {
873            filters: vec![filter_a.clone(), filter_b.clone()],
874            ..scan.clone()
875        });
876        let partition_columns = ["user_id".to_string(), "value".to_string()];
877        let expected = vec![PartitionExpr::new(
878            Operand::Expr(PartitionExpr::new(
879                Operand::Column("user_id".to_string()),
880                RestrictedOp::Eq,
881                Operand::Value(Value::Int64(10)),
882            )),
883            RestrictedOp::And,
884            Operand::Expr(PartitionExpr::new(
885                Operand::Column("value".to_string()),
886                RestrictedOp::Eq,
887                Operand::Value(Value::Int64(20)),
888            )),
889        )];
890
891        let partition_exprs =
892            PredicateExtractor::extract_partition_expressions(&plan, &partition_columns).unwrap();
893        assert_eq!(partition_exprs, expected);
894
895        let unsupported = Expr::Cast(datafusion_expr::Cast::new(
896            Box::new(col("timestamp")),
897            DataType::Float32,
898        ))
899        .eq(lit(1.0f32));
900        let plan = LogicalPlan::TableScan(datafusion_expr::logical_plan::TableScan {
901            filters: vec![filter_a, unsupported, filter_b],
902            ..scan
903        });
904
905        let partition_exprs =
906            PredicateExtractor::extract_partition_expressions(&plan, &partition_columns).unwrap();
907
908        assert_eq!(partition_exprs, expected);
909    }
910
911    #[test]
912    fn test_basic_constraints_extraction() {
913        let cases = vec![
914            FilterTestCase::new(
915                "non_partition_column_ignored",
916                col("value").gt_eq(lit(100i64)),
917                vec![],
918                vec!["user_id"],
919            ),
920            FilterTestCase::new(
921                "simple_constraint",
922                col("user_id").gt_eq(lit(100i64)),
923                vec![PartitionExpr::new(
924                    Operand::Column("user_id".to_string()),
925                    RestrictedOp::GtEq,
926                    Operand::Value(Value::Int64(100)),
927                )],
928                vec!["user_id"],
929            ),
930            FilterTestCase::new(
931                "or_expression",
932                col("user_id")
933                    .eq(lit(100i64))
934                    .or(col("user_id").eq(lit(200i64))),
935                vec![PartitionExpr::new(
936                    Operand::Expr(PartitionExpr::new(
937                        Operand::Column("user_id".to_string()),
938                        RestrictedOp::Eq,
939                        Operand::Value(Value::Int64(100)),
940                    )),
941                    RestrictedOp::Or,
942                    Operand::Expr(PartitionExpr::new(
943                        Operand::Column("user_id".to_string()),
944                        RestrictedOp::Eq,
945                        Operand::Value(Value::Int64(200)),
946                    )),
947                )],
948                vec!["user_id"],
949            ),
950            FilterTestCase::new(
951                "complex_and_or",
952                col("user_id")
953                    .gt_eq(lit(100i64))
954                    .and(col("user_id").lt(lit(200i64)))
955                    .or(col("user_id")
956                        .gt_eq(lit(300i64))
957                        .and(col("user_id").lt(lit(400i64)))),
958                vec![PartitionExpr::new(
959                    Operand::Expr(PartitionExpr::new(
960                        Operand::Expr(PartitionExpr::new(
961                            Operand::Column("user_id".to_string()),
962                            RestrictedOp::GtEq,
963                            Operand::Value(Value::Int64(100)),
964                        )),
965                        RestrictedOp::And,
966                        Operand::Expr(PartitionExpr::new(
967                            Operand::Column("user_id".to_string()),
968                            RestrictedOp::Lt,
969                            Operand::Value(Value::Int64(200)),
970                        )),
971                    )),
972                    RestrictedOp::Or,
973                    Operand::Expr(PartitionExpr::new(
974                        Operand::Expr(PartitionExpr::new(
975                            Operand::Column("user_id".to_string()),
976                            RestrictedOp::GtEq,
977                            Operand::Value(Value::Int64(300)),
978                        )),
979                        RestrictedOp::And,
980                        Operand::Expr(PartitionExpr::new(
981                            Operand::Column("user_id".to_string()),
982                            RestrictedOp::Lt,
983                            Operand::Value(Value::Int64(400)),
984                        )),
985                    )),
986                )],
987                vec!["user_id"],
988            ),
989        ];
990        check_partition_expressions(cases);
991    }
992
993    #[test]
994    fn test_alias_expressions() {
995        let cases = vec![
996            FilterTestCase::new(
997                "simple_alias",
998                col("user_id").alias("uid").eq(lit(100i64)),
999                vec![PartitionExpr::new(
1000                    Operand::Column("user_id".to_string()),
1001                    RestrictedOp::Eq,
1002                    Operand::Value(Value::Int64(100)),
1003                )],
1004                vec!["user_id"],
1005            ),
1006            FilterTestCase::new(
1007                "nested_alias",
1008                col("user_id").alias("uid").alias("u").gt_eq(lit(50i64)),
1009                vec![PartitionExpr::new(
1010                    Operand::Column("user_id".to_string()),
1011                    RestrictedOp::GtEq,
1012                    Operand::Value(Value::Int64(50)),
1013                )],
1014                vec!["user_id"],
1015            ),
1016            FilterTestCase::new(
1017                "complex_alias_with_and_or",
1018                col("user_id")
1019                    .alias("uid")
1020                    .gt_eq(lit(100i64))
1021                    .and(col("user_id").alias("u").lt(lit(200i64)))
1022                    .or(col("user_id").alias("id").eq(lit(300i64))),
1023                vec![PartitionExpr::new(
1024                    Operand::Expr(PartitionExpr::new(
1025                        Operand::Expr(PartitionExpr::new(
1026                            Operand::Column("user_id".to_string()),
1027                            RestrictedOp::GtEq,
1028                            Operand::Value(Value::Int64(100)),
1029                        )),
1030                        RestrictedOp::And,
1031                        Operand::Expr(PartitionExpr::new(
1032                            Operand::Column("user_id".to_string()),
1033                            RestrictedOp::Lt,
1034                            Operand::Value(Value::Int64(200)),
1035                        )),
1036                    )),
1037                    RestrictedOp::Or,
1038                    Operand::Expr(PartitionExpr::new(
1039                        Operand::Column("user_id".to_string()),
1040                        RestrictedOp::Eq,
1041                        Operand::Value(Value::Int64(300)),
1042                    )),
1043                )],
1044                vec!["user_id"],
1045            ),
1046        ];
1047        check_partition_expressions(cases);
1048    }
1049
1050    #[test]
1051    fn test_inlist_expressions() {
1052        let cases = vec![
1053            FilterTestCase::new(
1054                "simple_inlist",
1055                col("user_id").in_list(vec![lit(100i64), lit(200i64), lit(300i64)], false),
1056                vec![PartitionExpr::new(
1057                    Operand::Expr(PartitionExpr::new(
1058                        Operand::Expr(PartitionExpr::new(
1059                            Operand::Column("user_id".to_string()),
1060                            RestrictedOp::Eq,
1061                            Operand::Value(Value::Int64(100)),
1062                        )),
1063                        RestrictedOp::Or,
1064                        Operand::Expr(PartitionExpr::new(
1065                            Operand::Column("user_id".to_string()),
1066                            RestrictedOp::Eq,
1067                            Operand::Value(Value::Int64(200)),
1068                        )),
1069                    )),
1070                    RestrictedOp::Or,
1071                    Operand::Expr(PartitionExpr::new(
1072                        Operand::Column("user_id".to_string()),
1073                        RestrictedOp::Eq,
1074                        Operand::Value(Value::Int64(300)),
1075                    )),
1076                )],
1077                vec!["user_id"],
1078            ),
1079            FilterTestCase::new(
1080                "negated_inlist",
1081                col("user_id").in_list(vec![lit(100i64), lit(200i64)], true),
1082                vec![PartitionExpr::new(
1083                    Operand::Expr(PartitionExpr::new(
1084                        Operand::Column("user_id".to_string()),
1085                        RestrictedOp::NotEq,
1086                        Operand::Value(Value::Int64(100)),
1087                    )),
1088                    RestrictedOp::And,
1089                    Operand::Expr(PartitionExpr::new(
1090                        Operand::Column("user_id".to_string()),
1091                        RestrictedOp::NotEq,
1092                        Operand::Value(Value::Int64(200)),
1093                    )),
1094                )],
1095                vec!["user_id"],
1096            ),
1097            FilterTestCase::new(
1098                "inlist_with_alias",
1099                col("user_id")
1100                    .alias("uid")
1101                    .in_list(vec![lit(100i64), lit(200i64)], false),
1102                vec![PartitionExpr::new(
1103                    Operand::Expr(PartitionExpr::new(
1104                        Operand::Column("user_id".to_string()),
1105                        RestrictedOp::Eq,
1106                        Operand::Value(Value::Int64(100)),
1107                    )),
1108                    RestrictedOp::Or,
1109                    Operand::Expr(PartitionExpr::new(
1110                        Operand::Column("user_id".to_string()),
1111                        RestrictedOp::Eq,
1112                        Operand::Value(Value::Int64(200)),
1113                    )),
1114                )],
1115                vec!["user_id"],
1116            ),
1117        ];
1118        check_partition_expressions(cases);
1119    }
1120
1121    #[test]
1122    fn test_between_expressions() {
1123        let cases = vec![
1124            FilterTestCase::new(
1125                "simple_between",
1126                col("user_id").between(lit(100i64), lit(200i64)),
1127                vec![PartitionExpr::new(
1128                    Operand::Expr(PartitionExpr::new(
1129                        Operand::Column("user_id".to_string()),
1130                        RestrictedOp::GtEq,
1131                        Operand::Value(Value::Int64(100)),
1132                    )),
1133                    RestrictedOp::And,
1134                    Operand::Expr(PartitionExpr::new(
1135                        Operand::Column("user_id".to_string()),
1136                        RestrictedOp::LtEq,
1137                        Operand::Value(Value::Int64(200)),
1138                    )),
1139                )],
1140                vec!["user_id"],
1141            ),
1142            FilterTestCase::new(
1143                "negated_between",
1144                Expr::Between(datafusion_expr::Between {
1145                    expr: Box::new(col("user_id")),
1146                    negated: true,
1147                    low: Box::new(lit(100i64)),
1148                    high: Box::new(lit(200i64)),
1149                }),
1150                vec![PartitionExpr::new(
1151                    Operand::Expr(PartitionExpr::new(
1152                        Operand::Column("user_id".to_string()),
1153                        RestrictedOp::Lt,
1154                        Operand::Value(Value::Int64(100)),
1155                    )),
1156                    RestrictedOp::Or,
1157                    Operand::Expr(PartitionExpr::new(
1158                        Operand::Column("user_id".to_string()),
1159                        RestrictedOp::Gt,
1160                        Operand::Value(Value::Int64(200)),
1161                    )),
1162                )],
1163                vec!["user_id"],
1164            ),
1165            FilterTestCase::new(
1166                "between_with_alias",
1167                col("user_id")
1168                    .alias("uid")
1169                    .between(lit(100i64), lit(200i64)),
1170                vec![PartitionExpr::new(
1171                    Operand::Expr(PartitionExpr::new(
1172                        Operand::Column("user_id".to_string()),
1173                        RestrictedOp::GtEq,
1174                        Operand::Value(Value::Int64(100)),
1175                    )),
1176                    RestrictedOp::And,
1177                    Operand::Expr(PartitionExpr::new(
1178                        Operand::Column("user_id".to_string()),
1179                        RestrictedOp::LtEq,
1180                        Operand::Value(Value::Int64(200)),
1181                    )),
1182                )],
1183                vec!["user_id"],
1184            ),
1185        ];
1186        check_partition_expressions(cases);
1187    }
1188
1189    #[test]
1190    fn test_null_expressions() {
1191        let cases = vec![
1192            FilterTestCase::new(
1193                "is_null",
1194                col("user_id").is_null(),
1195                vec![PartitionExpr::new(
1196                    Operand::Column("user_id".to_string()),
1197                    RestrictedOp::Eq,
1198                    Operand::Value(Value::Null),
1199                )],
1200                vec!["user_id"],
1201            ),
1202            FilterTestCase::new(
1203                "is_not_null",
1204                col("user_id").is_not_null(),
1205                vec![PartitionExpr::new(
1206                    Operand::Column("user_id".to_string()),
1207                    RestrictedOp::NotEq,
1208                    Operand::Value(Value::Null),
1209                )],
1210                vec!["user_id"],
1211            ),
1212            FilterTestCase::new(
1213                "null_with_alias",
1214                col("user_id").alias("uid").is_null(),
1215                vec![PartitionExpr::new(
1216                    Operand::Column("user_id".to_string()),
1217                    RestrictedOp::Eq,
1218                    Operand::Value(Value::Null),
1219                )],
1220                vec!["user_id"],
1221            ),
1222        ];
1223        check_partition_expressions(cases);
1224    }
1225
1226    #[test]
1227    fn test_cast_expressions() {
1228        let cases = vec![
1229            FilterTestCase::new(
1230                "column_cast_requires_type_proof",
1231                Expr::Cast(datafusion_expr::Cast::new(
1232                    Box::new(col("user_id")),
1233                    DataType::Int64,
1234                ))
1235                .eq(lit(100i64)),
1236                vec![],
1237                vec!["user_id"],
1238            ),
1239            FilterTestCase::new(
1240                "cast_with_alias_requires_type_proof",
1241                Expr::Cast(datafusion_expr::Cast::new(
1242                    Box::new(col("user_id").alias("uid")),
1243                    DataType::Int64,
1244                ))
1245                .eq(lit(100i64)),
1246                vec![],
1247                vec!["user_id"],
1248            ),
1249            FilterTestCase::new(
1250                "unsafe_cast",
1251                Expr::Cast(datafusion_expr::Cast::new(
1252                    Box::new(col("user_id")),
1253                    DataType::List(std::sync::Arc::new(
1254                        datafusion::arrow::datatypes::Field::new("item", DataType::Int32, true),
1255                    )),
1256                ))
1257                .eq(lit(100i64)),
1258                vec![],
1259                vec!["user_id"],
1260            ),
1261        ];
1262        check_partition_expressions(cases);
1263    }
1264
1265    #[test]
1266    fn test_not_expressions() {
1267        let cases = vec![
1268            FilterTestCase::new(
1269                "not_equality",
1270                Expr::Not(Box::new(col("user_id").eq(lit(100i64)))),
1271                vec![PartitionExpr::new(
1272                    Operand::Column("user_id".to_string()),
1273                    RestrictedOp::NotEq,
1274                    Operand::Value(Value::Int64(100)),
1275                )],
1276                vec!["user_id"],
1277            ),
1278            FilterTestCase::new(
1279                "not_comparison",
1280                Expr::Not(Box::new(col("user_id").lt(lit(100i64)))),
1281                vec![PartitionExpr::new(
1282                    Operand::Column("user_id".to_string()),
1283                    RestrictedOp::GtEq,
1284                    Operand::Value(Value::Int64(100)),
1285                )],
1286                vec!["user_id"],
1287            ),
1288            FilterTestCase::new(
1289                "not_is_null",
1290                Expr::Not(Box::new(col("user_id").is_null())),
1291                vec![PartitionExpr::new(
1292                    Operand::Column("user_id".to_string()),
1293                    RestrictedOp::NotEq,
1294                    Operand::Value(Value::Null),
1295                )],
1296                vec!["user_id"],
1297            ),
1298            FilterTestCase::new(
1299                "not_with_alias",
1300                Expr::Not(Box::new(col("user_id").alias("uid").eq(lit(100i64)))),
1301                vec![PartitionExpr::new(
1302                    Operand::Column("user_id".to_string()),
1303                    RestrictedOp::NotEq,
1304                    Operand::Value(Value::Int64(100)),
1305                )],
1306                vec!["user_id"],
1307            ),
1308        ];
1309        check_partition_expressions(cases);
1310    }
1311
1312    #[test]
1313    fn test_edge_cases() {
1314        let cases = vec![
1315            FilterTestCase::new(
1316                "qualified_column_name",
1317                {
1318                    let qualified_col = Expr::Column(Column::new(Some("test"), "user_id"));
1319                    qualified_col.eq(lit(100i64))
1320                },
1321                vec![PartitionExpr::new(
1322                    Operand::Column("user_id".to_string()),
1323                    RestrictedOp::Eq,
1324                    Operand::Value(Value::Int64(100)),
1325                )],
1326                vec!["user_id"],
1327            ),
1328            FilterTestCase::new(
1329                "comprehensive_combinations",
1330                {
1331                    let in_expr = col("user_id")
1332                        .alias("uid")
1333                        .in_list(vec![lit(100i64), lit(200i64)], false);
1334                    let between_expr = col("user_id").between(lit(300i64), lit(400i64));
1335                    in_expr.or(between_expr)
1336                },
1337                vec![PartitionExpr::new(
1338                    Operand::Expr(PartitionExpr::new(
1339                        Operand::Expr(PartitionExpr::new(
1340                            Operand::Column("user_id".to_string()),
1341                            RestrictedOp::Eq,
1342                            Operand::Value(Value::Int64(100)),
1343                        )),
1344                        RestrictedOp::Or,
1345                        Operand::Expr(PartitionExpr::new(
1346                            Operand::Column("user_id".to_string()),
1347                            RestrictedOp::Eq,
1348                            Operand::Value(Value::Int64(200)),
1349                        )),
1350                    )),
1351                    RestrictedOp::Or,
1352                    Operand::Expr(PartitionExpr::new(
1353                        Operand::Expr(PartitionExpr::new(
1354                            Operand::Column("user_id".to_string()),
1355                            RestrictedOp::GtEq,
1356                            Operand::Value(Value::Int64(300)),
1357                        )),
1358                        RestrictedOp::And,
1359                        Operand::Expr(PartitionExpr::new(
1360                            Operand::Column("user_id".to_string()),
1361                            RestrictedOp::LtEq,
1362                            Operand::Value(Value::Int64(400)),
1363                        )),
1364                    )),
1365                )],
1366                vec!["user_id"],
1367            ),
1368        ];
1369        check_partition_expressions(cases);
1370    }
1371
1372    #[test]
1373    fn test_mixed_partition_non_partition_expressions() {
1374        let cases = vec![
1375            // Mixed AND expression - should extract only partition part
1376            FilterTestCase::new(
1377                "mixed_and_expression",
1378                col("user_id")
1379                    .eq(lit(100i64))
1380                    .and(col("value").gt(lit(50i64))),
1381                vec![PartitionExpr::new(
1382                    Operand::Column("user_id".to_string()),
1383                    RestrictedOp::Eq,
1384                    Operand::Value(Value::Int64(100)),
1385                )],
1386                vec!["user_id"],
1387            ),
1388            // Mixed OR expression - should be dropped entirely
1389            FilterTestCase::new(
1390                "mixed_or_expression",
1391                col("user_id")
1392                    .between(lit(1i64), lit(10i64))
1393                    .or(col("value").gt(lit(50i64))),
1394                vec![], // Empty result - expression should be dropped
1395                vec!["user_id"],
1396            ),
1397            // Complex mixed AND expression with multiple parts
1398            FilterTestCase::new(
1399                "complex_mixed_and",
1400                col("user_id")
1401                    .gt_eq(lit(100i64))
1402                    .and(col("value").eq(lit(200i64)))
1403                    .and(col("timestamp").lt(lit(1000i64))),
1404                vec![
1405                    PartitionExpr::new(
1406                        Operand::Column("user_id".to_string()),
1407                        RestrictedOp::GtEq,
1408                        Operand::Value(Value::Int64(100)),
1409                    ),
1410                    PartitionExpr::new(
1411                        Operand::Column("timestamp".to_string()),
1412                        RestrictedOp::Lt,
1413                        Operand::Value(Value::Int64(1000)),
1414                    ),
1415                ],
1416                vec!["user_id", "timestamp"], // Both partition columns
1417            ),
1418            // Pure partition expression - should be kept as-is
1419            FilterTestCase::new(
1420                "pure_partition_and",
1421                col("user_id")
1422                    .gt_eq(lit(100i64))
1423                    .and(col("timestamp").lt(lit(1000i64))),
1424                vec![PartitionExpr::new(
1425                    Operand::Expr(PartitionExpr::new(
1426                        Operand::Column("user_id".to_string()),
1427                        RestrictedOp::GtEq,
1428                        Operand::Value(Value::Int64(100)),
1429                    )),
1430                    RestrictedOp::And,
1431                    Operand::Expr(PartitionExpr::new(
1432                        Operand::Column("timestamp".to_string()),
1433                        RestrictedOp::Lt,
1434                        Operand::Value(Value::Int64(1000)),
1435                    )),
1436                )],
1437                vec!["user_id", "timestamp"],
1438            ),
1439            // Pure partition OR expression - should be kept as-is
1440            FilterTestCase::new(
1441                "pure_partition_or",
1442                col("user_id")
1443                    .eq(lit(100i64))
1444                    .or(col("user_id").eq(lit(200i64))),
1445                vec![PartitionExpr::new(
1446                    Operand::Expr(PartitionExpr::new(
1447                        Operand::Column("user_id".to_string()),
1448                        RestrictedOp::Eq,
1449                        Operand::Value(Value::Int64(100)),
1450                    )),
1451                    RestrictedOp::Or,
1452                    Operand::Expr(PartitionExpr::new(
1453                        Operand::Column("user_id".to_string()),
1454                        RestrictedOp::Eq,
1455                        Operand::Value(Value::Int64(200)),
1456                    )),
1457                )],
1458                vec!["user_id"],
1459            ),
1460            // Pure non-partition expression - should be dropped
1461            FilterTestCase::new(
1462                "pure_non_partition",
1463                col("value").gt_eq(lit(100i64)),
1464                vec![], // Empty result - no partition columns involved
1465                vec!["user_id"],
1466            ),
1467            // Complex nested mixed expression
1468            FilterTestCase::new(
1469                "nested_mixed_expression",
1470                (col("user_id")
1471                    .eq(lit(100i64))
1472                    .and(col("value").gt(lit(50i64))))
1473                .or(col("user_id").eq(lit(200i64))),
1474                vec![], // Empty result - OR with mixed sub-expression should be dropped
1475                vec!["user_id"],
1476            ),
1477            // AND with nested OR (mixed) - should extract partition parts only
1478            FilterTestCase::new(
1479                "and_with_nested_mixed_or",
1480                col("user_id")
1481                    .gt_eq(lit(100i64))
1482                    .and(col("value").eq(lit(1i64)).or(col("value").eq(lit(2i64)))),
1483                vec![PartitionExpr::new(
1484                    Operand::Column("user_id".to_string()),
1485                    RestrictedOp::GtEq,
1486                    Operand::Value(Value::Int64(100)),
1487                )],
1488                vec!["user_id"],
1489            ),
1490        ];
1491        check_partition_expressions(cases);
1492    }
1493}