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