Skip to main content

datafusion_physical_expr/expressions/
in_list.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Implementation of `InList` expressions: [`InListExpr`]
6
7use std::fmt::Debug;
8use std::hash::{Hash, Hasher};
9use std::sync::Arc;
10
11use crate::PhysicalExpr;
12use crate::expressions::Literal;
13use crate::physical_expr::physical_exprs_bag_equal;
14
15use arrow::array::*;
16use arrow::buffer::{BooleanBuffer, NullBuffer};
17use arrow::compute::SortOptions;
18use arrow::compute::kernels::boolean::{not, or_kleene};
19use arrow::compute::kernels::cmp::eq as arrow_eq;
20use arrow::datatypes::*;
21
22use datafusion_common::float_semantics::normalize_floats;
23use datafusion_common::tree_node::TreeNode;
24use datafusion_common::{
25    DFSchema, Result, ScalarValue, assert_or_internal_err, exec_err,
26};
27use datafusion_expr::{ColumnarValue, expr_vec_fmt};
28
29mod array_static_filter;
30mod branchless_filter;
31mod byte_view_filter;
32mod dictionary_filter;
33mod fixed_size_binary_filter;
34mod primitive_filter;
35mod result;
36mod static_filter;
37mod strategy;
38
39use static_filter::StaticFilterRef;
40use strategy::instantiate_static_filter;
41
42/// InList
43pub struct InListExpr {
44    expr: Arc<dyn PhysicalExpr>,
45    list: Vec<Arc<dyn PhysicalExpr>>,
46    negated: bool,
47    static_filter: Option<StaticFilterRef>,
48}
49
50impl Debug for InListExpr {
51    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
52        f.debug_struct("InListExpr")
53            .field("expr", &self.expr)
54            .field("list", &self.list)
55            .field("negated", &self.negated)
56            .finish()
57    }
58}
59
60/// Returns true if Arrow's vectorized `eq` kernel supports this data type.
61///
62/// Supported: primitives, boolean, strings (Utf8/LargeUtf8/Utf8View),
63/// binary (Binary/LargeBinary/BinaryView/FixedSizeBinary), Null, and
64/// Dictionary-encoded variants of the above.
65/// Unsupported: nested types (Struct, List, Map, Union) and RunEndEncoded.
66fn supports_arrow_eq(dt: &DataType) -> bool {
67    use DataType::*;
68    match dt {
69        Boolean | Binary | LargeBinary | BinaryView | FixedSizeBinary(_) => true,
70        Dictionary(_, v) => supports_arrow_eq(v.as_ref()),
71        _ => dt.is_primitive() || dt.is_null() || dt.is_string(),
72    }
73}
74
75fn normalize_in_list_value(value: ColumnarValue) -> ColumnarValue {
76    match value {
77        ColumnarValue::Array(array) => ColumnarValue::Array(normalize_floats(&array)),
78        ColumnarValue::Scalar(scalar) => ColumnarValue::Scalar(scalar.normalize()),
79    }
80}
81
82/// Evaluates the list of expressions into an array, flattening any dictionaries
83fn evaluate_list(
84    list: &[Arc<dyn PhysicalExpr>],
85    batch: &RecordBatch,
86) -> Result<ArrayRef> {
87    let scalars = list
88        .iter()
89        .map(|expr| {
90            expr.evaluate(batch).and_then(|r| match r {
91                ColumnarValue::Array(_) => {
92                    exec_err!("InList expression must evaluate to a scalar")
93                }
94                // Flatten dictionary values
95                ColumnarValue::Scalar(ScalarValue::Dictionary(_, v)) => Ok(*v),
96                ColumnarValue::Scalar(s) => Ok(s),
97            })
98        })
99        .collect::<Result<Vec<_>>>()?;
100
101    ScalarValue::iter_to_array(scalars)
102}
103
104/// Try to evaluate a list of expressions as constants.
105///
106/// Returns:
107/// - `Ok(Some(ArrayRef))` if all expressions are constants (built only from literals)
108/// - `Ok(None)` if the list contains non-constant expressions
109/// - `Err(...)` only for actual errors (not for non-constant expressions)
110///
111/// This is used to detect when a list contains only literals, casts of literals,
112/// or other constant expressions.
113fn try_evaluate_constant_list(
114    list: &[Arc<dyn PhysicalExpr>],
115    schema: &Schema,
116) -> Result<Option<ArrayRef>> {
117    // An item can read a column yet return a scalar on an empty batch (a CASE whose
118    // WHEN matches all zero rows returns its THEN), so require literal leaves.
119    for expr in list {
120        if expr.exists(|e| {
121            Ok(e.is_volatile_node() || (e.children().is_empty() && !e.is::<Literal>()))
122        })? {
123            return Ok(None);
124        }
125    }
126    let batch = RecordBatch::new_empty(Arc::new(schema.clone()));
127    match evaluate_list(list, &batch) {
128        Ok(array) => Ok(Some(array)),
129        Err(_) => {
130            // Non-constant expressions can't be evaluated on an empty batch
131            // This is not an error, just means we can't use a static filter
132            Ok(None)
133        }
134    }
135}
136
137/// Asserts that the InList expression's data type matches a list element's
138/// data type. `DataType::Null` list elements are accepted unconditionally so
139/// that null literals and `NullArray` haystacks remain compatible with any
140/// expression type.
141fn assert_inlist_data_types_match(
142    expr_data_type: &DataType,
143    list_data_type: &DataType,
144) -> Result<()> {
145    if *list_data_type != DataType::Null {
146        assert_or_internal_err!(
147            DFSchema::datatype_is_logically_equal(expr_data_type, list_data_type),
148            "The data type inlist should be same, the value type is {expr_data_type}, one of list expr type is {list_data_type}"
149        );
150    }
151    Ok(())
152}
153
154impl InListExpr {
155    /// Create a new InList expression
156    fn new(
157        expr: Arc<dyn PhysicalExpr>,
158        list: Vec<Arc<dyn PhysicalExpr>>,
159        negated: bool,
160        static_filter: Option<StaticFilterRef>,
161    ) -> Self {
162        Self {
163            expr,
164            list,
165            negated,
166            static_filter,
167        }
168    }
169
170    /// Input expression
171    pub fn expr(&self) -> &Arc<dyn PhysicalExpr> {
172        &self.expr
173    }
174
175    /// List to search in
176    pub fn list(&self) -> &[Arc<dyn PhysicalExpr>] {
177        &self.list
178    }
179
180    pub fn is_empty(&self) -> bool {
181        self.list.is_empty()
182    }
183
184    pub fn len(&self) -> usize {
185        self.list.len()
186    }
187
188    /// Is this negated e.g. NOT IN LIST
189    pub fn negated(&self) -> bool {
190        self.negated
191    }
192
193    /// Create a new InList expression directly from an array, bypassing expression evaluation.
194    ///
195    /// This is more efficient than [`InListExpr::try_new`] when you already have the list
196    /// as an array, as it builds the static filter directly from the array instead of
197    /// reconstructing an intermediate array from literal expressions.
198    ///
199    /// The `list` field is populated with literal expressions extracted from
200    /// the array, and the array is used to build a static filter for
201    /// efficient set membership evaluation.
202    ///
203    /// The `array` may be dictionary-encoded — it will be flattened to its
204    /// value type such that specialized filters are used.
205    ///
206    /// Returns an error if the expression's data type and the array's data type
207    /// are not logically equal. Null arrays are always accepted.
208    pub fn try_new_from_array(
209        expr: Arc<dyn PhysicalExpr>,
210        array: ArrayRef,
211        negated: bool,
212        schema: &Schema,
213    ) -> Result<Self> {
214        let expr_data_type = expr.data_type(schema)?;
215        assert_inlist_data_types_match(&expr_data_type, array.data_type())?;
216
217        let list = (0..array.len())
218            .map(|i| {
219                let scalar = ScalarValue::try_from_array(array.as_ref(), i)?;
220                Ok(crate::expressions::lit(scalar) as Arc<dyn PhysicalExpr>)
221            })
222            .collect::<Result<Vec<_>>>()?;
223        Ok(Self::new(
224            expr,
225            list,
226            negated,
227            Some(instantiate_static_filter(array, &expr_data_type)?),
228        ))
229    }
230
231    /// Create a new InList expression, using a static filter when possible.
232    ///
233    /// This validates data types and attempts to create a static filter for constant
234    /// list expressions. Uses specialized branchless, bitmap, or hash-set filters
235    /// when the list's physical representation supports them.
236    ///
237    /// Returns an error if data types don't match. If the list contains non-constant
238    /// expressions, falls back to dynamic evaluation at runtime.
239    pub fn try_new(
240        expr: Arc<dyn PhysicalExpr>,
241        list: Vec<Arc<dyn PhysicalExpr>>,
242        negated: bool,
243        schema: &Schema,
244    ) -> Result<Self> {
245        // Check the data types match
246        let expr_data_type = expr.data_type(schema)?;
247        for list_expr in list.iter() {
248            let list_expr_data_type = list_expr.data_type(schema)?;
249            assert_inlist_data_types_match(&expr_data_type, &list_expr_data_type)?;
250        }
251
252        // Try to create a static filter if all list expressions are constants
253        let static_filter = match try_evaluate_constant_list(&list, schema)? {
254            Some(in_array) => Some(instantiate_static_filter(in_array, &expr_data_type)?),
255            None => None, // Non-constant expressions, fall back to dynamic evaluation
256        };
257
258        Ok(Self::new(expr, list, negated, static_filter))
259    }
260
261    #[cfg(feature = "proto")]
262    pub fn try_from_proto(
263        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
264        ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
265    ) -> Result<Arc<dyn PhysicalExpr>> {
266        use datafusion_physical_expr_common::expect_expr_variant;
267        use datafusion_proto_models::protobuf;
268
269        let node = expect_expr_variant!(
270            node,
271            protobuf::physical_expr_node::ExprType::InList,
272            "InList",
273        );
274        let protobuf::PhysicalInListNode {
275            expr,
276            list,
277            negated,
278        } = &**node;
279
280        let expr =
281            ctx.decode_required_expression(expr.as_deref(), "InListExpr", "expr")?;
282        let list = ctx.decode_children_expressions(list)?;
283
284        Ok(Arc::new(InListExpr::try_new(
285            expr,
286            list,
287            *negated,
288            ctx.schema(),
289        )?))
290    }
291}
292impl std::fmt::Display for InListExpr {
293    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
294        let list = expr_vec_fmt!(self.list);
295
296        if self.negated {
297            if self.static_filter.is_some() {
298                write!(f, "{} NOT IN (SET) ([{list}])", self.expr)
299            } else {
300                write!(f, "{} NOT IN ([{list}])", self.expr)
301            }
302        } else if self.static_filter.is_some() {
303            write!(f, "{} IN (SET) ([{list}])", self.expr)
304        } else {
305            write!(f, "{} IN ([{list}])", self.expr)
306        }
307    }
308}
309
310impl PhysicalExpr for InListExpr {
311    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
312        Ok(DataType::Boolean)
313    }
314
315    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
316        if self.expr.nullable(input_schema)? {
317            return Ok(true);
318        }
319
320        if let Some(static_filter) = &self.static_filter {
321            Ok(static_filter.null_count() > 0)
322        } else {
323            for expr in &self.list {
324                if expr.nullable(input_schema)? {
325                    return Ok(true);
326                }
327            }
328            Ok(false)
329        }
330    }
331
332    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
333        let num_rows = batch.num_rows();
334        let value = self.expr.evaluate(batch)?;
335        let r = match &self.static_filter {
336            Some(filter) => {
337                match value {
338                    ColumnarValue::Array(array) => {
339                        filter.contains(&array, self.negated)?
340                    }
341                    ColumnarValue::Scalar(scalar) => {
342                        if scalar.is_null() {
343                            // SQL three-valued logic: null IN (...) is always null
344                            // The code below would handle this correctly but this is a faster path
345                            let nulls = NullBuffer::new_null(num_rows);
346                            return Ok(ColumnarValue::Array(Arc::new(
347                                BooleanArray::new(
348                                    BooleanBuffer::new_unset(num_rows),
349                                    Some(nulls),
350                                ),
351                            )));
352                        }
353                        // Use a 1 row array to avoid code duplication/branching
354                        // Since all we do is compute hash and lookup this should be efficient enough
355                        let array = scalar.to_array()?;
356                        let result_array =
357                            filter.contains(array.as_ref(), self.negated)?;
358                        // Broadcast the single result to all rows
359                        // Must check is_null() to preserve NULL values (SQL three-valued logic)
360                        if result_array.is_null(0) {
361                            let nulls = NullBuffer::new_null(num_rows);
362                            BooleanArray::new(
363                                BooleanBuffer::new_unset(num_rows),
364                                Some(nulls),
365                            )
366                        } else if result_array.value(0) {
367                            BooleanArray::new(BooleanBuffer::new_set(num_rows), None)
368                        } else {
369                            BooleanArray::new(BooleanBuffer::new_unset(num_rows), None)
370                        }
371                    }
372                }
373            }
374            None => {
375                // No static filter: iterate through each expression, compare, and OR results.
376                // Use Arrow's vectorized eq kernel for types it supports (primitive,
377                // boolean, string, binary, dictionary), falling back to row-by-row
378                // comparator for unsupported types (nested, RunEndEncoded, etc.).
379                // Normalize the left side once for the whole list. Doing this
380                // outside `compare_one` avoids rescanning it for every item.
381                let value = normalize_in_list_value(value).into_array(num_rows)?;
382                let lhs_supports_arrow_eq = supports_arrow_eq(value.data_type());
383
384                // Helper: compare value against a single list expression
385                let compare_one = |expr: &Arc<dyn PhysicalExpr>| -> Result<BooleanArray> {
386                    match normalize_in_list_value(expr.evaluate(batch)?) {
387                        ColumnarValue::Array(array) => {
388                            if lhs_supports_arrow_eq
389                                && supports_arrow_eq(array.data_type())
390                            {
391                                Ok(arrow_eq(&value, &array)?)
392                            } else {
393                                let cmp = make_comparator(
394                                    value.as_ref(),
395                                    array.as_ref(),
396                                    SortOptions::default(),
397                                )?;
398                                let buffer = BooleanBuffer::collect_bool(num_rows, |i| {
399                                    cmp(i, i).is_eq()
400                                });
401                                let nulls =
402                                    NullBuffer::union(value.nulls(), array.nulls());
403                                Ok(BooleanArray::new(buffer, nulls))
404                            }
405                        }
406                        ColumnarValue::Scalar(scalar) => {
407                            // Check if scalar is null once, before the loop
408                            if scalar.is_null() {
409                                // If scalar is null, all comparisons return null
410                                Ok(BooleanArray::from(vec![None; num_rows]))
411                            } else if lhs_supports_arrow_eq {
412                                let scalar_datum = scalar.to_scalar()?;
413                                Ok(arrow_eq(&value, &scalar_datum)?)
414                            } else {
415                                // Convert scalar to 1-element array
416                                let array = scalar.to_array()?;
417                                let cmp = make_comparator(
418                                    value.as_ref(),
419                                    array.as_ref(),
420                                    SortOptions::default(),
421                                )?;
422                                // Compare each row of value with the single scalar element
423                                let buffer = BooleanBuffer::collect_bool(num_rows, |i| {
424                                    cmp(i, 0).is_eq()
425                                });
426                                Ok(BooleanArray::new(buffer, value.nulls().cloned()))
427                            }
428                        }
429                    }
430                };
431
432                // Evaluate first expression directly to avoid a redundant
433                // or_kleene with an all-false accumulator.
434                let mut found = if let Some(first) = self.list.first() {
435                    compare_one(first)?
436                } else {
437                    BooleanArray::new(BooleanBuffer::new_unset(num_rows), None)
438                };
439
440                for expr in self.list.iter().skip(1) {
441                    // Short-circuit: if every non-null row is already true,
442                    // no further list items can change the result.
443                    if found.null_count() == 0 && !found.has_false() {
444                        break;
445                    }
446                    found = or_kleene(&found, &compare_one(expr)?)?;
447                }
448
449                if self.negated { not(&found)? } else { found }
450            }
451        };
452        Ok(ColumnarValue::Array(Arc::new(r)))
453    }
454
455    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
456        let mut children = Vec::with_capacity(self.list.len() + 1);
457        children.push(&self.expr);
458        children.extend(&self.list);
459        children
460    }
461
462    fn with_new_children(
463        self: Arc<Self>,
464        children: Vec<Arc<dyn PhysicalExpr>>,
465    ) -> Result<Arc<dyn PhysicalExpr>> {
466        // assume the static_filter will not change during the rewrite process
467        Ok(Arc::new(InListExpr::new(
468            Arc::clone(&children[0]),
469            children[1..].to_vec(),
470            self.negated,
471            self.static_filter.as_ref().map(Arc::clone),
472        )))
473    }
474
475    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476        self.expr.fmt_sql(f)?;
477        if self.negated {
478            write!(f, " NOT")?;
479        }
480
481        write!(f, " IN (")?;
482        for (i, expr) in self.list.iter().enumerate() {
483            if i > 0 {
484                write!(f, ", ")?;
485            }
486            expr.fmt_sql(f)?;
487        }
488        write!(f, ")")
489    }
490
491    #[cfg(feature = "proto")]
492    fn try_to_proto(
493        &self,
494        ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
495    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
496        use datafusion_proto_models::protobuf;
497
498        let Self {
499            expr,
500            list,
501            negated,
502            // Lookup set rebuilt from `list` by `try_new` on decode.
503            static_filter: _,
504        } = self;
505
506        Ok(Some(protobuf::PhysicalExprNode {
507            expr_id: None,
508            expr_type: Some(protobuf::physical_expr_node::ExprType::InList(Box::new(
509                protobuf::PhysicalInListNode {
510                    expr: Some(Box::new(ctx.encode_child(expr)?)),
511                    list: ctx.encode_children_expressions(list)?,
512                    negated: *negated,
513                },
514            ))),
515        }))
516    }
517}
518
519impl PartialEq for InListExpr {
520    fn eq(&self, other: &Self) -> bool {
521        self.expr.eq(&other.expr)
522            && physical_exprs_bag_equal(&self.list, &other.list)
523            && self.negated == other.negated
524    }
525}
526
527impl Eq for InListExpr {}
528
529impl Hash for InListExpr {
530    fn hash<H: Hasher>(&self, state: &mut H) {
531        self.expr.hash(state);
532        self.negated.hash(state);
533        // Add `self.static_filter` when hash is available
534        self.list.hash(state);
535    }
536}
537
538/// Creates a unary expression InList
539pub fn in_list(
540    expr: Arc<dyn PhysicalExpr>,
541    list: Vec<Arc<dyn PhysicalExpr>>,
542    negated: &bool,
543    schema: &Schema,
544) -> Result<Arc<dyn PhysicalExpr>> {
545    Ok(Arc::new(InListExpr::try_new(expr, list, *negated, schema)?))
546}
547
548#[cfg(test)]
549mod tests {
550    use super::*;
551    use crate::expressions::{binary, case, col, lit, try_cast};
552    use arrow::datatypes::{IntervalDayTime, IntervalMonthDayNano, i256};
553    use datafusion_common::plan_err;
554    use datafusion_expr::Operator;
555    use datafusion_expr::type_coercion::binary::comparison_coercion;
556    use datafusion_physical_expr_common::physical_expr::fmt_sql;
557    use insta::assert_snapshot;
558    use itertools::Itertools;
559
560    type InListCastResult = (Arc<dyn PhysicalExpr>, Vec<Arc<dyn PhysicalExpr>>);
561
562    // Try to do the type coercion for list physical expr.
563    // It's just used in the test
564    fn in_list_cast(
565        expr: Arc<dyn PhysicalExpr>,
566        list: Vec<Arc<dyn PhysicalExpr>>,
567        input_schema: &Schema,
568    ) -> Result<InListCastResult> {
569        let expr_type = &expr.data_type(input_schema)?;
570        let list_types: Vec<DataType> = list
571            .iter()
572            .map(|list_expr| list_expr.data_type(input_schema).unwrap())
573            .collect();
574        let result_type = get_coerce_type(expr_type, &list_types);
575        match result_type {
576            None => plan_err!(
577                "Can not find compatible types to compare {expr_type} with [{}]",
578                list_types.iter().join(", ")
579            ),
580            Some(data_type) => {
581                // find the coerced type
582                let cast_expr = try_cast(expr, input_schema, data_type.clone())?;
583                let cast_list_expr = list
584                    .into_iter()
585                    .map(|list_expr| {
586                        try_cast(list_expr, input_schema, data_type.clone()).unwrap()
587                    })
588                    .collect();
589                Ok((cast_expr, cast_list_expr))
590            }
591        }
592    }
593
594    // Attempts to coerce the types of `list_type` to be comparable with the
595    // `expr_type`
596    fn get_coerce_type(expr_type: &DataType, list_type: &[DataType]) -> Option<DataType> {
597        list_type
598            .iter()
599            .try_fold(expr_type.clone(), |left_type, right_type| {
600                comparison_coercion(&left_type, right_type)
601            })
602    }
603
604    /// Test helper macro that evaluates an IN LIST expression with automatic type casting.
605    ///
606    /// # Parameters
607    /// - `$BATCH`: The `RecordBatch` containing the input data to evaluate against
608    /// - `$LIST`: A `Vec<Arc<dyn PhysicalExpr>>` of literal expressions representing the IN list values
609    /// - `$NEGATED`: A `&bool` indicating whether this is a NOT IN operation (true) or IN operation (false)
610    /// - `$EXPECTED`: A `Vec<Option<bool>>` representing the expected boolean results for each row
611    /// - `$COL`: An `Arc<dyn PhysicalExpr>` representing the column expression to evaluate
612    /// - `$SCHEMA`: A `&Schema` reference for the input batch
613    ///
614    /// This macro first applies type casting to the column and list expressions to ensure
615    /// type compatibility, then delegates to `in_list_raw!` to perform the evaluation and assertion.
616    macro_rules! in_list {
617        ($BATCH:expr, $LIST:expr, $NEGATED:expr, $EXPECTED:expr, $COL:expr, $SCHEMA:expr) => {{
618            let (cast_expr, cast_list_exprs) = in_list_cast($COL, $LIST, $SCHEMA)?;
619            in_list_raw!(
620                $BATCH,
621                cast_list_exprs,
622                $NEGATED,
623                $EXPECTED,
624                cast_expr,
625                $SCHEMA
626            );
627        }};
628    }
629
630    /// Test helper macro that evaluates an IN LIST expression without automatic type casting.
631    ///
632    /// # Parameters
633    /// - `$BATCH`: The `RecordBatch` containing the input data to evaluate against
634    /// - `$LIST`: A `Vec<Arc<dyn PhysicalExpr>>` of literal expressions representing the IN list values
635    /// - `$NEGATED`: A `&bool` indicating whether this is a NOT IN operation (true) or IN operation (false)
636    /// - `$EXPECTED`: A `Vec<Option<bool>>` representing the expected boolean results for each row
637    /// - `$COL`: An `Arc<dyn PhysicalExpr>` representing the column expression to evaluate
638    /// - `$SCHEMA`: A `&Schema` reference for the input batch
639    ///
640    /// This macro creates an IN LIST expression, evaluates it against the batch, converts the result
641    /// to a `BooleanArray`, and asserts that it matches the expected output. Use this when the column
642    /// and list expressions are already the correct types and don't require casting.
643    macro_rules! in_list_raw {
644        ($BATCH:expr, $LIST:expr, $NEGATED:expr, $EXPECTED:expr, $COL:expr, $SCHEMA:expr) => {{
645            let col_expr = $COL;
646            let expr = in_list(Arc::clone(&col_expr), $LIST, $NEGATED, $SCHEMA).unwrap();
647            let result = expr
648                .evaluate(&$BATCH)?
649                .into_array($BATCH.num_rows())
650                .expect("Failed to convert to array");
651            let result = as_boolean_array(&result);
652            let expected = &BooleanArray::from($EXPECTED);
653            assert_eq!(
654                expected,
655                result,
656                "Failed for: {}\n{}: {:?}",
657                fmt_sql(expr.as_ref()),
658                fmt_sql(col_expr.as_ref()),
659                col_expr
660                    .evaluate(&$BATCH)?
661                    .into_array($BATCH.num_rows())
662                    .unwrap()
663            );
664        }};
665    }
666
667    /// Test case for primitive types following the standard IN LIST pattern.
668    ///
669    /// Each test case represents a data type with:
670    /// - `value_in`: A value that appears in both the test array and the IN list (matches → true)
671    /// - `value_not_in`: A value that appears in the test array but NOT in the IN list (doesn't match → false)
672    /// - `other_list_values`: Additional values in the IN list besides `value_in`
673    /// - `null_value`: Optional null scalar value for NULL handling tests. When None, tests
674    ///   without nulls are run, exercising the `(false, false)` and `(false, true)` branches.
675    struct InListPrimitiveTestCase {
676        name: &'static str,
677        value_in: ScalarValue,
678        value_not_in: ScalarValue,
679        other_list_values: Vec<ScalarValue>,
680        null_value: Option<ScalarValue>,
681    }
682
683    /// Generic test data struct for primitive types.
684    ///
685    /// Holds test values needed for IN LIST tests, allowing the data
686    /// to be declared explicitly and reused across multiple types.
687    #[derive(Clone)]
688    struct PrimitiveTestCaseData<T> {
689        value_in: T,
690        value_not_in: T,
691        other_list_values: Vec<T>,
692    }
693
694    /// Helper to create test cases for any primitive type using generic data.
695    ///
696    /// Uses TryInto for flexible type conversion, allowing test data to be
697    /// declared in any convertible type (e.g., i32 for all integer types).
698    /// Creates a test case WITH null support (for null handling tests).
699    fn primitive_test_case<T, D, F>(
700        name: &'static str,
701        constructor: F,
702        data: PrimitiveTestCaseData<D>,
703    ) -> InListPrimitiveTestCase
704    where
705        D: TryInto<T> + Clone,
706        <D as TryInto<T>>::Error: Debug,
707        F: Fn(Option<T>) -> ScalarValue,
708        T: Clone,
709    {
710        InListPrimitiveTestCase {
711            name,
712            value_in: constructor(Some(data.value_in.try_into().unwrap())),
713            value_not_in: constructor(Some(data.value_not_in.try_into().unwrap())),
714            other_list_values: data
715                .other_list_values
716                .into_iter()
717                .map(|v| constructor(Some(v.try_into().unwrap())))
718                .collect(),
719            null_value: Some(constructor(None)),
720        }
721    }
722
723    /// Helper to create test cases WITHOUT null support.
724    /// These test cases exercise the `(false, true)` branch (no nulls, negated).
725    fn primitive_test_case_no_nulls<T, D, F>(
726        name: &'static str,
727        constructor: F,
728        data: PrimitiveTestCaseData<D>,
729    ) -> InListPrimitiveTestCase
730    where
731        D: TryInto<T> + Clone,
732        <D as TryInto<T>>::Error: Debug,
733        F: Fn(Option<T>) -> ScalarValue,
734        T: Clone,
735    {
736        InListPrimitiveTestCase {
737            name,
738            value_in: constructor(Some(data.value_in.try_into().unwrap())),
739            value_not_in: constructor(Some(data.value_not_in.try_into().unwrap())),
740            other_list_values: data
741                .other_list_values
742                .into_iter()
743                .map(|v| constructor(Some(v.try_into().unwrap())))
744                .collect(),
745            null_value: None,
746        }
747    }
748
749    /// Runs test cases for multiple types, providing detailed SQL error messages on failure.
750    ///
751    /// For each test case, runs IN LIST scenarios based on whether null_value is Some or None:
752    /// - With null_value (Some): 4 tests including null handling
753    /// - Without null_value (None): 2 tests exercising the no-nulls paths
754    fn run_test_cases(test_cases: Vec<InListPrimitiveTestCase>) -> Result<()> {
755        for test_case in test_cases {
756            let test_name = test_case.name;
757
758            // Get the data type from the scalar value
759            let data_type = test_case.value_in.data_type();
760
761            // Build the base list: [value_in, ...other_list_values]
762            let build_base_list = || -> Vec<Arc<dyn PhysicalExpr>> {
763                let mut list = vec![lit(test_case.value_in.clone())];
764                list.extend(test_case.other_list_values.iter().map(|v| lit(v.clone())));
765                list
766            };
767
768            match &test_case.null_value {
769                Some(null_val) => {
770                    // Tests WITH nulls in the needle array
771                    let schema =
772                        Schema::new(vec![Field::new("a", data_type.clone(), true)]);
773
774                    // Create array from scalar values: [value_in, value_not_in, None]
775                    let array = ScalarValue::iter_to_array(vec![
776                        test_case.value_in.clone(),
777                        test_case.value_not_in.clone(),
778                        null_val.clone(),
779                    ])?;
780
781                    let col_a = col("a", &schema)?;
782                    let batch = RecordBatch::try_new(
783                        Arc::new(schema.clone()),
784                        vec![Arc::clone(&array)],
785                    )?;
786
787                    // Test 1: a IN (list) → [true, false, null]
788                    let list = build_base_list();
789                    in_list!(
790                        batch,
791                        list,
792                        &false,
793                        vec![Some(true), Some(false), None],
794                        Arc::clone(&col_a),
795                        &schema
796                    );
797
798                    // Test 2: a NOT IN (list) → [false, true, null]
799                    let list = build_base_list();
800                    in_list!(
801                        batch,
802                        list,
803                        &true,
804                        vec![Some(false), Some(true), None],
805                        Arc::clone(&col_a),
806                        &schema
807                    );
808
809                    // Test 3: a IN (list, NULL) → [true, null, null]
810                    let mut list = build_base_list();
811                    list.push(lit(null_val.clone()));
812                    in_list!(
813                        batch,
814                        list,
815                        &false,
816                        vec![Some(true), None, None],
817                        Arc::clone(&col_a),
818                        &schema
819                    );
820
821                    // Test 4: a NOT IN (list, NULL) → [false, null, null]
822                    let mut list = build_base_list();
823                    list.push(lit(null_val.clone()));
824                    in_list!(
825                        batch,
826                        list,
827                        &true,
828                        vec![Some(false), None, None],
829                        Arc::clone(&col_a),
830                        &schema
831                    );
832                }
833                None => {
834                    // Tests WITHOUT nulls - exercises the (false, false) and (false, true) branches
835                    let schema =
836                        Schema::new(vec![Field::new("a", data_type.clone(), false)]);
837
838                    // Create array from scalar values: [value_in, value_not_in] (no NULL)
839                    let array = ScalarValue::iter_to_array(vec![
840                        test_case.value_in.clone(),
841                        test_case.value_not_in.clone(),
842                    ])?;
843
844                    let col_a = col("a", &schema)?;
845                    let batch = RecordBatch::try_new(
846                        Arc::new(schema.clone()),
847                        vec![Arc::clone(&array)],
848                    )?;
849
850                    // Test 1: a IN (list) → [true, false] - exercises (false, false) branch
851                    let list = build_base_list();
852                    in_list!(
853                        batch,
854                        list,
855                        &false,
856                        vec![Some(true), Some(false)],
857                        Arc::clone(&col_a),
858                        &schema
859                    );
860
861                    // Test 2: a NOT IN (list) → [false, true] - exercises (false, true) branch
862                    let list = build_base_list();
863                    in_list!(
864                        batch,
865                        list,
866                        &true,
867                        vec![Some(false), Some(true)],
868                        Arc::clone(&col_a),
869                        &schema
870                    );
871
872                    eprintln!(
873                        "Test '{test_name}': exercised (false, true) branch (no nulls, negated)",
874                    );
875                }
876            }
877        }
878
879        Ok(())
880    }
881
882    /// Test IN LIST for all integer types (Int8/16/32/64, UInt8/16/32/64).
883    ///
884    /// Test data: 0 (in list), 2 (not in list), [1, 3, 5] (other list values)
885    #[test]
886    fn in_list_int_types() -> Result<()> {
887        let int_data = PrimitiveTestCaseData {
888            value_in: 0,
889            value_not_in: 2,
890            other_list_values: vec![1, 3, 5],
891        };
892
893        run_test_cases(vec![
894            // Tests WITH nulls
895            primitive_test_case("int8", ScalarValue::Int8, int_data.clone()),
896            primitive_test_case("int16", ScalarValue::Int16, int_data.clone()),
897            primitive_test_case("int32", ScalarValue::Int32, int_data.clone()),
898            primitive_test_case("int64", ScalarValue::Int64, int_data.clone()),
899            primitive_test_case("uint8", ScalarValue::UInt8, int_data.clone()),
900            primitive_test_case("uint16", ScalarValue::UInt16, int_data.clone()),
901            primitive_test_case("uint32", ScalarValue::UInt32, int_data.clone()),
902            primitive_test_case("uint64", ScalarValue::UInt64, int_data.clone()),
903            // Tests WITHOUT nulls - exercises (false, true) branch
904            primitive_test_case_no_nulls("int32_no_nulls", ScalarValue::Int32, int_data),
905        ])
906    }
907
908    /// Test IN LIST for all string types (Utf8, LargeUtf8, Utf8View).
909    ///
910    /// Test data: "a" (in list), "d" (not in list), `["b", "c"]` (other list values)
911    #[test]
912    fn in_list_string_types() -> Result<()> {
913        let string_data = PrimitiveTestCaseData {
914            value_in: "a",
915            value_not_in: "d",
916            other_list_values: vec!["b", "c"],
917        };
918
919        run_test_cases(vec![
920            primitive_test_case("utf8", ScalarValue::Utf8, string_data.clone()),
921            primitive_test_case(
922                "large_utf8",
923                ScalarValue::LargeUtf8,
924                string_data.clone(),
925            ),
926            primitive_test_case("utf8_view", ScalarValue::Utf8View, string_data),
927        ])
928    }
929
930    /// Test IN LIST for all binary types (Binary, LargeBinary, BinaryView).
931    ///
932    /// Test data: [1,2,3] (in list), [1,2,2] (not in list), [[4,5,6], [7,8,9]] (other list values)
933    #[test]
934    fn in_list_binary_types() -> Result<()> {
935        let binary_data = PrimitiveTestCaseData {
936            value_in: vec![1_u8, 2, 3],
937            value_not_in: vec![1_u8, 2, 2],
938            other_list_values: vec![vec![4_u8, 5, 6], vec![7_u8, 8, 9]],
939        };
940
941        run_test_cases(vec![
942            primitive_test_case("binary", ScalarValue::Binary, binary_data.clone()),
943            primitive_test_case(
944                "large_binary",
945                ScalarValue::LargeBinary,
946                binary_data.clone(),
947            ),
948            primitive_test_case("binary_view", ScalarValue::BinaryView, binary_data),
949        ])
950    }
951
952    /// Test IN LIST for date types (Date32, Date64).
953    ///
954    /// Test data: 0 (in list), 2 (not in list), [1, 3] (other list values)
955    #[test]
956    fn in_list_date_types() -> Result<()> {
957        let date_data = PrimitiveTestCaseData {
958            value_in: 0,
959            value_not_in: 2,
960            other_list_values: vec![1, 3],
961        };
962
963        run_test_cases(vec![
964            primitive_test_case("date32", ScalarValue::Date32, date_data.clone()),
965            primitive_test_case("date64", ScalarValue::Date64, date_data),
966        ])
967    }
968
969    /// Test IN LIST for Decimal128 type.
970    ///
971    /// Test data: 0 (in list), 200 (not in list), [100, 300] (other list values) with precision=10, scale=2
972    #[test]
973    fn in_list_decimal() -> Result<()> {
974        run_test_cases(vec![InListPrimitiveTestCase {
975            name: "decimal128",
976            value_in: ScalarValue::Decimal128(Some(0), 10, 2),
977            value_not_in: ScalarValue::Decimal128(Some(200), 10, 2),
978            other_list_values: vec![
979                ScalarValue::Decimal128(Some(100), 10, 2),
980                ScalarValue::Decimal128(Some(300), 10, 2),
981            ],
982            null_value: Some(ScalarValue::Decimal128(None, 10, 2)),
983        }])
984    }
985
986    /// Test IN LIST for timestamp types.
987    ///
988    /// Test data: 0 (in list), 2000 (not in list), [1000, 3000] (other list values)
989    #[test]
990    fn in_list_timestamp_types() -> Result<()> {
991        run_test_cases(vec![
992            InListPrimitiveTestCase {
993                name: "timestamp_nanosecond",
994                value_in: ScalarValue::TimestampNanosecond(Some(0), None),
995                value_not_in: ScalarValue::TimestampNanosecond(Some(2000), None),
996                other_list_values: vec![
997                    ScalarValue::TimestampNanosecond(Some(1000), None),
998                    ScalarValue::TimestampNanosecond(Some(3000), None),
999                ],
1000                null_value: Some(ScalarValue::TimestampNanosecond(None, None)),
1001            },
1002            InListPrimitiveTestCase {
1003                name: "timestamp_millisecond_with_tz",
1004                value_in: ScalarValue::TimestampMillisecond(
1005                    Some(1500000),
1006                    Some("+05:00".into()),
1007                ),
1008                value_not_in: ScalarValue::TimestampMillisecond(
1009                    Some(2500000),
1010                    Some("+05:00".into()),
1011                ),
1012                other_list_values: vec![ScalarValue::TimestampMillisecond(
1013                    Some(3500000),
1014                    Some("+05:00".into()),
1015                )],
1016                null_value: Some(ScalarValue::TimestampMillisecond(
1017                    None,
1018                    Some("+05:00".into()),
1019                )),
1020            },
1021            InListPrimitiveTestCase {
1022                name: "timestamp_millisecond_mixed_tz",
1023                value_in: ScalarValue::TimestampMillisecond(
1024                    Some(1500000),
1025                    Some("+05:00".into()),
1026                ),
1027                value_not_in: ScalarValue::TimestampMillisecond(
1028                    Some(2500000),
1029                    Some("+05:00".into()),
1030                ),
1031                other_list_values: vec![
1032                    ScalarValue::TimestampMillisecond(
1033                        Some(3500000),
1034                        Some("+01:00".into()),
1035                    ),
1036                    ScalarValue::TimestampMillisecond(Some(4500000), Some("UTC".into())),
1037                ],
1038                null_value: Some(ScalarValue::TimestampMillisecond(
1039                    None,
1040                    Some("+05:00".into()),
1041                )),
1042            },
1043        ])
1044    }
1045
1046    #[test]
1047    fn in_list_float64() -> Result<()> {
1048        let schema = Schema::new(vec![Field::new("a", DataType::Float64, true)]);
1049        let a = Float64Array::from(vec![
1050            Some(0.0),
1051            Some(0.2),
1052            None,
1053            Some(f64::NAN),
1054            Some(-f64::NAN),
1055        ]);
1056        let col_a = col("a", &schema)?;
1057        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
1058
1059        // expression: "a in (0.0, 0.1)"
1060        let list = vec![lit(0.0f64), lit(0.1f64)];
1061        in_list!(
1062            batch,
1063            list,
1064            &false,
1065            vec![Some(true), Some(false), None, Some(false), Some(false)],
1066            Arc::clone(&col_a),
1067            &schema
1068        );
1069
1070        // expression: "a not in (0.0, 0.1)"
1071        let list = vec![lit(0.0f64), lit(0.1f64)];
1072        in_list!(
1073            batch,
1074            list,
1075            &true,
1076            vec![Some(false), Some(true), None, Some(true), Some(true)],
1077            Arc::clone(&col_a),
1078            &schema
1079        );
1080
1081        // expression: "a in (0.0, 0.1, NULL)"
1082        let list = vec![lit(0.0f64), lit(0.1f64), lit(ScalarValue::Null)];
1083        in_list!(
1084            batch,
1085            list,
1086            &false,
1087            vec![Some(true), None, None, None, None],
1088            Arc::clone(&col_a),
1089            &schema
1090        );
1091
1092        // expression: "a not in (0.0, 0.1, NULL)"
1093        let list = vec![lit(0.0f64), lit(0.1f64), lit(ScalarValue::Null)];
1094        in_list!(
1095            batch,
1096            list,
1097            &true,
1098            vec![Some(false), None, None, None, None],
1099            Arc::clone(&col_a),
1100            &schema
1101        );
1102
1103        // expression: "a in (0.0, 0.1, NaN)"
1104        let list = vec![lit(0.0f64), lit(0.1f64), lit(f64::NAN)];
1105        in_list!(
1106            batch,
1107            list,
1108            &false,
1109            vec![Some(true), Some(false), None, Some(true), Some(false)],
1110            Arc::clone(&col_a),
1111            &schema
1112        );
1113
1114        // expression: "a not in (0.0, 0.1, NaN)"
1115        let list = vec![lit(0.0f64), lit(0.1f64), lit(f64::NAN)];
1116        in_list!(
1117            batch,
1118            list,
1119            &true,
1120            vec![Some(false), Some(true), None, Some(false), Some(true)],
1121            Arc::clone(&col_a),
1122            &schema
1123        );
1124
1125        // expression: "a in (0.0, 0.1, -NaN)"
1126        let list = vec![lit(0.0f64), lit(0.1f64), lit(-f64::NAN)];
1127        in_list!(
1128            batch,
1129            list,
1130            &false,
1131            vec![Some(true), Some(false), None, Some(false), Some(true)],
1132            Arc::clone(&col_a),
1133            &schema
1134        );
1135
1136        // expression: "a not in (0.0, 0.1, -NaN)"
1137        let list = vec![lit(0.0f64), lit(0.1f64), lit(-f64::NAN)];
1138        in_list!(
1139            batch,
1140            list,
1141            &true,
1142            vec![Some(false), Some(true), None, Some(true), Some(false)],
1143            Arc::clone(&col_a),
1144            &schema
1145        );
1146
1147        Ok(())
1148    }
1149
1150    #[test]
1151    fn in_list_bool() -> Result<()> {
1152        let schema = Schema::new(vec![Field::new("a", DataType::Boolean, true)]);
1153        let a = BooleanArray::from(vec![Some(true), None]);
1154        let col_a = col("a", &schema)?;
1155        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
1156
1157        // expression: "a in (true)"
1158        let list = vec![lit(true)];
1159        in_list!(
1160            batch,
1161            list,
1162            &false,
1163            vec![Some(true), None],
1164            Arc::clone(&col_a),
1165            &schema
1166        );
1167
1168        // expression: "a not in (true)"
1169        let list = vec![lit(true)];
1170        in_list!(
1171            batch,
1172            list,
1173            &true,
1174            vec![Some(false), None],
1175            Arc::clone(&col_a),
1176            &schema
1177        );
1178
1179        // expression: "a in (true, NULL)"
1180        let list = vec![lit(true), lit(ScalarValue::Null)];
1181        in_list!(
1182            batch,
1183            list,
1184            &false,
1185            vec![Some(true), None],
1186            Arc::clone(&col_a),
1187            &schema
1188        );
1189
1190        // expression: "a not in (true, NULL)"
1191        let list = vec![lit(true), lit(ScalarValue::Null)];
1192        in_list!(
1193            batch,
1194            list,
1195            &true,
1196            vec![Some(false), None],
1197            Arc::clone(&col_a),
1198            &schema
1199        );
1200
1201        Ok(())
1202    }
1203
1204    macro_rules! test_nullable {
1205        ($COL:expr, $LIST:expr, $SCHEMA:expr, $EXPECTED:expr) => {{
1206            let (cast_expr, cast_list_exprs) = in_list_cast($COL, $LIST, $SCHEMA)?;
1207            let expr = in_list(cast_expr, cast_list_exprs, &false, $SCHEMA).unwrap();
1208            let result = expr.nullable($SCHEMA)?;
1209            assert_eq!($EXPECTED, result);
1210        }};
1211    }
1212
1213    #[test]
1214    fn in_list_nullable() -> Result<()> {
1215        let schema = Schema::new(vec![
1216            Field::new("c1_nullable", DataType::Int64, true),
1217            Field::new("c2_non_nullable", DataType::Int64, false),
1218        ]);
1219
1220        let c1_nullable = col("c1_nullable", &schema)?;
1221        let c2_non_nullable = col("c2_non_nullable", &schema)?;
1222
1223        // static_filter has no nulls
1224        let list = vec![lit(1_i64), lit(2_i64)];
1225        test_nullable!(Arc::clone(&c1_nullable), list.clone(), &schema, true);
1226        test_nullable!(Arc::clone(&c2_non_nullable), list.clone(), &schema, false);
1227
1228        // static_filter has nulls
1229        let list = vec![lit(1_i64), lit(2_i64), lit(ScalarValue::Null)];
1230        test_nullable!(Arc::clone(&c1_nullable), list.clone(), &schema, true);
1231        test_nullable!(Arc::clone(&c2_non_nullable), list.clone(), &schema, true);
1232
1233        let list = vec![Arc::clone(&c1_nullable)];
1234        test_nullable!(Arc::clone(&c2_non_nullable), list.clone(), &schema, true);
1235
1236        let list = vec![Arc::clone(&c2_non_nullable)];
1237        test_nullable!(Arc::clone(&c1_nullable), list.clone(), &schema, true);
1238
1239        let list = vec![Arc::clone(&c2_non_nullable), Arc::clone(&c2_non_nullable)];
1240        test_nullable!(Arc::clone(&c2_non_nullable), list.clone(), &schema, false);
1241
1242        Ok(())
1243    }
1244
1245    #[test]
1246    fn in_list_no_cols() -> Result<()> {
1247        // test logic when the in_list expression doesn't have any columns
1248        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
1249        let a = Int32Array::from(vec![Some(1), Some(2), None]);
1250        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
1251
1252        let list = vec![lit(ScalarValue::from(1i32)), lit(ScalarValue::from(6i32))];
1253
1254        // 1 IN (1, 6)
1255        let expr = lit(ScalarValue::Int32(Some(1)));
1256        in_list!(
1257            batch,
1258            list.clone(),
1259            &false,
1260            // should have three outputs, as the input batch has three rows
1261            vec![Some(true), Some(true), Some(true)],
1262            expr,
1263            &schema
1264        );
1265
1266        // 2 IN (1, 6)
1267        let expr = lit(ScalarValue::Int32(Some(2)));
1268        in_list!(
1269            batch,
1270            list.clone(),
1271            &false,
1272            // should have three outputs, as the input batch has three rows
1273            vec![Some(false), Some(false), Some(false)],
1274            expr,
1275            &schema
1276        );
1277
1278        // NULL IN (1, 6)
1279        let expr = lit(ScalarValue::Int32(None));
1280        in_list!(
1281            batch,
1282            list.clone(),
1283            &false,
1284            // should have three outputs, as the input batch has three rows
1285            vec![None, None, None],
1286            expr,
1287            &schema
1288        );
1289
1290        Ok(())
1291    }
1292
1293    #[test]
1294    fn in_list_nested_dictionary_scalar() -> Result<()> {
1295        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
1296        let batch = RecordBatch::try_new(
1297            Arc::new(schema.clone()),
1298            vec![Arc::new(Int32Array::from(vec![0, 0, 0]))],
1299        )?;
1300        for (value, list) in [
1301            (ScalarValue::Int32(Some(2)), vec![lit(1_i32), lit(2_i32)]),
1302            (
1303                ScalarValue::Float64(Some(-0.0)),
1304                vec![lit(0.0_f64), lit(1.0_f64)],
1305            ),
1306        ] {
1307            let needle = lit(ScalarValue::Dictionary(
1308                Box::new(DataType::Int16),
1309                Box::new(ScalarValue::Dictionary(
1310                    Box::new(DataType::Int8),
1311                    Box::new(value),
1312                )),
1313            ));
1314
1315            let expr = in_list(needle, list, &false, &schema)?;
1316            let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
1317            assert_eq!(
1318                as_boolean_array(&result),
1319                &BooleanArray::from(vec![true, true, true])
1320            );
1321        }
1322
1323        Ok(())
1324    }
1325
1326    #[test]
1327    fn in_list_utf8_with_dict_types() -> Result<()> {
1328        fn dict_lit(key_type: DataType, value: &str) -> Arc<dyn PhysicalExpr> {
1329            lit(ScalarValue::Dictionary(
1330                Box::new(key_type),
1331                Box::new(ScalarValue::new_utf8(value.to_string())),
1332            ))
1333        }
1334
1335        fn null_dict_lit(key_type: DataType) -> Arc<dyn PhysicalExpr> {
1336            lit(ScalarValue::Dictionary(
1337                Box::new(key_type),
1338                Box::new(ScalarValue::Utf8(None)),
1339            ))
1340        }
1341
1342        let schema = Schema::new(vec![Field::new(
1343            "a",
1344            DataType::Dictionary(Box::new(DataType::UInt16), Box::new(DataType::Utf8)),
1345            true,
1346        )]);
1347        let a: UInt16DictionaryArray =
1348            vec![Some("a"), Some("d"), None].into_iter().collect();
1349        let col_a = col("a", &schema)?;
1350        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
1351
1352        // expression: "a in ("a", "b")"
1353        let lists = [
1354            vec![lit("a"), lit("b")],
1355            vec![
1356                dict_lit(DataType::Int8, "a"),
1357                dict_lit(DataType::UInt16, "b"),
1358            ],
1359        ];
1360        for list in lists.iter() {
1361            in_list_raw!(
1362                batch,
1363                list.clone(),
1364                &false,
1365                vec![Some(true), Some(false), None],
1366                Arc::clone(&col_a),
1367                &schema
1368            );
1369        }
1370
1371        // expression: "a not in ("a", "b")"
1372        for list in lists.iter() {
1373            in_list_raw!(
1374                batch,
1375                list.clone(),
1376                &true,
1377                vec![Some(false), Some(true), None],
1378                Arc::clone(&col_a),
1379                &schema
1380            );
1381        }
1382
1383        // expression: "a in ("a", "b", null)"
1384        let lists = [
1385            vec![lit("a"), lit("b"), lit(ScalarValue::Utf8(None))],
1386            vec![
1387                dict_lit(DataType::Int8, "a"),
1388                dict_lit(DataType::UInt16, "b"),
1389                null_dict_lit(DataType::UInt16),
1390            ],
1391        ];
1392        for list in lists.iter() {
1393            in_list_raw!(
1394                batch,
1395                list.clone(),
1396                &false,
1397                vec![Some(true), None, None],
1398                Arc::clone(&col_a),
1399                &schema
1400            );
1401        }
1402
1403        // expression: "a not in ("a", "b", null)"
1404        for list in lists.iter() {
1405            in_list_raw!(
1406                batch,
1407                list.clone(),
1408                &true,
1409                vec![Some(false), None, None],
1410                Arc::clone(&col_a),
1411                &schema
1412            );
1413        }
1414
1415        Ok(())
1416    }
1417
1418    #[test]
1419    fn test_fmt_sql_1() -> Result<()> {
1420        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
1421        let col_a = col("a", &schema)?;
1422
1423        // Test: a IN ('a', 'b')
1424        let list = vec![lit("a"), lit("b")];
1425        let expr = in_list(Arc::clone(&col_a), list, &false, &schema)?;
1426        let sql_string = fmt_sql(expr.as_ref()).to_string();
1427        let display_string = expr.to_string();
1428        assert_snapshot!(sql_string, @"a IN (a, b)");
1429        assert_snapshot!(display_string, @"a@0 IN (SET) ([a, b])");
1430        Ok(())
1431    }
1432
1433    #[test]
1434    fn test_fmt_sql_2() -> Result<()> {
1435        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
1436        let col_a = col("a", &schema)?;
1437
1438        // Test: a NOT IN ('a', 'b')
1439        let list = vec![lit("a"), lit("b")];
1440        let expr = in_list(Arc::clone(&col_a), list, &true, &schema)?;
1441        let sql_string = fmt_sql(expr.as_ref()).to_string();
1442        let display_string = expr.to_string();
1443
1444        assert_snapshot!(sql_string, @"a NOT IN (a, b)");
1445        assert_snapshot!(display_string, @"a@0 NOT IN (SET) ([a, b])");
1446        Ok(())
1447    }
1448
1449    #[test]
1450    fn test_fmt_sql_3() -> Result<()> {
1451        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
1452        let col_a = col("a", &schema)?;
1453        // Test: a IN ('a', 'b', NULL)
1454        let list = vec![lit("a"), lit("b"), lit(ScalarValue::Utf8(None))];
1455        let expr = in_list(Arc::clone(&col_a), list, &false, &schema)?;
1456        let sql_string = fmt_sql(expr.as_ref()).to_string();
1457        let display_string = expr.to_string();
1458
1459        assert_snapshot!(sql_string, @"a IN (a, b, NULL)");
1460        assert_snapshot!(display_string, @"a@0 IN (SET) ([a, b, NULL])");
1461        Ok(())
1462    }
1463
1464    #[test]
1465    fn test_fmt_sql_4() -> Result<()> {
1466        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
1467        let col_a = col("a", &schema)?;
1468        // Test: a NOT IN ('a', 'b', NULL)
1469        let list = vec![lit("a"), lit("b"), lit(ScalarValue::Utf8(None))];
1470        let expr = in_list(Arc::clone(&col_a), list, &true, &schema)?;
1471        let sql_string = fmt_sql(expr.as_ref()).to_string();
1472        let display_string = expr.to_string();
1473        assert_snapshot!(sql_string, @"a NOT IN (a, b, NULL)");
1474        assert_snapshot!(display_string, @"a@0 NOT IN (SET) ([a, b, NULL])");
1475        Ok(())
1476    }
1477
1478    #[test]
1479    fn in_list_struct() -> Result<()> {
1480        // Create schema with a struct column
1481        let struct_fields = Fields::from(vec![
1482            Field::new("x", DataType::Int32, false),
1483            Field::new("y", DataType::Utf8, false),
1484        ]);
1485        let schema = Schema::new(vec![Field::new(
1486            "a",
1487            DataType::Struct(struct_fields.clone()),
1488            true,
1489        )]);
1490
1491        // Create test data: array of structs
1492        let x_array = Arc::new(Int32Array::from(vec![1, 2, 3]));
1493        let y_array = Arc::new(StringArray::from(vec!["a", "b", "c"]));
1494        let struct_array =
1495            StructArray::new(struct_fields.clone(), vec![x_array, y_array], None);
1496
1497        let col_a = col("a", &schema)?;
1498        let batch =
1499            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(struct_array)])?;
1500
1501        // Create literal structs for the IN list
1502        // Struct {x: 1, y: "a"}
1503        let struct1 = ScalarValue::Struct(Arc::new(StructArray::new(
1504            struct_fields.clone(),
1505            vec![
1506                Arc::new(Int32Array::from(vec![1])),
1507                Arc::new(StringArray::from(vec!["a"])),
1508            ],
1509            None,
1510        )));
1511
1512        // Struct {x: 3, y: "c"}
1513        let struct3 = ScalarValue::Struct(Arc::new(StructArray::new(
1514            struct_fields.clone(),
1515            vec![
1516                Arc::new(Int32Array::from(vec![3])),
1517                Arc::new(StringArray::from(vec!["c"])),
1518            ],
1519            None,
1520        )));
1521
1522        // Test: a IN ({1, "a"}, {3, "c"})
1523        let list = vec![lit(struct1.clone()), lit(struct3.clone())];
1524        in_list_raw!(
1525            batch,
1526            list.clone(),
1527            &false,
1528            vec![Some(true), Some(false), Some(true)],
1529            Arc::clone(&col_a),
1530            &schema
1531        );
1532
1533        // Test: a NOT IN ({1, "a"}, {3, "c"})
1534        in_list_raw!(
1535            batch,
1536            list,
1537            &true,
1538            vec![Some(false), Some(true), Some(false)],
1539            Arc::clone(&col_a),
1540            &schema
1541        );
1542
1543        Ok(())
1544    }
1545
1546    #[test]
1547    fn in_list_struct_with_nulls() -> Result<()> {
1548        // Create schema with a struct column
1549        let struct_fields = Fields::from(vec![
1550            Field::new("x", DataType::Int32, false),
1551            Field::new("y", DataType::Utf8, false),
1552        ]);
1553        let schema = Schema::new(vec![Field::new(
1554            "a",
1555            DataType::Struct(struct_fields.clone()),
1556            true,
1557        )]);
1558
1559        // Create test data with a null struct
1560        let x_array = Arc::new(Int32Array::from(vec![1, 2]));
1561        let y_array = Arc::new(StringArray::from(vec!["a", "b"]));
1562        let struct_array = StructArray::new(
1563            struct_fields.clone(),
1564            vec![x_array, y_array],
1565            Some(NullBuffer::from(vec![true, false])),
1566        );
1567
1568        let col_a = col("a", &schema)?;
1569        let batch =
1570            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(struct_array)])?;
1571
1572        // Create literal struct for the IN list
1573        let struct1 = ScalarValue::Struct(Arc::new(StructArray::new(
1574            struct_fields.clone(),
1575            vec![
1576                Arc::new(Int32Array::from(vec![1])),
1577                Arc::new(StringArray::from(vec!["a"])),
1578            ],
1579            None,
1580        )));
1581
1582        // Test: a IN ({1, "a"})
1583        let list = vec![lit(struct1.clone())];
1584        in_list_raw!(
1585            batch,
1586            list.clone(),
1587            &false,
1588            vec![Some(true), None],
1589            Arc::clone(&col_a),
1590            &schema
1591        );
1592
1593        // Test: a NOT IN ({1, "a"})
1594        in_list_raw!(
1595            batch,
1596            list,
1597            &true,
1598            vec![Some(false), None],
1599            Arc::clone(&col_a),
1600            &schema
1601        );
1602
1603        Ok(())
1604    }
1605
1606    #[test]
1607    fn in_list_struct_with_null_in_list() -> Result<()> {
1608        // Create schema with a struct column
1609        let struct_fields = Fields::from(vec![
1610            Field::new("x", DataType::Int32, false),
1611            Field::new("y", DataType::Utf8, false),
1612        ]);
1613        let schema = Schema::new(vec![Field::new(
1614            "a",
1615            DataType::Struct(struct_fields.clone()),
1616            true,
1617        )]);
1618
1619        // Create test data
1620        let x_array = Arc::new(Int32Array::from(vec![1, 2, 3]));
1621        let y_array = Arc::new(StringArray::from(vec!["a", "b", "c"]));
1622        let struct_array =
1623            StructArray::new(struct_fields.clone(), vec![x_array, y_array], None);
1624
1625        let col_a = col("a", &schema)?;
1626        let batch =
1627            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(struct_array)])?;
1628
1629        // Create literal structs including a NULL
1630        let struct1 = ScalarValue::Struct(Arc::new(StructArray::new(
1631            struct_fields.clone(),
1632            vec![
1633                Arc::new(Int32Array::from(vec![1])),
1634                Arc::new(StringArray::from(vec!["a"])),
1635            ],
1636            None,
1637        )));
1638
1639        let null_struct = ScalarValue::Struct(Arc::new(StructArray::new_null(
1640            struct_fields.clone(),
1641            1,
1642        )));
1643
1644        // Test: a IN ({1, "a"}, NULL)
1645        let list = vec![lit(struct1), lit(null_struct.clone())];
1646        in_list_raw!(
1647            batch,
1648            list.clone(),
1649            &false,
1650            vec![Some(true), None, None],
1651            Arc::clone(&col_a),
1652            &schema
1653        );
1654
1655        // Test: a NOT IN ({1, "a"}, NULL)
1656        in_list_raw!(
1657            batch,
1658            list,
1659            &true,
1660            vec![Some(false), None, None],
1661            Arc::clone(&col_a),
1662            &schema
1663        );
1664
1665        Ok(())
1666    }
1667
1668    #[test]
1669    fn in_list_nested_struct() -> Result<()> {
1670        // Create nested struct schema
1671        let inner_struct_fields = Fields::from(vec![
1672            Field::new("a", DataType::Int32, false),
1673            Field::new("b", DataType::Utf8, false),
1674        ]);
1675        let outer_struct_fields = Fields::from(vec![
1676            Field::new(
1677                "inner",
1678                DataType::Struct(inner_struct_fields.clone()),
1679                false,
1680            ),
1681            Field::new("c", DataType::Int32, false),
1682        ]);
1683        let schema = Schema::new(vec![Field::new(
1684            "x",
1685            DataType::Struct(outer_struct_fields.clone()),
1686            true,
1687        )]);
1688
1689        // Create test data with nested structs
1690        let inner1 = Arc::new(StructArray::new(
1691            inner_struct_fields.clone(),
1692            vec![
1693                Arc::new(Int32Array::from(vec![1, 2])),
1694                Arc::new(StringArray::from(vec!["x", "y"])),
1695            ],
1696            None,
1697        ));
1698        let c_array = Arc::new(Int32Array::from(vec![10, 20]));
1699        let outer_array =
1700            StructArray::new(outer_struct_fields.clone(), vec![inner1, c_array], None);
1701
1702        let col_x = col("x", &schema)?;
1703        let batch =
1704            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(outer_array)])?;
1705
1706        // Create a nested struct literal matching the first row
1707        let inner_match = Arc::new(StructArray::new(
1708            inner_struct_fields.clone(),
1709            vec![
1710                Arc::new(Int32Array::from(vec![1])),
1711                Arc::new(StringArray::from(vec!["x"])),
1712            ],
1713            None,
1714        ));
1715        let outer_match = ScalarValue::Struct(Arc::new(StructArray::new(
1716            outer_struct_fields.clone(),
1717            vec![inner_match, Arc::new(Int32Array::from(vec![10]))],
1718            None,
1719        )));
1720
1721        // Test: x IN ({{1, "x"}, 10})
1722        let list = vec![lit(outer_match)];
1723        in_list_raw!(
1724            batch,
1725            list.clone(),
1726            &false,
1727            vec![Some(true), Some(false)],
1728            Arc::clone(&col_x),
1729            &schema
1730        );
1731
1732        // Test: x NOT IN ({{1, "x"}, 10})
1733        in_list_raw!(
1734            batch,
1735            list,
1736            &true,
1737            vec![Some(false), Some(true)],
1738            Arc::clone(&col_x),
1739            &schema
1740        );
1741
1742        Ok(())
1743    }
1744
1745    #[test]
1746    fn in_list_struct_with_exprs_not_array() -> Result<()> {
1747        // Test InList using expressions (not the array constructor) with structs
1748        // By using InListExpr::new directly, we bypass the array optimization
1749        // and use the Exprs variant, testing the expression evaluation path
1750
1751        // Create schema with a struct column {x: Int32, y: Utf8}
1752        let struct_fields = Fields::from(vec![
1753            Field::new("x", DataType::Int32, false),
1754            Field::new("y", DataType::Utf8, false),
1755        ]);
1756        let schema = Schema::new(vec![Field::new(
1757            "a",
1758            DataType::Struct(struct_fields.clone()),
1759            true,
1760        )]);
1761
1762        // Create test data: array of structs [{1, "a"}, {2, "b"}, {3, "c"}]
1763        let x_array = Arc::new(Int32Array::from(vec![1, 2, 3]));
1764        let y_array = Arc::new(StringArray::from(vec!["a", "b", "c"]));
1765        let struct_array =
1766            StructArray::new(struct_fields.clone(), vec![x_array, y_array], None);
1767
1768        let col_a = col("a", &schema)?;
1769        let batch =
1770            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(struct_array)])?;
1771
1772        // Create struct literals with the SAME shape (so types are compatible)
1773        // Struct {x: 1, y: "a"}
1774        let struct1 = ScalarValue::Struct(Arc::new(StructArray::new(
1775            struct_fields.clone(),
1776            vec![
1777                Arc::new(Int32Array::from(vec![1])),
1778                Arc::new(StringArray::from(vec!["a"])),
1779            ],
1780            None,
1781        )));
1782
1783        // Struct {x: 3, y: "c"}
1784        let struct3 = ScalarValue::Struct(Arc::new(StructArray::new(
1785            struct_fields.clone(),
1786            vec![
1787                Arc::new(Int32Array::from(vec![3])),
1788                Arc::new(StringArray::from(vec!["c"])),
1789            ],
1790            None,
1791        )));
1792
1793        // Create list of struct expressions
1794        let list = vec![lit(struct1), lit(struct3)];
1795
1796        // Use InListExpr::new directly (not in_list()) to bypass array optimization
1797        // This creates an InList without a static filter
1798        let expr = Arc::new(InListExpr::new(Arc::clone(&col_a), list, false, None));
1799
1800        // Verify that the expression doesn't have a static filter
1801        // by checking the display string does NOT contain "(SET)"
1802        let display_string = expr.to_string();
1803        assert!(
1804            !display_string.contains("(SET)"),
1805            "Expected display string to NOT contain '(SET)' (should use Exprs variant), but got: {display_string}",
1806        );
1807
1808        // Evaluate the expression
1809        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
1810        let result = as_boolean_array(&result);
1811
1812        // Expected: first row {1, "a"} matches struct1,
1813        //           second row {2, "b"} doesn't match,
1814        //           third row {3, "c"} matches struct3
1815        let expected = BooleanArray::from(vec![Some(true), Some(false), Some(true)]);
1816        assert_eq!(result, &expected);
1817
1818        // Test NOT IN as well
1819        let expr_not = Arc::new(InListExpr::new(
1820            Arc::clone(&col_a),
1821            vec![
1822                lit(ScalarValue::Struct(Arc::new(StructArray::new(
1823                    struct_fields.clone(),
1824                    vec![
1825                        Arc::new(Int32Array::from(vec![1])),
1826                        Arc::new(StringArray::from(vec!["a"])),
1827                    ],
1828                    None,
1829                )))),
1830                lit(ScalarValue::Struct(Arc::new(StructArray::new(
1831                    struct_fields.clone(),
1832                    vec![
1833                        Arc::new(Int32Array::from(vec![3])),
1834                        Arc::new(StringArray::from(vec!["c"])),
1835                    ],
1836                    None,
1837                )))),
1838            ],
1839            true,
1840            None,
1841        ));
1842
1843        let result_not = expr_not.evaluate(&batch)?.into_array(batch.num_rows())?;
1844        let result_not = as_boolean_array(&result_not);
1845
1846        let expected_not = BooleanArray::from(vec![Some(false), Some(true), Some(false)]);
1847        assert_eq!(result_not, &expected_not);
1848
1849        Ok(())
1850    }
1851
1852    #[test]
1853    fn test_in_list_null_handling_comprehensive() -> Result<()> {
1854        // Comprehensive test demonstrating SQL three-valued logic for IN expressions
1855        // This test explicitly shows all possible outcomes: true, false, and null
1856        let schema = Schema::new(vec![Field::new("a", DataType::Int64, true)]);
1857
1858        // Test data: [1, 2, 3, null]
1859        // - 1 will match in both lists
1860        // - 2 will not match in either list
1861        // - 3 will not match in either list
1862        // - null is always null
1863        let a = Int64Array::from(vec![Some(1), Some(2), Some(3), None]);
1864        let col_a = col("a", &schema)?;
1865        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
1866
1867        // Case 1: List WITHOUT null - demonstrates true/false/null outcomes
1868        // "a IN (1, 4)" - 1 matches, 2 and 3 don't match, null is null
1869        let list = vec![lit(1i64), lit(4i64)];
1870        in_list!(
1871            batch,
1872            list,
1873            &false,
1874            vec![
1875                Some(true),  // 1 is in the list → true
1876                Some(false), // 2 is not in the list → false
1877                Some(false), // 3 is not in the list → false
1878                None,        // null IN (...) → null (SQL three-valued logic)
1879            ],
1880            Arc::clone(&col_a),
1881            &schema
1882        );
1883
1884        // Case 2: List WITH null - demonstrates null propagation for non-matches
1885        // "a IN (1, NULL)" - 1 matches (true), 2/3 don't match but list has null (null), null is null
1886        let list = vec![lit(1i64), lit(ScalarValue::Int64(None))];
1887        in_list!(
1888            batch,
1889            list,
1890            &false,
1891            vec![
1892                Some(true), // 1 is in the list → true (found match)
1893                None, // 2 is not in list, but list has NULL → null (might match NULL)
1894                None, // 3 is not in list, but list has NULL → null (might match NULL)
1895                None, // null IN (...) → null (SQL three-valued logic)
1896            ],
1897            Arc::clone(&col_a),
1898            &schema
1899        );
1900
1901        Ok(())
1902    }
1903
1904    #[test]
1905    fn test_in_list_with_only_nulls() -> Result<()> {
1906        // Edge case: IN list contains ONLY null values
1907        let schema = Schema::new(vec![Field::new("a", DataType::Int64, true)]);
1908        let a = Int64Array::from(vec![Some(1), Some(2), None]);
1909        let col_a = col("a", &schema)?;
1910        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
1911
1912        // "a IN (NULL, NULL)" - list has only nulls
1913        let list = vec![lit(ScalarValue::Int64(None)), lit(ScalarValue::Int64(None))];
1914
1915        // All results should be NULL because:
1916        // - Non-null values (1, 2) can't match anything concrete, but list might contain matching value
1917        // - NULL value is always NULL in IN expressions
1918        in_list!(
1919            batch,
1920            list.clone(),
1921            &false,
1922            vec![None, None, None],
1923            Arc::clone(&col_a),
1924            &schema
1925        );
1926
1927        // "a NOT IN (NULL, NULL)" - list has only nulls
1928        // All results should still be NULL due to three-valued logic
1929        in_list!(
1930            batch,
1931            list,
1932            &true,
1933            vec![None, None, None],
1934            Arc::clone(&col_a),
1935            &schema
1936        );
1937
1938        Ok(())
1939    }
1940
1941    #[test]
1942    fn test_in_list_multiple_nulls_deduplication() -> Result<()> {
1943        // Test that multiple NULLs in the list are handled correctly
1944        // This verifies deduplication doesn't break null handling
1945        let schema = Schema::new(vec![Field::new("a", DataType::Int64, true)]);
1946        let col_a = col("a", &schema)?;
1947
1948        // Create array with multiple nulls: [1, 2, NULL, NULL, 3, NULL]
1949        let array = Arc::new(Int64Array::from(vec![
1950            Some(1),
1951            Some(2),
1952            None,
1953            None,
1954            Some(3),
1955            None,
1956        ])) as ArrayRef;
1957
1958        // Create InListExpr from array
1959        let expr = Arc::new(InListExpr::try_new_from_array(
1960            Arc::clone(&col_a),
1961            array,
1962            false,
1963            &schema,
1964        )?) as Arc<dyn PhysicalExpr>;
1965
1966        // Create test data: [1, 2, 3, 4, null]
1967        let a = Int64Array::from(vec![Some(1), Some(2), Some(3), Some(4), None]);
1968        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
1969
1970        // Evaluate the expression
1971        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
1972        let result = as_boolean_array(&result);
1973
1974        // Expected behavior with multiple NULLs in list:
1975        // - Values in the list (1,2,3) → true
1976        // - Values not in the list (4) → NULL (because list contains NULL)
1977        // - NULL input → NULL
1978        let expected = BooleanArray::from(vec![
1979            Some(true), // 1 is in list
1980            Some(true), // 2 is in list
1981            Some(true), // 3 is in list
1982            None,       // 4 not in list, but list has NULLs
1983            None,       // NULL input
1984        ]);
1985        assert_eq!(result, &expected);
1986
1987        Ok(())
1988    }
1989
1990    #[test]
1991    fn test_not_in_null_handling_comprehensive() -> Result<()> {
1992        // Comprehensive test demonstrating SQL three-valued logic for NOT IN expressions
1993        // This test explicitly shows all possible outcomes for NOT IN: true, false, and null
1994        let schema = Schema::new(vec![Field::new("a", DataType::Int64, true)]);
1995
1996        // Test data: [1, 2, 3, null]
1997        let a = Int64Array::from(vec![Some(1), Some(2), Some(3), None]);
1998        let col_a = col("a", &schema)?;
1999        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
2000
2001        // Case 1: List WITHOUT null - demonstrates true/false/null outcomes for NOT IN
2002        // "a NOT IN (1, 4)" - 1 matches (false), 2 and 3 don't match (true), null is null
2003        let list = vec![lit(1i64), lit(4i64)];
2004        in_list!(
2005            batch,
2006            list,
2007            &true,
2008            vec![
2009                Some(false), // 1 is in the list → NOT IN returns false
2010                Some(true),  // 2 is not in the list → NOT IN returns true
2011                Some(true),  // 3 is not in the list → NOT IN returns true
2012                None,        // null NOT IN (...) → null (SQL three-valued logic)
2013            ],
2014            Arc::clone(&col_a),
2015            &schema
2016        );
2017
2018        // Case 2: List WITH null - demonstrates null propagation for NOT IN
2019        // "a NOT IN (1, NULL)" - 1 matches (false), 2/3 don't match but list has null (null), null is null
2020        let list = vec![lit(1i64), lit(ScalarValue::Int64(None))];
2021        in_list!(
2022            batch,
2023            list,
2024            &true,
2025            vec![
2026                Some(false), // 1 is in the list → NOT IN returns false
2027                None, // 2 is not in known values, but list has NULL → null (can't prove it's not in list)
2028                None, // 3 is not in known values, but list has NULL → null (can't prove it's not in list)
2029                None, // null NOT IN (...) → null (SQL three-valued logic)
2030            ],
2031            Arc::clone(&col_a),
2032            &schema
2033        );
2034
2035        Ok(())
2036    }
2037
2038    #[test]
2039    fn test_in_list_null_type_column() -> Result<()> {
2040        // Test with a column that has DataType::Null (not just nullable values)
2041        // All values in a NullArray are null by definition
2042        let schema = Schema::new(vec![Field::new("a", DataType::Null, true)]);
2043        let a = NullArray::new(3);
2044        let col_a = col("a", &schema)?;
2045        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
2046
2047        // "null_column IN (1, 2)" - comparing Null type against Int64 list
2048        // Note: This tests type coercion behavior between Null and Int64
2049        let list = vec![lit(1i64), lit(2i64)];
2050
2051        // All results should be NULL because:
2052        // - Every value in the column is null (DataType::Null)
2053        // - null IN (anything) always returns null per SQL three-valued logic
2054        in_list!(
2055            batch,
2056            list.clone(),
2057            &false,
2058            vec![None, None, None],
2059            Arc::clone(&col_a),
2060            &schema
2061        );
2062
2063        // "null_column NOT IN (1, 2)"
2064        // Same behavior for NOT IN - null NOT IN (anything) is still null
2065        in_list!(
2066            batch,
2067            list,
2068            &true,
2069            vec![None, None, None],
2070            Arc::clone(&col_a),
2071            &schema
2072        );
2073
2074        Ok(())
2075    }
2076
2077    #[test]
2078    fn test_in_list_null_type_list() -> Result<()> {
2079        // Test with a list that has DataType::Null
2080        let schema = Schema::new(vec![Field::new("a", DataType::Int64, true)]);
2081        let a = Int64Array::from(vec![Some(1), Some(2), None]);
2082        let col_a = col("a", &schema)?;
2083
2084        // Create a NullArray as the list
2085        let null_array = Arc::new(NullArray::new(2)) as ArrayRef;
2086
2087        // Try to create InListExpr with a NullArray list
2088        // This tests whether try_new_from_array can handle Null type arrays
2089        let expr = Arc::new(InListExpr::try_new_from_array(
2090            Arc::clone(&col_a),
2091            null_array,
2092            false,
2093            &schema,
2094        )?) as Arc<dyn PhysicalExpr>;
2095        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
2096        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
2097        let result = as_boolean_array(&result);
2098
2099        // If it succeeds, all results should be NULL
2100        // because the list contains only null type values
2101        let expected = BooleanArray::from(vec![None, None, None]);
2102        assert_eq!(result, &expected);
2103
2104        Ok(())
2105    }
2106
2107    #[test]
2108    fn test_in_list_null_type_both() -> Result<()> {
2109        // Test when both column and list are DataType::Null
2110        let schema = Schema::new(vec![Field::new("a", DataType::Null, true)]);
2111        let a = NullArray::new(3);
2112        let col_a = col("a", &schema)?;
2113
2114        // Create a NullArray as the list
2115        let null_array = Arc::new(NullArray::new(2)) as ArrayRef;
2116
2117        // Try to create InListExpr with both Null types
2118        let expr = Arc::new(InListExpr::try_new_from_array(
2119            Arc::clone(&col_a),
2120            null_array,
2121            false,
2122            &schema,
2123        )?) as Arc<dyn PhysicalExpr>;
2124
2125        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
2126        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
2127        let result = as_boolean_array(&result);
2128
2129        // If successful, all results should be NULL
2130        // null IN [null, null] -> null
2131        let expected = BooleanArray::from(vec![None, None, None]);
2132        assert_eq!(result, &expected);
2133
2134        Ok(())
2135    }
2136
2137    #[test]
2138    fn test_in_list_comprehensive_null_handling() -> Result<()> {
2139        // Comprehensive test for IN LIST operations with various NULL handling scenarios.
2140        // This test covers the key cases validated against DuckDB as the source of truth.
2141        //
2142        // Note: Some scalar literal tests (like NULL IN (1, 2)) are omitted as they
2143        // appear to expose an issue with static filter optimization. These are covered
2144        // by existing tests like in_list_no_cols().
2145
2146        let schema = Arc::new(Schema::new(vec![Field::new("b", DataType::Int32, true)]));
2147        let col_b = col("b", &schema)?;
2148        let null_i32 = ScalarValue::Int32(None);
2149
2150        // Helper to create a batch
2151        let make_batch = |values: Vec<Option<i32>>| -> Result<RecordBatch> {
2152            let array = Arc::new(Int32Array::from(values));
2153            Ok(RecordBatch::try_new(Arc::clone(&schema), vec![array])?)
2154        };
2155
2156        // Helper to run a test
2157        let run_test = |batch: &RecordBatch,
2158                        expr: Arc<dyn PhysicalExpr>,
2159                        list: Vec<Arc<dyn PhysicalExpr>>,
2160                        expected: Vec<Option<bool>>|
2161         -> Result<()> {
2162            let in_expr = in_list(expr, list, &false, schema.as_ref())?;
2163            let result = in_expr.evaluate(batch)?.into_array(batch.num_rows())?;
2164            let result = as_boolean_array(&result);
2165            assert_eq!(result, &BooleanArray::from(expected));
2166            Ok(())
2167        };
2168
2169        // ========================================================================
2170        // COLUMN TESTS - col(b) IN [1, 2]
2171        // ========================================================================
2172
2173        // [1] IN (1, 2) => [TRUE]
2174        let batch = make_batch(vec![Some(1)])?;
2175        run_test(
2176            &batch,
2177            Arc::clone(&col_b),
2178            vec![lit(1i32), lit(2i32)],
2179            vec![Some(true)],
2180        )?;
2181
2182        // [1, 2] IN (1, 2) => [TRUE, TRUE]
2183        let batch = make_batch(vec![Some(1), Some(2)])?;
2184        run_test(
2185            &batch,
2186            Arc::clone(&col_b),
2187            vec![lit(1i32), lit(2i32)],
2188            vec![Some(true), Some(true)],
2189        )?;
2190
2191        // [3, 4] IN (1, 2) => [FALSE, FALSE]
2192        let batch = make_batch(vec![Some(3), Some(4)])?;
2193        run_test(
2194            &batch,
2195            Arc::clone(&col_b),
2196            vec![lit(1i32), lit(2i32)],
2197            vec![Some(false), Some(false)],
2198        )?;
2199
2200        // [1, NULL] IN (1, 2) => [TRUE, NULL]
2201        let batch = make_batch(vec![Some(1), None])?;
2202        run_test(
2203            &batch,
2204            Arc::clone(&col_b),
2205            vec![lit(1i32), lit(2i32)],
2206            vec![Some(true), None],
2207        )?;
2208
2209        // [3, NULL] IN (1, 2) => [FALSE, NULL] (no match, NULL is NULL)
2210        let batch = make_batch(vec![Some(3), None])?;
2211        run_test(
2212            &batch,
2213            Arc::clone(&col_b),
2214            vec![lit(1i32), lit(2i32)],
2215            vec![Some(false), None],
2216        )?;
2217
2218        // ========================================================================
2219        // COLUMN WITH NULL IN LIST - col(b) IN [NULL, 1]
2220        // ========================================================================
2221
2222        // [1] IN (NULL, 1) => [TRUE] (found match)
2223        let batch = make_batch(vec![Some(1)])?;
2224        run_test(
2225            &batch,
2226            Arc::clone(&col_b),
2227            vec![lit(null_i32.clone()), lit(1i32)],
2228            vec![Some(true)],
2229        )?;
2230
2231        // [2] IN (NULL, 1) => [NULL] (no match, but list has NULL)
2232        let batch = make_batch(vec![Some(2)])?;
2233        run_test(
2234            &batch,
2235            Arc::clone(&col_b),
2236            vec![lit(null_i32.clone()), lit(1i32)],
2237            vec![None],
2238        )?;
2239
2240        // [NULL] IN (NULL, 1) => [NULL]
2241        let batch = make_batch(vec![None])?;
2242        run_test(
2243            &batch,
2244            Arc::clone(&col_b),
2245            vec![lit(null_i32.clone()), lit(1i32)],
2246            vec![None],
2247        )?;
2248
2249        // ========================================================================
2250        // COLUMN WITH ALL NULLS IN LIST - col(b) IN [NULL, NULL]
2251        // ========================================================================
2252
2253        // [1] IN (NULL, NULL) => [NULL]
2254        let batch = make_batch(vec![Some(1)])?;
2255        run_test(
2256            &batch,
2257            Arc::clone(&col_b),
2258            vec![lit(null_i32.clone()), lit(null_i32.clone())],
2259            vec![None],
2260        )?;
2261
2262        // [NULL] IN (NULL, NULL) => [NULL]
2263        let batch = make_batch(vec![None])?;
2264        run_test(
2265            &batch,
2266            Arc::clone(&col_b),
2267            vec![lit(null_i32.clone()), lit(null_i32.clone())],
2268            vec![None],
2269        )?;
2270
2271        // ========================================================================
2272        // LITERAL IN LIST WITH COLUMN - lit(1) IN [2, col(b)]
2273        // ========================================================================
2274
2275        // 1 IN (2, [1]) => [TRUE] (matches column value)
2276        let batch = make_batch(vec![Some(1)])?;
2277        run_test(
2278            &batch,
2279            lit(1i32),
2280            vec![lit(2i32), Arc::clone(&col_b)],
2281            vec![Some(true)],
2282        )?;
2283
2284        // 1 IN (2, [3]) => [FALSE] (no match)
2285        let batch = make_batch(vec![Some(3)])?;
2286        run_test(
2287            &batch,
2288            lit(1i32),
2289            vec![lit(2i32), Arc::clone(&col_b)],
2290            vec![Some(false)],
2291        )?;
2292
2293        // 1 IN (2, [NULL]) => [NULL] (no match, column is NULL)
2294        let batch = make_batch(vec![None])?;
2295        run_test(
2296            &batch,
2297            lit(1i32),
2298            vec![lit(2i32), Arc::clone(&col_b)],
2299            vec![None],
2300        )?;
2301
2302        // ========================================================================
2303        // COLUMN IN LIST CONTAINING ITSELF - col(b) IN [1, col(b)]
2304        // ========================================================================
2305
2306        // [1] IN (1, [1]) => [TRUE] (always matches - either list literal or itself)
2307        let batch = make_batch(vec![Some(1)])?;
2308        run_test(
2309            &batch,
2310            Arc::clone(&col_b),
2311            vec![lit(1i32), Arc::clone(&col_b)],
2312            vec![Some(true)],
2313        )?;
2314
2315        // [2] IN (1, [2]) => [TRUE] (matches itself)
2316        let batch = make_batch(vec![Some(2)])?;
2317        run_test(
2318            &batch,
2319            Arc::clone(&col_b),
2320            vec![lit(1i32), Arc::clone(&col_b)],
2321            vec![Some(true)],
2322        )?;
2323
2324        // [NULL] IN (1, [NULL]) => [NULL] (NULL is never equal to anything)
2325        let batch = make_batch(vec![None])?;
2326        run_test(
2327            &batch,
2328            Arc::clone(&col_b),
2329            vec![lit(1i32), Arc::clone(&col_b)],
2330            vec![None],
2331        )?;
2332
2333        Ok(())
2334    }
2335
2336    #[test]
2337    fn test_in_list_scalar_literal_cases() -> Result<()> {
2338        // Test scalar literal cases (both NULL and non-NULL) to ensure SQL three-valued
2339        // logic is correctly implemented. This covers the important case where a scalar
2340        // value is tested against a list containing NULL.
2341
2342        let schema = Arc::new(Schema::new(vec![Field::new("b", DataType::Int32, true)]));
2343        let null_i32 = ScalarValue::Int32(None);
2344
2345        // Helper to create a batch
2346        let make_batch = |values: Vec<Option<i32>>| -> Result<RecordBatch> {
2347            let array = Arc::new(Int32Array::from(values));
2348            Ok(RecordBatch::try_new(Arc::clone(&schema), vec![array])?)
2349        };
2350
2351        // Helper to run a test
2352        let run_test = |batch: &RecordBatch,
2353                        expr: Arc<dyn PhysicalExpr>,
2354                        list: Vec<Arc<dyn PhysicalExpr>>,
2355                        negated: bool,
2356                        expected: Vec<Option<bool>>|
2357         -> Result<()> {
2358            let in_expr = in_list(expr, list, &negated, schema.as_ref())?;
2359            let result = in_expr.evaluate(batch)?.into_array(batch.num_rows())?;
2360            let result = as_boolean_array(&result);
2361            let expected_array = BooleanArray::from(expected);
2362            assert_eq!(
2363                result,
2364                &expected_array,
2365                "Expected {:?}, got {:?}",
2366                expected_array,
2367                result.iter().collect::<Vec<_>>()
2368            );
2369            Ok(())
2370        };
2371
2372        let batch = make_batch(vec![Some(1)])?;
2373
2374        // ========================================================================
2375        // NULL LITERAL TESTS
2376        // According to SQL semantics, NULL IN (any_list) should always return NULL
2377        // ========================================================================
2378
2379        // NULL IN (1, 1) => NULL
2380        run_test(
2381            &batch,
2382            lit(null_i32.clone()),
2383            vec![lit(1i32), lit(1i32)],
2384            false,
2385            vec![None],
2386        )?;
2387
2388        // NULL IN (NULL, 1) => NULL
2389        run_test(
2390            &batch,
2391            lit(null_i32.clone()),
2392            vec![lit(null_i32.clone()), lit(1i32)],
2393            false,
2394            vec![None],
2395        )?;
2396
2397        // NULL IN (NULL, NULL) => NULL
2398        run_test(
2399            &batch,
2400            lit(null_i32.clone()),
2401            vec![lit(null_i32.clone()), lit(null_i32.clone())],
2402            false,
2403            vec![None],
2404        )?;
2405
2406        // ========================================================================
2407        // NON-NULL SCALAR LITERALS WITH NULL IN LIST - Int32
2408        // When a scalar value is NOT in a list containing NULL, the result is NULL
2409        // When a scalar value IS in the list, the result is TRUE (NULL doesn't matter)
2410        // ========================================================================
2411
2412        // 3 IN (0, 1, 2, NULL) => NULL (not in list, but list has NULL)
2413        run_test(
2414            &batch,
2415            lit(3i32),
2416            vec![lit(0i32), lit(1i32), lit(2i32), lit(null_i32.clone())],
2417            false,
2418            vec![None],
2419        )?;
2420
2421        // 3 NOT IN (0, 1, 2, NULL) => NULL (not in list, but list has NULL)
2422        run_test(
2423            &batch,
2424            lit(3i32),
2425            vec![lit(0i32), lit(1i32), lit(2i32), lit(null_i32.clone())],
2426            true,
2427            vec![None],
2428        )?;
2429
2430        // 1 IN (0, 1, 2, NULL) => TRUE (found match, NULL doesn't matter)
2431        run_test(
2432            &batch,
2433            lit(1i32),
2434            vec![lit(0i32), lit(1i32), lit(2i32), lit(null_i32.clone())],
2435            false,
2436            vec![Some(true)],
2437        )?;
2438
2439        // 1 NOT IN (0, 1, 2, NULL) => FALSE (found match, NULL doesn't matter)
2440        run_test(
2441            &batch,
2442            lit(1i32),
2443            vec![lit(0i32), lit(1i32), lit(2i32), lit(null_i32.clone())],
2444            true,
2445            vec![Some(false)],
2446        )?;
2447
2448        // ========================================================================
2449        // NON-NULL SCALAR LITERALS WITH NULL IN LIST - String
2450        // Same semantics as Int32 but with string type
2451        // ========================================================================
2452
2453        let schema_str =
2454            Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, true)]));
2455        let batch_str = RecordBatch::try_new(
2456            Arc::clone(&schema_str),
2457            vec![Arc::new(StringArray::from(vec![Some("dummy")]))],
2458        )?;
2459        let null_str = ScalarValue::Utf8(None);
2460
2461        let run_test_str = |expr: Arc<dyn PhysicalExpr>,
2462                            list: Vec<Arc<dyn PhysicalExpr>>,
2463                            negated: bool,
2464                            expected: Vec<Option<bool>>|
2465         -> Result<()> {
2466            let in_expr = in_list(expr, list, &negated, schema_str.as_ref())?;
2467            let result = in_expr
2468                .evaluate(&batch_str)?
2469                .into_array(batch_str.num_rows())?;
2470            let result = as_boolean_array(&result);
2471            let expected_array = BooleanArray::from(expected);
2472            assert_eq!(
2473                result,
2474                &expected_array,
2475                "Expected {:?}, got {:?}",
2476                expected_array,
2477                result.iter().collect::<Vec<_>>()
2478            );
2479            Ok(())
2480        };
2481
2482        // 'c' IN ('a', 'b', NULL) => NULL (not in list, but list has NULL)
2483        run_test_str(
2484            lit("c"),
2485            vec![lit("a"), lit("b"), lit(null_str.clone())],
2486            false,
2487            vec![None],
2488        )?;
2489
2490        // 'c' NOT IN ('a', 'b', NULL) => NULL (not in list, but list has NULL)
2491        run_test_str(
2492            lit("c"),
2493            vec![lit("a"), lit("b"), lit(null_str.clone())],
2494            true,
2495            vec![None],
2496        )?;
2497
2498        // 'a' IN ('a', 'b', NULL) => TRUE (found match, NULL doesn't matter)
2499        run_test_str(
2500            lit("a"),
2501            vec![lit("a"), lit("b"), lit(null_str.clone())],
2502            false,
2503            vec![Some(true)],
2504        )?;
2505
2506        // 'a' NOT IN ('a', 'b', NULL) => FALSE (found match, NULL doesn't matter)
2507        run_test_str(
2508            lit("a"),
2509            vec![lit("a"), lit("b"), lit(null_str.clone())],
2510            true,
2511            vec![Some(false)],
2512        )?;
2513
2514        Ok(())
2515    }
2516
2517    #[test]
2518    fn test_in_list_tuple_cases() -> Result<()> {
2519        // Test tuple/struct cases from the original request: (lit, lit) IN (lit, lit)
2520        // These test row-wise comparisons like (1, 2) IN ((1, 2), (3, 4))
2521
2522        let schema = Arc::new(Schema::new(vec![Field::new("b", DataType::Int32, true)]));
2523
2524        // Helper to create struct scalars for tuple comparisons
2525        let make_struct = |v1: Option<i32>, v2: Option<i32>| -> ScalarValue {
2526            let fields = Fields::from(vec![
2527                Field::new("field_0", DataType::Int32, true),
2528                Field::new("field_1", DataType::Int32, true),
2529            ]);
2530            ScalarValue::Struct(Arc::new(StructArray::new(
2531                fields,
2532                vec![
2533                    Arc::new(Int32Array::from(vec![v1])),
2534                    Arc::new(Int32Array::from(vec![v2])),
2535                ],
2536                None,
2537            )))
2538        };
2539
2540        // Need a single row batch for scalar tests
2541        let batch = RecordBatch::try_new(
2542            Arc::clone(&schema),
2543            vec![Arc::new(Int32Array::from(vec![Some(1)]))],
2544        )?;
2545
2546        // Helper to run tuple tests
2547        let run_tuple_test = |lhs: ScalarValue,
2548                              list: Vec<ScalarValue>,
2549                              expected: Vec<Option<bool>>|
2550         -> Result<()> {
2551            let expr = in_list(
2552                lit(lhs),
2553                list.into_iter().map(lit).collect(),
2554                &false,
2555                schema.as_ref(),
2556            )?;
2557            let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
2558            let result = as_boolean_array(&result);
2559            assert_eq!(result, &BooleanArray::from(expected));
2560            Ok(())
2561        };
2562
2563        // (NULL, NULL) IN ((1, 2)) => FALSE (tuples don't match)
2564        run_tuple_test(
2565            make_struct(None, None),
2566            vec![make_struct(Some(1), Some(2))],
2567            vec![Some(false)],
2568        )?;
2569
2570        // (NULL, NULL) IN ((NULL, 1)) => FALSE
2571        run_tuple_test(
2572            make_struct(None, None),
2573            vec![make_struct(None, Some(1))],
2574            vec![Some(false)],
2575        )?;
2576
2577        // (NULL, NULL) IN ((NULL, NULL)) => TRUE (exact match including nulls)
2578        run_tuple_test(
2579            make_struct(None, None),
2580            vec![make_struct(None, None)],
2581            vec![Some(true)],
2582        )?;
2583
2584        // (NULL, 1) IN ((1, 2)) => FALSE
2585        run_tuple_test(
2586            make_struct(None, Some(1)),
2587            vec![make_struct(Some(1), Some(2))],
2588            vec![Some(false)],
2589        )?;
2590
2591        // (NULL, 1) IN ((NULL, 1)) => TRUE (exact match)
2592        run_tuple_test(
2593            make_struct(None, Some(1)),
2594            vec![make_struct(None, Some(1))],
2595            vec![Some(true)],
2596        )?;
2597
2598        // (NULL, 1) IN ((NULL, NULL)) => FALSE
2599        run_tuple_test(
2600            make_struct(None, Some(1)),
2601            vec![make_struct(None, None)],
2602            vec![Some(false)],
2603        )?;
2604
2605        // (1, 2) IN ((1, 2)) => TRUE
2606        run_tuple_test(
2607            make_struct(Some(1), Some(2)),
2608            vec![make_struct(Some(1), Some(2))],
2609            vec![Some(true)],
2610        )?;
2611
2612        // (1, 3) IN ((1, 2)) => FALSE
2613        run_tuple_test(
2614            make_struct(Some(1), Some(3)),
2615            vec![make_struct(Some(1), Some(2))],
2616            vec![Some(false)],
2617        )?;
2618
2619        // (4, 4) IN ((1, 2)) => FALSE
2620        run_tuple_test(
2621            make_struct(Some(4), Some(4)),
2622            vec![make_struct(Some(1), Some(2))],
2623            vec![Some(false)],
2624        )?;
2625
2626        // (1, 1) IN ((NULL, 1)) => FALSE
2627        run_tuple_test(
2628            make_struct(Some(1), Some(1)),
2629            vec![make_struct(None, Some(1))],
2630            vec![Some(false)],
2631        )?;
2632
2633        // (1, 1) IN ((NULL, NULL)) => FALSE
2634        run_tuple_test(
2635            make_struct(Some(1), Some(1)),
2636            vec![make_struct(None, None)],
2637            vec![Some(false)],
2638        )?;
2639
2640        Ok(())
2641    }
2642
2643    #[test]
2644    fn test_in_list_dictionary_int32() -> Result<()> {
2645        // Create schema with dictionary-encoded Int32 column
2646        let dict_type =
2647            DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32));
2648        let schema = Schema::new(vec![Field::new("a", dict_type.clone(), false)]);
2649        let col_a = col("a", &schema)?;
2650
2651        // Create IN list with Int32 literals: (100, 200, 300)
2652        let list = vec![lit(100i32), lit(200i32), lit(300i32)];
2653
2654        // Create InListExpr via in_list(), which selects a primitive static filter.
2655        let expr = in_list(col_a, list, &false, &schema)?;
2656
2657        // Create dictionary-encoded batch with values [100, 200, 500]
2658        // Dictionary: keys [0, 1, 2] -> values [100, 200, 500]
2659        // Using values clearly distinct from keys to avoid confusion
2660        let keys = Int8Array::from(vec![0, 1, 2]);
2661        let values = Int32Array::from(vec![100, 200, 500]);
2662        let dict_array: ArrayRef =
2663            Arc::new(DictionaryArray::try_new(keys, Arc::new(values))?);
2664        let batch = RecordBatch::try_new(Arc::new(schema), vec![dict_array])?;
2665
2666        // Expected: [100 IN (100,200,300), 200 IN (100,200,300), 500 IN (100,200,300)] = [true, true, false]
2667        let result = expr.evaluate(&batch)?.into_array(3)?;
2668        let result = as_boolean_array(&result);
2669        assert_eq!(result, &BooleanArray::from(vec![true, true, false]));
2670        Ok(())
2671    }
2672
2673    #[test]
2674    fn test_in_list_dictionary_types() -> Result<()> {
2675        // Helper functions for creating dictionary literals
2676        fn dict_lit_int64(key_type: DataType, value: i64) -> Arc<dyn PhysicalExpr> {
2677            lit(ScalarValue::Dictionary(
2678                Box::new(key_type),
2679                Box::new(ScalarValue::Int64(Some(value))),
2680            ))
2681        }
2682
2683        fn dict_lit_float64(key_type: DataType, value: f64) -> Arc<dyn PhysicalExpr> {
2684            lit(ScalarValue::Dictionary(
2685                Box::new(key_type),
2686                Box::new(ScalarValue::Float64(Some(value))),
2687            ))
2688        }
2689
2690        // Test case structures
2691        struct DictNeedleTest {
2692            list_values: Vec<Arc<dyn PhysicalExpr>>,
2693            expected: Vec<Option<bool>>,
2694        }
2695
2696        struct DictionaryInListTestCase {
2697            name: &'static str,
2698            dict_type: DataType,
2699            dict_keys: Vec<Option<i8>>,
2700            dict_values: ArrayRef,
2701            list_values_no_null: Vec<Arc<dyn PhysicalExpr>>,
2702            list_values_with_null: Vec<Arc<dyn PhysicalExpr>>,
2703            expected_1: Vec<Option<bool>>,
2704            expected_2: Vec<Option<bool>>,
2705            expected_3: Vec<Option<bool>>,
2706            expected_4: Vec<Option<bool>>,
2707            dict_needle_test: Option<DictNeedleTest>,
2708        }
2709
2710        // Test harness function
2711        fn run_dictionary_in_list_test(
2712            test_case: DictionaryInListTestCase,
2713        ) -> Result<()> {
2714            // Create schema with dictionary type
2715            let schema =
2716                Schema::new(vec![Field::new("a", test_case.dict_type.clone(), true)]);
2717            let col_a = col("a", &schema)?;
2718
2719            // Create dictionary array from keys and values
2720            let keys = Int8Array::from(test_case.dict_keys.clone());
2721            let dict_array: ArrayRef =
2722                Arc::new(DictionaryArray::try_new(keys, test_case.dict_values)?);
2723            let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![dict_array])?;
2724
2725            let exp1 = test_case.expected_1.clone();
2726            let exp2 = test_case.expected_2.clone();
2727            let exp3 = test_case.expected_3.clone();
2728            let exp4 = test_case.expected_4;
2729
2730            // Test 1: a IN (values_no_null)
2731            in_list!(
2732                batch,
2733                test_case.list_values_no_null.clone(),
2734                &false,
2735                exp1,
2736                Arc::clone(&col_a),
2737                &schema
2738            );
2739
2740            // Test 2: a NOT IN (values_no_null)
2741            in_list!(
2742                batch,
2743                test_case.list_values_no_null.clone(),
2744                &true,
2745                exp2,
2746                Arc::clone(&col_a),
2747                &schema
2748            );
2749
2750            // Test 3: a IN (values_with_null)
2751            in_list!(
2752                batch,
2753                test_case.list_values_with_null.clone(),
2754                &false,
2755                exp3,
2756                Arc::clone(&col_a),
2757                &schema
2758            );
2759
2760            // Test 4: a NOT IN (values_with_null)
2761            in_list!(
2762                batch,
2763                test_case.list_values_with_null,
2764                &true,
2765                exp4,
2766                Arc::clone(&col_a),
2767                &schema
2768            );
2769
2770            // Optional: Dictionary needle test (if provided)
2771            if let Some(needle_test) = test_case.dict_needle_test {
2772                in_list_raw!(
2773                    batch,
2774                    needle_test.list_values,
2775                    &false,
2776                    needle_test.expected,
2777                    Arc::clone(&col_a),
2778                    &schema
2779                );
2780            }
2781
2782            Ok(())
2783        }
2784
2785        // Test case 1: UTF8
2786        // Dictionary: keys [0, 1, null] → values ["a", "d", -]
2787        // Rows: ["a", "d", null]
2788        let utf8_case = DictionaryInListTestCase {
2789            name: "dictionary_utf8",
2790            dict_type: DataType::Dictionary(
2791                Box::new(DataType::Int8),
2792                Box::new(DataType::Utf8),
2793            ),
2794            dict_keys: vec![Some(0), Some(1), None],
2795            dict_values: Arc::new(StringArray::from(vec![Some("a"), Some("d")])),
2796            list_values_no_null: vec![lit("a"), lit("b")],
2797            list_values_with_null: vec![lit("a"), lit("b"), lit(ScalarValue::Utf8(None))],
2798            expected_1: vec![Some(true), Some(false), None],
2799            expected_2: vec![Some(false), Some(true), None],
2800            expected_3: vec![Some(true), None, None],
2801            expected_4: vec![Some(false), None, None],
2802            dict_needle_test: None,
2803        };
2804
2805        // Test case 2: Int64 with dictionary needles
2806        // Dictionary: keys [0, 1, null] → values [10, 20, -]
2807        // Rows: [10, 20, null]
2808        let int64_case = DictionaryInListTestCase {
2809            name: "dictionary_int64",
2810            dict_type: DataType::Dictionary(
2811                Box::new(DataType::Int8),
2812                Box::new(DataType::Int64),
2813            ),
2814            dict_keys: vec![Some(0), Some(1), None],
2815            dict_values: Arc::new(Int64Array::from(vec![Some(10), Some(20)])),
2816            list_values_no_null: vec![lit(10i64), lit(15i64)],
2817            list_values_with_null: vec![
2818                lit(10i64),
2819                lit(15i64),
2820                lit(ScalarValue::Int64(None)),
2821            ],
2822            expected_1: vec![Some(true), Some(false), None],
2823            expected_2: vec![Some(false), Some(true), None],
2824            expected_3: vec![Some(true), None, None],
2825            expected_4: vec![Some(false), None, None],
2826            dict_needle_test: Some(DictNeedleTest {
2827                list_values: vec![
2828                    dict_lit_int64(DataType::Int16, 10),
2829                    dict_lit_int64(DataType::Int16, 15),
2830                ],
2831                expected: vec![Some(true), Some(false), None],
2832            }),
2833        };
2834
2835        // Test case 3: Float64 with NaN and dictionary needles
2836        // Dictionary: keys [0, 1, null, 2] → values [1.5, 3.7, NaN, -]
2837        // Rows: [1.5, 3.7, null, NaN]
2838        // Note: NaN is a value (not null), so it goes in the values array
2839        let float64_case = DictionaryInListTestCase {
2840            name: "dictionary_float64",
2841            dict_type: DataType::Dictionary(
2842                Box::new(DataType::Int8),
2843                Box::new(DataType::Float64),
2844            ),
2845            dict_keys: vec![Some(0), Some(1), None, Some(2)],
2846            dict_values: Arc::new(Float64Array::from(vec![
2847                Some(1.5),      // index 0
2848                Some(3.7),      // index 1
2849                Some(f64::NAN), // index 2
2850            ])),
2851            list_values_no_null: vec![lit(1.5f64), lit(2.0f64)],
2852            list_values_with_null: vec![
2853                lit(1.5f64),
2854                lit(2.0f64),
2855                lit(ScalarValue::Float64(None)),
2856            ],
2857            // Test 1: a IN (1.5, 2.0) → [true, false, null, false]
2858            // NaN is false because NaN not in list and no NULL in list
2859            expected_1: vec![Some(true), Some(false), None, Some(false)],
2860            // Test 2: a NOT IN (1.5, 2.0) → [false, true, null, true]
2861            // NaN is true because NaN not in list
2862            expected_2: vec![Some(false), Some(true), None, Some(true)],
2863            // Test 3: a IN (1.5, 2.0, NULL) → [true, null, null, null]
2864            // 3.7 and NaN become null due to NULL in list (three-valued logic)
2865            expected_3: vec![Some(true), None, None, None],
2866            // Test 4: a NOT IN (1.5, 2.0, NULL) → [false, null, null, null]
2867            // 3.7 and NaN become null due to NULL in list
2868            expected_4: vec![Some(false), None, None, None],
2869            dict_needle_test: Some(DictNeedleTest {
2870                list_values: vec![
2871                    dict_lit_float64(DataType::UInt16, 1.5),
2872                    dict_lit_float64(DataType::UInt16, 2.0),
2873                ],
2874                expected: vec![Some(true), Some(false), None, Some(false)],
2875            }),
2876        };
2877
2878        // Execute all test cases
2879        let test_name = utf8_case.name;
2880        run_dictionary_in_list_test(utf8_case).map_err(|e| {
2881            datafusion_common::DataFusionError::Execution(format!(
2882                "Dictionary test '{test_name}' failed: {e}"
2883            ))
2884        })?;
2885
2886        let test_name = int64_case.name;
2887        run_dictionary_in_list_test(int64_case).map_err(|e| {
2888            datafusion_common::DataFusionError::Execution(format!(
2889                "Dictionary test '{test_name}' failed: {e}"
2890            ))
2891        })?;
2892
2893        let test_name = float64_case.name;
2894        run_dictionary_in_list_test(float64_case).map_err(|e| {
2895            datafusion_common::DataFusionError::Execution(format!(
2896                "Dictionary test '{test_name}' failed: {e}"
2897            ))
2898        })?;
2899
2900        // Additional test: Dictionary deduplication with repeated keys
2901        // This tests that multiple rows with the same key (pointing to the same value)
2902        // are evaluated correctly
2903        let dedup_case = DictionaryInListTestCase {
2904            name: "dictionary_deduplication",
2905            dict_type: DataType::Dictionary(
2906                Box::new(DataType::Int8),
2907                Box::new(DataType::Utf8),
2908            ),
2909            // Keys: [0, 1, 0, 1, null] - keys 0 and 1 are repeated
2910            // This creates data: ["a", "d", "a", "d", null]
2911            dict_keys: vec![Some(0), Some(1), Some(0), Some(1), None],
2912            dict_values: Arc::new(StringArray::from(vec![Some("a"), Some("d")])),
2913            list_values_no_null: vec![lit("a"), lit("b")],
2914            list_values_with_null: vec![lit("a"), lit("b"), lit(ScalarValue::Utf8(None))],
2915            // Test 1: a IN ("a", "b") → [true, false, true, false, null]
2916            // Rows 0 and 2 both have key 0 → "a", so both are true
2917            expected_1: vec![Some(true), Some(false), Some(true), Some(false), None],
2918            // Test 2: a NOT IN ("a", "b") → [false, true, false, true, null]
2919            expected_2: vec![Some(false), Some(true), Some(false), Some(true), None],
2920            // Test 3: a IN ("a", "b", NULL) → [true, null, true, null, null]
2921            // "d" becomes null due to NULL in list
2922            expected_3: vec![Some(true), None, Some(true), None, None],
2923            // Test 4: a NOT IN ("a", "b", NULL) → [false, null, false, null, null]
2924            expected_4: vec![Some(false), None, Some(false), None, None],
2925            dict_needle_test: None,
2926        };
2927
2928        let test_name = dedup_case.name;
2929        run_dictionary_in_list_test(dedup_case).map_err(|e| {
2930            datafusion_common::DataFusionError::Execution(format!(
2931                "Dictionary test '{test_name}' failed: {e}"
2932            ))
2933        })?;
2934
2935        // Additional test for Float64 NaN in IN list
2936        let dict_type =
2937            DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Float64));
2938        let schema = Schema::new(vec![Field::new("a", dict_type.clone(), true)]);
2939        let col_a = col("a", &schema)?;
2940
2941        let keys = Int8Array::from(vec![Some(0), Some(1), None, Some(2)]);
2942        let values = Float64Array::from(vec![Some(1.5), Some(3.7), Some(f64::NAN)]);
2943        let dict_array: ArrayRef =
2944            Arc::new(DictionaryArray::try_new(keys, Arc::new(values))?);
2945        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![dict_array])?;
2946
2947        // Test: a IN (1.5, 2.0, NaN)
2948        let list_with_nan = vec![lit(1.5f64), lit(2.0f64), lit(f64::NAN)];
2949        in_list!(
2950            batch,
2951            list_with_nan,
2952            &false,
2953            vec![Some(true), Some(false), None, Some(true)],
2954            col_a,
2955            &schema
2956        );
2957
2958        Ok(())
2959    }
2960
2961    #[test]
2962    fn test_in_list_esoteric_types() -> Result<()> {
2963        // Test less common types covered by IN-list evaluation. Some of these
2964        // use specialized filters, and others fall back to the generic path;
2965        // this keeps the end-to-end behavior covered either way.
2966
2967        // Helper: simple IN test that expects [Some(true), Some(false)]
2968        let test_type = |data_type: DataType,
2969                         in_array: ArrayRef,
2970                         list_values: Vec<ScalarValue>|
2971         -> Result<()> {
2972            let schema = Schema::new(vec![Field::new("a", data_type.clone(), false)]);
2973            let col_a = col("a", &schema)?;
2974            let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![in_array])?;
2975
2976            let list = list_values.into_iter().map(lit).collect();
2977            in_list!(
2978                batch,
2979                list,
2980                &false,
2981                vec![Some(true), Some(false)],
2982                col_a,
2983                &schema
2984            );
2985            Ok(())
2986        };
2987
2988        // Timestamp types
2989        test_type(
2990            DataType::Timestamp(TimeUnit::Second, None),
2991            Arc::new(TimestampSecondArray::from(vec![Some(1000), Some(2000)])),
2992            vec![
2993                ScalarValue::TimestampSecond(Some(1000), None),
2994                ScalarValue::TimestampSecond(Some(1500), None),
2995            ],
2996        )?;
2997
2998        test_type(
2999            DataType::Timestamp(TimeUnit::Millisecond, None),
3000            Arc::new(TimestampMillisecondArray::from(vec![
3001                Some(1000000),
3002                Some(2000000),
3003            ])),
3004            vec![
3005                ScalarValue::TimestampMillisecond(Some(1000000), None),
3006                ScalarValue::TimestampMillisecond(Some(1500000), None),
3007            ],
3008        )?;
3009
3010        test_type(
3011            DataType::Timestamp(TimeUnit::Microsecond, None),
3012            Arc::new(TimestampMicrosecondArray::from(vec![
3013                Some(1000000000),
3014                Some(2000000000),
3015            ])),
3016            vec![
3017                ScalarValue::TimestampMicrosecond(Some(1000000000), None),
3018                ScalarValue::TimestampMicrosecond(Some(1500000000), None),
3019            ],
3020        )?;
3021
3022        // Time32 and Time64
3023        test_type(
3024            DataType::Time32(TimeUnit::Second),
3025            Arc::new(Time32SecondArray::from(vec![Some(3600), Some(7200)])),
3026            vec![
3027                ScalarValue::Time32Second(Some(3600)),
3028                ScalarValue::Time32Second(Some(5400)),
3029            ],
3030        )?;
3031
3032        test_type(
3033            DataType::Time32(TimeUnit::Millisecond),
3034            Arc::new(Time32MillisecondArray::from(vec![
3035                Some(3600000),
3036                Some(7200000),
3037            ])),
3038            vec![
3039                ScalarValue::Time32Millisecond(Some(3600000)),
3040                ScalarValue::Time32Millisecond(Some(5400000)),
3041            ],
3042        )?;
3043
3044        test_type(
3045            DataType::Time64(TimeUnit::Microsecond),
3046            Arc::new(Time64MicrosecondArray::from(vec![
3047                Some(3600000000),
3048                Some(7200000000),
3049            ])),
3050            vec![
3051                ScalarValue::Time64Microsecond(Some(3600000000)),
3052                ScalarValue::Time64Microsecond(Some(5400000000)),
3053            ],
3054        )?;
3055
3056        test_type(
3057            DataType::Time64(TimeUnit::Nanosecond),
3058            Arc::new(Time64NanosecondArray::from(vec![
3059                Some(3600000000000),
3060                Some(7200000000000),
3061            ])),
3062            vec![
3063                ScalarValue::Time64Nanosecond(Some(3600000000000)),
3064                ScalarValue::Time64Nanosecond(Some(5400000000000)),
3065            ],
3066        )?;
3067
3068        // Duration types
3069        test_type(
3070            DataType::Duration(TimeUnit::Second),
3071            Arc::new(DurationSecondArray::from(vec![Some(86400), Some(172800)])),
3072            vec![
3073                ScalarValue::DurationSecond(Some(86400)),
3074                ScalarValue::DurationSecond(Some(129600)),
3075            ],
3076        )?;
3077
3078        test_type(
3079            DataType::Duration(TimeUnit::Millisecond),
3080            Arc::new(DurationMillisecondArray::from(vec![
3081                Some(86400000),
3082                Some(172800000),
3083            ])),
3084            vec![
3085                ScalarValue::DurationMillisecond(Some(86400000)),
3086                ScalarValue::DurationMillisecond(Some(129600000)),
3087            ],
3088        )?;
3089
3090        test_type(
3091            DataType::Duration(TimeUnit::Microsecond),
3092            Arc::new(DurationMicrosecondArray::from(vec![
3093                Some(86400000000),
3094                Some(172800000000),
3095            ])),
3096            vec![
3097                ScalarValue::DurationMicrosecond(Some(86400000000)),
3098                ScalarValue::DurationMicrosecond(Some(129600000000)),
3099            ],
3100        )?;
3101
3102        test_type(
3103            DataType::Duration(TimeUnit::Nanosecond),
3104            Arc::new(DurationNanosecondArray::from(vec![
3105                Some(86400000000000),
3106                Some(172800000000000),
3107            ])),
3108            vec![
3109                ScalarValue::DurationNanosecond(Some(86400000000000)),
3110                ScalarValue::DurationNanosecond(Some(129600000000000)),
3111            ],
3112        )?;
3113
3114        // Interval types
3115        test_type(
3116            DataType::Interval(IntervalUnit::YearMonth),
3117            Arc::new(IntervalYearMonthArray::from(vec![Some(12), Some(24)])),
3118            vec![
3119                ScalarValue::IntervalYearMonth(Some(12)),
3120                ScalarValue::IntervalYearMonth(Some(18)),
3121            ],
3122        )?;
3123
3124        test_type(
3125            DataType::Interval(IntervalUnit::DayTime),
3126            Arc::new(IntervalDayTimeArray::from(vec![
3127                Some(IntervalDayTime {
3128                    days: 1,
3129                    milliseconds: 0,
3130                }),
3131                Some(IntervalDayTime {
3132                    days: 2,
3133                    milliseconds: 0,
3134                }),
3135            ])),
3136            vec![
3137                ScalarValue::IntervalDayTime(Some(IntervalDayTime {
3138                    days: 1,
3139                    milliseconds: 0,
3140                })),
3141                ScalarValue::IntervalDayTime(Some(IntervalDayTime {
3142                    days: 1,
3143                    milliseconds: 500,
3144                })),
3145            ],
3146        )?;
3147
3148        test_type(
3149            DataType::Interval(IntervalUnit::MonthDayNano),
3150            Arc::new(IntervalMonthDayNanoArray::from(vec![
3151                Some(IntervalMonthDayNano {
3152                    months: 1,
3153                    days: 0,
3154                    nanoseconds: 0,
3155                }),
3156                Some(IntervalMonthDayNano {
3157                    months: 2,
3158                    days: 0,
3159                    nanoseconds: 0,
3160                }),
3161            ])),
3162            vec![
3163                ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano {
3164                    months: 1,
3165                    days: 0,
3166                    nanoseconds: 0,
3167                })),
3168                ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano {
3169                    months: 1,
3170                    days: 15,
3171                    nanoseconds: 0,
3172                })),
3173            ],
3174        )?;
3175
3176        // Decimal256. Need to use with_precision_and_scale() to set the metadata.
3177        let precision = 38;
3178        let scale = 10;
3179        test_type(
3180            DataType::Decimal256(precision, scale),
3181            Arc::new(
3182                Decimal256Array::from(vec![
3183                    Some(i256::from(12345)),
3184                    Some(i256::from(67890)),
3185                ])
3186                .with_precision_and_scale(precision, scale)?,
3187            ),
3188            vec![
3189                ScalarValue::Decimal256(Some(i256::from(12345)), precision, scale),
3190                ScalarValue::Decimal256(Some(i256::from(54321)), precision, scale),
3191            ],
3192        )?;
3193
3194        Ok(())
3195    }
3196
3197    #[test]
3198    fn test_in_list_case_item_reading_a_column() -> Result<()> {
3199        // n IN (2, CASE WHEN d > 5 THEN 1 ELSE d END)
3200        let schema = Schema::new(vec![
3201            Field::new("n", DataType::Int32, false),
3202            Field::new("d", DataType::Int32, false),
3203        ]);
3204        let d = col("d", &schema)?;
3205        let when = binary(Arc::clone(&d), Operator::Gt, lit(5i32), &schema)?;
3206        let item = case(None, vec![(when, lit(1i32))], Some(d))?;
3207        let expr = in_list(col("n", &schema)?, vec![lit(2i32), item], &false, &schema)?;
3208        let batch = RecordBatch::try_new(
3209            Arc::new(schema),
3210            vec![
3211                Arc::new(Int32Array::from(vec![2, 4, 1])),
3212                Arc::new(Int32Array::from(vec![0, 4, 3])),
3213            ],
3214        )?;
3215
3216        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3217        assert_eq!(
3218            as_boolean_array(&result),
3219            &BooleanArray::from(vec![true, true, false])
3220        );
3221        Ok(())
3222    }
3223
3224    /// Helper: creates an InListExpr with `static_filter = None`
3225    /// to force the column-reference evaluation path.
3226    fn make_in_list_with_columns(
3227        expr: Arc<dyn PhysicalExpr>,
3228        list: Vec<Arc<dyn PhysicalExpr>>,
3229        negated: bool,
3230    ) -> Arc<InListExpr> {
3231        Arc::new(InListExpr::new(expr, list, negated, None))
3232    }
3233
3234    #[test]
3235    fn test_in_list_with_columns_int32_scalars() -> Result<()> {
3236        // Column-reference path with scalar literals (bypassing static filter)
3237        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
3238        let col_a = col("a", &schema)?;
3239        let batch = RecordBatch::try_new(
3240            Arc::new(schema),
3241            vec![Arc::new(Int32Array::from(vec![
3242                Some(1),
3243                Some(2),
3244                Some(3),
3245                None,
3246            ]))],
3247        )?;
3248
3249        let list = vec![
3250            lit(ScalarValue::Int32(Some(1))),
3251            lit(ScalarValue::Int32(Some(3))),
3252        ];
3253        let expr = make_in_list_with_columns(col_a, list, false);
3254
3255        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3256        let result = as_boolean_array(&result);
3257        assert_eq!(
3258            result,
3259            &BooleanArray::from(vec![Some(true), Some(false), Some(true), None,])
3260        );
3261        Ok(())
3262    }
3263
3264    #[test]
3265    fn test_in_list_with_columns_int32_column_refs() -> Result<()> {
3266        // IN list with column references
3267        let schema = Schema::new(vec![
3268            Field::new("a", DataType::Int32, true),
3269            Field::new("b", DataType::Int32, true),
3270            Field::new("c", DataType::Int32, true),
3271        ]);
3272        let batch = RecordBatch::try_new(
3273            Arc::new(schema.clone()),
3274            vec![
3275                Arc::new(Int32Array::from(vec![Some(1), Some(2), Some(3), None])),
3276                Arc::new(Int32Array::from(vec![
3277                    Some(1),
3278                    Some(99),
3279                    Some(99),
3280                    Some(99),
3281                ])),
3282                Arc::new(Int32Array::from(vec![Some(99), Some(99), Some(3), None])),
3283            ],
3284        )?;
3285
3286        let col_a = col("a", &schema)?;
3287        let list = vec![col("b", &schema)?, col("c", &schema)?];
3288        let expr = make_in_list_with_columns(col_a, list, false);
3289
3290        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3291        let result = as_boolean_array(&result);
3292        // row 0: 1 IN (1, 99) → true
3293        // row 1: 2 IN (99, 99) → false
3294        // row 2: 3 IN (99, 3) → true
3295        // row 3: NULL IN (99, NULL) → NULL
3296        assert_eq!(
3297            result,
3298            &BooleanArray::from(vec![Some(true), Some(false), Some(true), None,])
3299        );
3300        Ok(())
3301    }
3302
3303    #[test]
3304    fn test_in_list_with_columns_utf8_column_refs() -> Result<()> {
3305        // IN list with Utf8 column references
3306        let schema = Schema::new(vec![
3307            Field::new("a", DataType::Utf8, false),
3308            Field::new("b", DataType::Utf8, false),
3309        ]);
3310        let batch = RecordBatch::try_new(
3311            Arc::new(schema.clone()),
3312            vec![
3313                Arc::new(StringArray::from(vec!["x", "y", "z"])),
3314                Arc::new(StringArray::from(vec!["x", "x", "z"])),
3315            ],
3316        )?;
3317
3318        let col_a = col("a", &schema)?;
3319        let list = vec![col("b", &schema)?];
3320        let expr = make_in_list_with_columns(col_a, list, false);
3321
3322        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3323        let result = as_boolean_array(&result);
3324        // row 0: "x" IN ("x") → true
3325        // row 1: "y" IN ("x") → false
3326        // row 2: "z" IN ("z") → true
3327        assert_eq!(result, &BooleanArray::from(vec![true, false, true]));
3328        Ok(())
3329    }
3330
3331    #[test]
3332    fn test_in_list_with_columns_negated() -> Result<()> {
3333        // NOT IN with column references
3334        let schema = Schema::new(vec![
3335            Field::new("a", DataType::Int32, false),
3336            Field::new("b", DataType::Int32, false),
3337        ]);
3338        let batch = RecordBatch::try_new(
3339            Arc::new(schema.clone()),
3340            vec![
3341                Arc::new(Int32Array::from(vec![1, 2, 3])),
3342                Arc::new(Int32Array::from(vec![1, 99, 3])),
3343            ],
3344        )?;
3345
3346        let col_a = col("a", &schema)?;
3347        let list = vec![col("b", &schema)?];
3348        let expr = make_in_list_with_columns(col_a, list, true);
3349
3350        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3351        let result = as_boolean_array(&result);
3352        // row 0: 1 NOT IN (1) → false
3353        // row 1: 2 NOT IN (99) → true
3354        // row 2: 3 NOT IN (3) → false
3355        assert_eq!(result, &BooleanArray::from(vec![false, true, false]));
3356        Ok(())
3357    }
3358
3359    #[test]
3360    fn test_in_list_with_columns_null_in_list() -> Result<()> {
3361        // IN list with NULL scalar (column-reference path)
3362        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
3363        let col_a = col("a", &schema)?;
3364        let batch = RecordBatch::try_new(
3365            Arc::new(schema),
3366            vec![Arc::new(Int32Array::from(vec![1, 2]))],
3367        )?;
3368
3369        let list = vec![
3370            lit(ScalarValue::Int32(None)),
3371            lit(ScalarValue::Int32(Some(1))),
3372        ];
3373        let expr = make_in_list_with_columns(col_a, list, false);
3374
3375        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3376        let result = as_boolean_array(&result);
3377        // row 0: 1 IN (NULL, 1) → true (true OR null = true)
3378        // row 1: 2 IN (NULL, 1) → NULL (false OR null = null)
3379        assert_eq!(result, &BooleanArray::from(vec![Some(true), None]));
3380        Ok(())
3381    }
3382
3383    #[test]
3384    fn test_in_list_with_columns_float_nan() -> Result<()> {
3385        // Verify NaN == NaN is true in the column-reference path
3386        // (consistent with Arrow's totalOrder semantics)
3387        let schema = Schema::new(vec![
3388            Field::new("a", DataType::Float64, false),
3389            Field::new("b", DataType::Float64, false),
3390        ]);
3391        let batch = RecordBatch::try_new(
3392            Arc::new(schema.clone()),
3393            vec![
3394                Arc::new(Float64Array::from(vec![f64::NAN, 1.0, f64::NAN])),
3395                Arc::new(Float64Array::from(vec![f64::NAN, 2.0, 0.0])),
3396            ],
3397        )?;
3398
3399        let col_a = col("a", &schema)?;
3400        let list = vec![col("b", &schema)?];
3401        let expr = make_in_list_with_columns(col_a, list, false);
3402
3403        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3404        let result = as_boolean_array(&result);
3405        // row 0: NaN IN (NaN) → true
3406        // row 1: 1.0 IN (2.0) → false
3407        // row 2: NaN IN (0.0) → false
3408        assert_eq!(result, &BooleanArray::from(vec![true, false, false]));
3409        Ok(())
3410    }
3411
3412    #[test]
3413    fn test_in_list_with_columns_float_signed_zero() -> Result<()> {
3414        use arrow::compute::cast;
3415
3416        for (data_type, dictionary) in [
3417            (DataType::Float32, false),
3418            (DataType::Float64, false),
3419            (DataType::Float64, true),
3420        ] {
3421            let mut left = cast(&Float64Array::from(vec![0.0, -0.0, 1.0]), &data_type)?;
3422            let mut right = cast(&Float64Array::from(vec![-0.0, 0.0, 2.0]), &data_type)?;
3423            if dictionary {
3424                left = wrap_in_dict(left);
3425                right = wrap_in_dict(right);
3426            }
3427            let scalar = lit(ScalarValue::try_from_array(left.as_ref(), 1)?);
3428            let batch = RecordBatch::try_from_iter([("a", left), ("b", right)])?;
3429            let schema = batch.schema();
3430
3431            // Exercise array and scalar values on both sides, including scalar
3432            // normalization before the left-hand side is broadcast.
3433            for (left, right) in [
3434                (col("a", &schema)?, col("b", &schema)?),
3435                (col("a", &schema)?, Arc::clone(&scalar)),
3436                (scalar, col("a", &schema)?),
3437            ] {
3438                let expr = make_in_list_with_columns(left, vec![right], false);
3439                let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3440                assert_eq!(
3441                    as_boolean_array(&result),
3442                    &BooleanArray::from(vec![true, true, false]),
3443                    "{data_type:?}, dictionary={dictionary}: {expr}"
3444                );
3445            }
3446        }
3447        Ok(())
3448    }
3449
3450    /// Tests that short-circuit evaluation produces correct results.
3451    /// When all rows match after the first list item, remaining items
3452    /// should be skipped without affecting correctness.
3453    #[test]
3454    fn test_in_list_with_columns_short_circuit() -> Result<()> {
3455        // a IN (b, c) where b already matches every row of a
3456        // The short-circuit should skip evaluating c
3457        let schema = Schema::new(vec![
3458            Field::new("a", DataType::Int32, false),
3459            Field::new("b", DataType::Int32, false),
3460            Field::new("c", DataType::Int32, false),
3461        ]);
3462        let batch = RecordBatch::try_new(
3463            Arc::new(schema.clone()),
3464            vec![
3465                Arc::new(Int32Array::from(vec![1, 2, 3])),
3466                Arc::new(Int32Array::from(vec![1, 2, 3])), // b == a for all rows
3467                Arc::new(Int32Array::from(vec![99, 99, 99])),
3468            ],
3469        )?;
3470
3471        let col_a = col("a", &schema)?;
3472        let list = vec![col("b", &schema)?, col("c", &schema)?];
3473        let expr = make_in_list_with_columns(col_a, list, false);
3474
3475        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3476        let result = as_boolean_array(&result);
3477        assert_eq!(result, &BooleanArray::from(vec![true, true, true]));
3478        Ok(())
3479    }
3480
3481    /// Short-circuit must NOT skip when nulls are present (three-valued logic).
3482    /// Even if all non-null values are true, null rows keep the result as null.
3483    #[test]
3484    fn test_in_list_with_columns_short_circuit_with_nulls() -> Result<()> {
3485        // a IN (b, c) where a has nulls
3486        // Even if b matches all non-null rows, result should preserve nulls
3487        let schema = Schema::new(vec![
3488            Field::new("a", DataType::Int32, true),
3489            Field::new("b", DataType::Int32, false),
3490            Field::new("c", DataType::Int32, false),
3491        ]);
3492        let batch = RecordBatch::try_new(
3493            Arc::new(schema.clone()),
3494            vec![
3495                Arc::new(Int32Array::from(vec![Some(1), None, Some(3)])),
3496                Arc::new(Int32Array::from(vec![1, 2, 3])), // matches non-null rows
3497                Arc::new(Int32Array::from(vec![99, 99, 99])),
3498            ],
3499        )?;
3500
3501        let col_a = col("a", &schema)?;
3502        let list = vec![col("b", &schema)?, col("c", &schema)?];
3503        let expr = make_in_list_with_columns(col_a, list, false);
3504
3505        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3506        let result = as_boolean_array(&result);
3507        // row 0: 1 IN (1, 99) → true
3508        // row 1: NULL IN (2, 99) → NULL
3509        // row 2: 3 IN (3, 99) → true
3510        assert_eq!(
3511            result,
3512            &BooleanArray::from(vec![Some(true), None, Some(true)])
3513        );
3514        Ok(())
3515    }
3516
3517    /// Tests the make_comparator + collect_bool fallback path using
3518    /// struct column references (nested types don't support arrow_eq).
3519    #[test]
3520    fn test_in_list_with_columns_struct() -> Result<()> {
3521        let struct_fields = Fields::from(vec![
3522            Field::new("x", DataType::Int32, false),
3523            Field::new("y", DataType::Utf8, false),
3524        ]);
3525        let struct_dt = DataType::Struct(struct_fields.clone());
3526
3527        let schema = Schema::new(vec![
3528            Field::new("a", struct_dt.clone(), true),
3529            Field::new("b", struct_dt.clone(), false),
3530            Field::new("c", struct_dt.clone(), false),
3531        ]);
3532
3533        // a: [{1,"a"}, {2,"b"}, NULL,    {4,"d"}]
3534        // b: [{1,"a"}, {9,"z"}, {3,"c"}, {4,"d"}]
3535        // c: [{9,"z"}, {2,"b"}, {9,"z"}, {9,"z"}]
3536        let a = Arc::new(StructArray::new(
3537            struct_fields.clone(),
3538            vec![
3539                Arc::new(Int32Array::from(vec![1, 2, 3, 4])),
3540                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])),
3541            ],
3542            Some(vec![true, true, false, true].into()),
3543        ));
3544        let b = Arc::new(StructArray::new(
3545            struct_fields.clone(),
3546            vec![
3547                Arc::new(Int32Array::from(vec![1, 9, 3, 4])),
3548                Arc::new(StringArray::from(vec!["a", "z", "c", "d"])),
3549            ],
3550            None,
3551        ));
3552        let c = Arc::new(StructArray::new(
3553            struct_fields.clone(),
3554            vec![
3555                Arc::new(Int32Array::from(vec![9, 2, 9, 9])),
3556                Arc::new(StringArray::from(vec!["z", "b", "z", "z"])),
3557            ],
3558            None,
3559        ));
3560
3561        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![a, b, c])?;
3562
3563        let col_a = col("a", &schema)?;
3564        let list = vec![col("b", &schema)?, col("c", &schema)?];
3565        let expr = make_in_list_with_columns(col_a, list, false);
3566
3567        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3568        let result = as_boolean_array(&result);
3569        // row 0: {1,"a"} IN ({1,"a"}, {9,"z"}) → true  (matches b)
3570        // row 1: {2,"b"} IN ({9,"z"}, {2,"b"}) → true  (matches c)
3571        // row 2: NULL    IN ({3,"c"}, {9,"z"}) → NULL
3572        // row 3: {4,"d"} IN ({4,"d"}, {9,"z"}) → true  (matches b)
3573        assert_eq!(
3574            result,
3575            &BooleanArray::from(vec![Some(true), Some(true), None, Some(true)])
3576        );
3577
3578        // Also test NOT IN
3579        let col_a = col("a", &schema)?;
3580        let list = vec![col("b", &schema)?, col("c", &schema)?];
3581        let expr = make_in_list_with_columns(col_a, list, true);
3582
3583        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3584        let result = as_boolean_array(&result);
3585        // row 0: {1,"a"} NOT IN ({1,"a"}, {9,"z"}) → false
3586        // row 1: {2,"b"} NOT IN ({9,"z"}, {2,"b"}) → false
3587        // row 2: NULL    NOT IN ({3,"c"}, {9,"z"}) → NULL
3588        // row 3: {4,"d"} NOT IN ({4,"d"}, {9,"z"}) → false
3589        assert_eq!(
3590            result,
3591            &BooleanArray::from(vec![Some(false), Some(false), None, Some(false)])
3592        );
3593        Ok(())
3594    }
3595
3596    // -----------------------------------------------------------------------
3597    // Tests for try_new_from_array: evaluates `needle IN in_array`.
3598    //
3599    // This exercises the code path used by HashJoin dynamic filter pushdown,
3600    // where in_array is built directly from the join's build-side arrays.
3601    // Unlike try_new (used by SQL IN expressions), which always produces a
3602    // non-Dictionary in_array because evaluate_list() flattens Dictionary
3603    // scalars, try_new_from_array passes the array directly and can produce
3604    // a Dictionary in_array.
3605    // -----------------------------------------------------------------------
3606
3607    fn wrap_in_dict(array: ArrayRef) -> ArrayRef {
3608        let keys = Int32Array::from((0..array.len() as i32).collect::<Vec<_>>());
3609        Arc::new(DictionaryArray::new(keys, array))
3610    }
3611
3612    /// Evaluates `needle IN in_array` via try_new_from_array, the same
3613    /// path used by HashJoin dynamic filter pushdown (not the SQL literal
3614    /// IN path which goes through try_new).
3615    fn eval_in_list_from_array(
3616        needle: ArrayRef,
3617        in_array: ArrayRef,
3618    ) -> Result<BooleanArray> {
3619        let schema =
3620            Schema::new(vec![Field::new("a", needle.data_type().clone(), false)]);
3621        let col_a = col("a", &schema)?;
3622        let expr = Arc::new(InListExpr::try_new_from_array(
3623            col_a, in_array, false, &schema,
3624        )?) as Arc<dyn PhysicalExpr>;
3625        let batch = RecordBatch::try_new(Arc::new(schema), vec![needle])?;
3626        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3627        Ok(as_boolean_array(&result).clone())
3628    }
3629
3630    #[test]
3631    fn test_in_list_from_array_type_combinations() -> Result<()> {
3632        use arrow::compute::cast;
3633
3634        // All cases: needle[0] and needle[2] match, needle[1] does not.
3635        let expected = BooleanArray::from(vec![Some(true), Some(false), Some(true)]);
3636
3637        // Base arrays cast to each target type
3638        let base_in = Arc::new(Int64Array::from(vec![1i64, 2, 3])) as ArrayRef;
3639        let base_needle = Arc::new(Int64Array::from(vec![1i64, 4, 2])) as ArrayRef;
3640
3641        // Test all specializations in instantiate_static_filter
3642        let primitive_types = vec![
3643            DataType::Int8,
3644            DataType::Int16,
3645            DataType::Int32,
3646            DataType::Int64,
3647            DataType::UInt8,
3648            DataType::UInt16,
3649            DataType::UInt32,
3650            DataType::UInt64,
3651            DataType::Float16,
3652            DataType::Float32,
3653            DataType::Float64,
3654        ];
3655
3656        for dt in &primitive_types {
3657            let in_array = cast(&base_in, dt)?;
3658            let needle = cast(&base_needle, dt)?;
3659
3660            // T in_array, T needle
3661            assert_eq!(
3662                expected,
3663                eval_in_list_from_array(Arc::clone(&needle), Arc::clone(&in_array))?,
3664                "same-type failed for {dt:?}"
3665            );
3666
3667            // T in_array, Dict(Int32, T) needle
3668            assert_eq!(
3669                expected,
3670                eval_in_list_from_array(wrap_in_dict(needle), in_array)?,
3671                "dict-needle failed for {dt:?}"
3672            );
3673        }
3674
3675        // FixedSizeBinary in_array, FixedSizeBinary and Dictionary needles
3676        let fsb_in = Arc::new(FixedSizeBinaryArray::try_from_iter(
3677            [
3678                [1, 2, 3, 4].as_slice(),
3679                [5, 6, 7, 8].as_slice(),
3680                [9, 10, 11, 12].as_slice(),
3681            ]
3682            .into_iter(),
3683        )?) as ArrayRef;
3684        let fsb_needle = Arc::new(FixedSizeBinaryArray::try_from_iter(
3685            [
3686                [1, 2, 3, 4].as_slice(),
3687                [13, 14, 15, 16].as_slice(),
3688                [5, 6, 7, 8].as_slice(),
3689            ]
3690            .into_iter(),
3691        )?) as ArrayRef;
3692        assert_eq!(
3693            expected,
3694            eval_in_list_from_array(Arc::clone(&fsb_needle), Arc::clone(&fsb_in))?
3695        );
3696        // The dictionary does not reference its second value, so that value
3697        // must not become a member of the flattened list.
3698        let dict_fsb_in = Arc::new(DictionaryArray::new(
3699            Int32Array::from(vec![0, 2]),
3700            Arc::clone(&fsb_in),
3701        ));
3702        assert_eq!(
3703            BooleanArray::from(vec![Some(true), Some(false), Some(false)]),
3704            eval_in_list_from_array(wrap_in_dict(fsb_needle), dict_fsb_in)?
3705        );
3706
3707        // Utf8 (falls through to ArrayStaticFilter)
3708        let utf8_in = Arc::new(StringArray::from(vec!["a", "b", "c"])) as ArrayRef;
3709        let utf8_needle = Arc::new(StringArray::from(vec!["a", "d", "b"])) as ArrayRef;
3710
3711        // Utf8 in_array, Utf8 needle
3712        assert_eq!(
3713            expected,
3714            eval_in_list_from_array(Arc::clone(&utf8_needle), Arc::clone(&utf8_in),)?
3715        );
3716
3717        // Utf8 in_array, Dict(Utf8) needle
3718        assert_eq!(
3719            expected,
3720            eval_in_list_from_array(
3721                wrap_in_dict(Arc::clone(&utf8_needle)),
3722                Arc::clone(&utf8_in),
3723            )?
3724        );
3725
3726        // Dict(Utf8) in_array, Dict(Utf8) needle: the #20937 bug
3727        assert_eq!(
3728            expected,
3729            eval_in_list_from_array(
3730                wrap_in_dict(Arc::clone(&utf8_needle)),
3731                wrap_in_dict(Arc::clone(&utf8_in)),
3732            )?
3733        );
3734
3735        // Utf8View in_array, Utf8View and Dict(Utf8View) needles
3736        let utf8view_in =
3737            Arc::new(StringViewArray::from(vec!["a", "b", "c", "d", "e"])) as ArrayRef;
3738        let utf8view_needle =
3739            Arc::new(StringViewArray::from(vec!["a", "missing", "b"])) as ArrayRef;
3740        assert_eq!(
3741            expected,
3742            eval_in_list_from_array(
3743                Arc::clone(&utf8view_needle),
3744                Arc::clone(&utf8view_in),
3745            )?
3746        );
3747        assert_eq!(
3748            expected,
3749            eval_in_list_from_array(wrap_in_dict(utf8view_needle), utf8view_in)?
3750        );
3751
3752        // Struct in_array, Struct needle: multi-column join
3753        let struct_fields = Fields::from(vec![
3754            Field::new("c0", DataType::Utf8, true),
3755            Field::new("c1", DataType::Int64, true),
3756        ]);
3757        let make_struct = |c0: ArrayRef, c1: ArrayRef| -> ArrayRef {
3758            let pairs: Vec<(FieldRef, ArrayRef)> =
3759                struct_fields.iter().cloned().zip([c0, c1]).collect();
3760            Arc::new(StructArray::from(pairs))
3761        };
3762        assert_eq!(
3763            expected,
3764            eval_in_list_from_array(
3765                make_struct(
3766                    Arc::clone(&utf8_needle),
3767                    Arc::new(Int64Array::from(vec![1, 4, 2])),
3768                ),
3769                make_struct(
3770                    Arc::clone(&utf8_in),
3771                    Arc::new(Int64Array::from(vec![1, 2, 3])),
3772                ),
3773            )?
3774        );
3775
3776        // Struct with Dict fields: multi-column Dict join
3777        let dict_struct_fields = Fields::from(vec![
3778            Field::new(
3779                "c0",
3780                DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
3781                true,
3782            ),
3783            Field::new("c1", DataType::Int64, true),
3784        ]);
3785        let make_dict_struct = |c0: ArrayRef, c1: ArrayRef| -> ArrayRef {
3786            let pairs: Vec<(FieldRef, ArrayRef)> =
3787                dict_struct_fields.iter().cloned().zip([c0, c1]).collect();
3788            Arc::new(StructArray::from(pairs))
3789        };
3790        assert_eq!(
3791            expected,
3792            eval_in_list_from_array(
3793                make_dict_struct(
3794                    wrap_in_dict(Arc::clone(&utf8_needle)),
3795                    Arc::new(Int64Array::from(vec![1, 4, 2])),
3796                ),
3797                make_dict_struct(
3798                    wrap_in_dict(Arc::clone(&utf8_in)),
3799                    Arc::new(Int64Array::from(vec![1, 2, 3])),
3800                ),
3801            )?
3802        );
3803
3804        Ok(())
3805    }
3806
3807    fn make_int32_dict_array(values: Vec<Option<i32>>) -> ArrayRef {
3808        let mut builder = PrimitiveDictionaryBuilder::<Int8Type, Int32Type>::new();
3809        for v in values {
3810            match v {
3811                Some(val) => builder.append_value(val),
3812                None => builder.append_null(),
3813            }
3814        }
3815        Arc::new(builder.finish())
3816    }
3817
3818    fn make_f64_dict_array(values: Vec<Option<f64>>) -> ArrayRef {
3819        let mut builder = PrimitiveDictionaryBuilder::<Int8Type, Float64Type>::new();
3820        for v in values {
3821            match v {
3822                Some(val) => builder.append_value(val),
3823                None => builder.append_null(),
3824            }
3825        }
3826        Arc::new(builder.finish())
3827    }
3828
3829    #[test]
3830    fn test_try_new_from_array_dict_haystack_int32() -> Result<()> {
3831        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
3832        let needle = Int32Array::from(vec![1, 2, 3, 4]);
3833        let batch =
3834            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(needle)])?;
3835
3836        let haystack = make_int32_dict_array(vec![Some(1), None, Some(3)]);
3837
3838        let col_a = col("a", &schema)?;
3839        let expr = InListExpr::try_new_from_array(col_a, haystack, false, &schema)?;
3840        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3841        let result = as_boolean_array(&result);
3842        assert_eq!(
3843            result,
3844            &BooleanArray::from(vec![Some(true), None, Some(true), None])
3845        );
3846
3847        Ok(())
3848    }
3849
3850    #[test]
3851    fn test_in_list_from_array_type_mismatch_errors() -> Result<()> {
3852        // Utf8 needle, Dict(Utf8) in_array: now works with dict haystack support
3853        assert_eq!(
3854            BooleanArray::from(vec![Some(true), Some(false), Some(true)]),
3855            eval_in_list_from_array(
3856                Arc::new(StringArray::from(vec!["a", "d", "b"])),
3857                wrap_in_dict(Arc::new(StringArray::from(vec!["a", "b", "c"]))),
3858            )?
3859        );
3860
3861        // Dict(Utf8) needle, Int64 in_array: type validation rejects at construction
3862        let err = eval_in_list_from_array(
3863            wrap_in_dict(Arc::new(StringArray::from(vec!["a", "d", "b"]))),
3864            Arc::new(Int64Array::from(vec![1, 2, 3])),
3865        )
3866        .unwrap_err()
3867        .to_string();
3868        assert!(err.contains("The data type inlist should be same"), "{err}");
3869
3870        // Dict(Int64) needle, Dict(Utf8) in_array: both Dict but different
3871        // value types, type validation rejects at construction
3872        let err = eval_in_list_from_array(
3873            wrap_in_dict(Arc::new(Int64Array::from(vec![1, 4, 2]))),
3874            wrap_in_dict(Arc::new(StringArray::from(vec!["a", "b", "c"]))),
3875        )
3876        .unwrap_err()
3877        .to_string();
3878        assert!(err.contains("The data type inlist should be same"), "{err}");
3879
3880        Ok(())
3881    }
3882
3883    #[test]
3884    fn test_try_new_from_array_dict_haystack_negated() -> Result<()> {
3885        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
3886        let needle = Int32Array::from(vec![1, 2, 3, 4]);
3887        let batch =
3888            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(needle)])?;
3889
3890        let haystack = make_int32_dict_array(vec![Some(1), None, Some(3)]);
3891
3892        let col_a = col("a", &schema)?;
3893        let expr = InListExpr::try_new_from_array(col_a, haystack, true, &schema)?;
3894        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3895        let result = as_boolean_array(&result);
3896        assert_eq!(
3897            result,
3898            &BooleanArray::from(vec![Some(false), None, Some(false), None])
3899        );
3900
3901        Ok(())
3902    }
3903
3904    #[test]
3905    fn test_try_new_from_array_dict_haystack_utf8() -> Result<()> {
3906        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
3907        let needle = StringArray::from(vec!["a", "b", "c"]);
3908        let batch =
3909            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(needle)])?;
3910
3911        let dict_builder = StringDictionaryBuilder::<Int8Type>::new();
3912        let mut builder = dict_builder;
3913        builder.append_value("a");
3914        builder.append_value("c");
3915        let haystack: ArrayRef = Arc::new(builder.finish());
3916
3917        let col_a = col("a", &schema)?;
3918        let expr = InListExpr::try_new_from_array(col_a, haystack, false, &schema)?;
3919        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3920        let result = as_boolean_array(&result);
3921        assert_eq!(
3922            result,
3923            &BooleanArray::from(vec![Some(true), Some(false), Some(true)])
3924        );
3925
3926        Ok(())
3927    }
3928
3929    #[test]
3930    fn test_try_new_from_array_dict_needle_and_plain_haystack() -> Result<()> {
3931        let schema = Schema::new(vec![Field::new(
3932            "a",
3933            DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
3934            false,
3935        )]);
3936
3937        let needle = make_int32_dict_array(vec![Some(1), Some(2), Some(3), Some(4)]);
3938        let batch =
3939            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::clone(&needle)])?;
3940
3941        let haystack: ArrayRef = Arc::new(Int32Array::from(vec![1, 3]));
3942        let col_a = col("a", &schema)?;
3943        let expr = InListExpr::try_new_from_array(col_a, haystack, false, &schema)?;
3944        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3945        let result = as_boolean_array(&result);
3946        assert_eq!(
3947            result,
3948            &BooleanArray::from(vec![Some(true), Some(false), Some(true), Some(false)])
3949        );
3950
3951        Ok(())
3952    }
3953
3954    #[test]
3955    fn test_try_new_from_array_dict_haystack_float64() -> Result<()> {
3956        let schema = Schema::new(vec![Field::new("a", DataType::Float64, false)]);
3957        let needle = Float64Array::from(vec![1.0, 2.0, 3.0]);
3958        let batch =
3959            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(needle)])?;
3960
3961        let haystack = make_f64_dict_array(vec![Some(1.0), Some(3.0)]);
3962
3963        let col_a = col("a", &schema)?;
3964        let expr = InListExpr::try_new_from_array(col_a, haystack, false, &schema)?;
3965        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
3966        let result = as_boolean_array(&result);
3967        assert_eq!(
3968            result,
3969            &BooleanArray::from(vec![Some(true), Some(false), Some(true)])
3970        );
3971
3972        Ok(())
3973    }
3974
3975    #[test]
3976    fn test_try_new_from_array_dict_haystack_float64_signed_zero() -> Result<()> {
3977        // One value beyond the branchless limit selects the hash-set strategy.
3978        let list_len =
3979            <Float64Type as branchless_filter::BranchlessFilterType>::MAX_LIST_LEN + 1;
3980        let haystack = make_f64_dict_array(vec![Some(-0.0); list_len]);
3981        let needles: ArrayRef = Arc::new(Float64Array::from(vec![0.0]));
3982        for needles in [Arc::clone(&needles), wrap_in_dict(needles)] {
3983            assert_eq!(
3984                eval_in_list_from_array(needles, Arc::clone(&haystack))?,
3985                BooleanArray::from(vec![true])
3986            );
3987        }
3988
3989        Ok(())
3990    }
3991
3992    #[test]
3993    fn test_try_new_from_array_type_mismatch_rejects() -> Result<()> {
3994        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
3995        let col_a = col("a", &schema)?;
3996        let haystack: ArrayRef = Arc::new(Float64Array::from(vec![1.0, 2.0]));
3997
3998        let result = InListExpr::try_new_from_array(col_a, haystack, false, &schema);
3999        assert!(result.is_err());
4000        Ok(())
4001    }
4002
4003    #[test]
4004    fn test_try_new_from_array_struct_haystack() -> Result<()> {
4005        let struct_fields = Fields::from(vec![
4006            Field::new("x", DataType::Int32, false),
4007            Field::new("y", DataType::Utf8, false),
4008        ]);
4009        let struct_dt = DataType::Struct(struct_fields.clone());
4010        let schema = Schema::new(vec![Field::new("a", struct_dt, true)]);
4011
4012        // Needle: [{1,"a"}, {2,"b"}, NULL, {4,"d"}]
4013        let needle = Arc::new(StructArray::new(
4014            struct_fields.clone(),
4015            vec![
4016                Arc::new(Int32Array::from(vec![1, 2, 3, 4])),
4017                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])),
4018            ],
4019            Some(vec![true, true, false, true].into()),
4020        ));
4021        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![needle])?;
4022
4023        // Haystack: [{1,"a"}, {4,"d"}]
4024        let haystack: ArrayRef = Arc::new(StructArray::new(
4025            struct_fields,
4026            vec![
4027                Arc::new(Int32Array::from(vec![1, 4])),
4028                Arc::new(StringArray::from(vec!["a", "d"])),
4029            ],
4030            None,
4031        ));
4032
4033        let col_a = col("a", &schema)?;
4034        let expr = InListExpr::try_new_from_array(
4035            Arc::clone(&col_a),
4036            Arc::clone(&haystack),
4037            false,
4038            &schema,
4039        )?;
4040        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
4041        let result = as_boolean_array(&result);
4042        // {1,"a"} -> true, {2,"b"} -> false, NULL -> NULL, {4,"d"} -> true
4043        assert_eq!(
4044            result,
4045            &BooleanArray::from(vec![Some(true), Some(false), None, Some(true)])
4046        );
4047
4048        // Negated path
4049        let expr = InListExpr::try_new_from_array(col_a, haystack, true, &schema)?;
4050        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
4051        let result = as_boolean_array(&result);
4052        assert_eq!(
4053            result,
4054            &BooleanArray::from(vec![Some(false), Some(true), None, Some(false)])
4055        );
4056
4057        Ok(())
4058    }
4059}
4060
4061#[cfg(all(test, feature = "proto"))]
4062mod proto_tests {
4063    use super::*;
4064    use crate::expressions::{Column, col, lit};
4065    use crate::proto_test_util::{
4066        StubDecoder, StubEncoder, UnreachableDecoder, column_node,
4067    };
4068    use arrow::datatypes::Field;
4069    use datafusion_common::DataFusionError;
4070    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
4071    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
4072    use datafusion_proto_models::protobuf::{
4073        PhysicalExprNode, PhysicalInListNode, physical_expr_node,
4074    };
4075
4076    /// Build an `InListExpr` proto node with the given children.
4077    fn in_list_node(
4078        expr: Option<Box<PhysicalExprNode>>,
4079        list: Vec<PhysicalExprNode>,
4080        negated: bool,
4081    ) -> PhysicalExprNode {
4082        PhysicalExprNode {
4083            expr_id: None,
4084            expr_type: Some(physical_expr_node::ExprType::InList(Box::new(
4085                PhysicalInListNode {
4086                    expr,
4087                    list,
4088                    negated,
4089                },
4090            ))),
4091        }
4092    }
4093
4094    /// An `InListExpr` over a column with one literal value.
4095    fn in_list_fixture(negated: bool) -> InListExpr {
4096        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
4097        InListExpr::try_new(col("a", &schema).unwrap(), vec![lit(1)], negated, &schema)
4098            .unwrap()
4099    }
4100
4101    #[test]
4102    fn try_to_proto_encodes_in_list() {
4103        let in_list = in_list_fixture(false);
4104        let encoder = StubEncoder::ok();
4105        let ctx = PhysicalExprEncodeCtx::new(&encoder);
4106
4107        let node = in_list
4108            .try_to_proto(&ctx)
4109            .unwrap()
4110            .expect("InListExpr should encode to Some(node)");
4111
4112        // Built-in exprs never set expr_id; only dynamic filters do.
4113        assert!(node.expr_id.is_none());
4114        let in_list_node = match node.expr_type {
4115            Some(physical_expr_node::ExprType::InList(boxed)) => *boxed,
4116            other => panic!("expected an InList node, got {other:?}"),
4117        };
4118        assert!(!in_list_node.negated);
4119        assert!(in_list_node.expr.is_some());
4120        assert_eq!(in_list_node.list.len(), 1);
4121
4122        assert!(matches!(
4123            in_list_fixture(true)
4124                .try_to_proto(&ctx)
4125                .unwrap()
4126                .unwrap()
4127                .expr_type,
4128            Some(physical_expr_node::ExprType::InList(node)) if node.negated
4129        ));
4130    }
4131
4132    #[test]
4133    fn try_to_proto_propagates_expr_encode_error() {
4134        let in_list = in_list_fixture(false);
4135        let encoder = StubEncoder::failing_on(1);
4136        let ctx = PhysicalExprEncodeCtx::new(&encoder);
4137        let err = in_list.try_to_proto(&ctx).unwrap_err();
4138        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
4139    }
4140
4141    #[test]
4142    fn try_to_proto_propagates_list_encode_error() {
4143        let in_list = in_list_fixture(false);
4144        // Call 1 is for `expr`, Call 2 is for the first element of `list`
4145        let encoder = StubEncoder::failing_on(2);
4146        let ctx = PhysicalExprEncodeCtx::new(&encoder);
4147        let err = in_list.try_to_proto(&ctx).unwrap_err();
4148        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 2")));
4149    }
4150
4151    #[test]
4152    fn try_from_proto_decodes_in_list() {
4153        let node = in_list_node(
4154            Some(Box::new(column_node("a"))),
4155            vec![column_node("b")],
4156            true,
4157        );
4158        let schema = Schema::new(vec![Field::new("decoded", DataType::Int32, true)]);
4159        let decoder = StubDecoder::ok();
4160        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
4161
4162        let decoded = InListExpr::try_from_proto(&node, &ctx).unwrap();
4163        let in_list = decoded
4164            .downcast_ref::<InListExpr>()
4165            .expect("decoded expr should be an InListExpr");
4166
4167        assert!(in_list.negated());
4168        assert!(in_list.expr().downcast_ref::<Column>().is_some());
4169        assert_eq!(in_list.list().len(), 1);
4170    }
4171
4172    #[test]
4173    fn try_from_proto_rejects_non_in_list_node() {
4174        let node = column_node("a");
4175        let schema = Schema::empty();
4176        let decoder = UnreachableDecoder;
4177        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
4178
4179        let err = InListExpr::try_from_proto(&node, &ctx).unwrap_err();
4180        assert!(matches!(
4181            err,
4182            DataFusionError::Internal(msg) if msg.contains("PhysicalExprNode is not a InList")
4183        ));
4184    }
4185
4186    #[test]
4187    fn try_from_proto_rejects_missing_expr() {
4188        let node = in_list_node(None, vec![column_node("b")], false);
4189        let schema = Schema::empty();
4190        let decoder = UnreachableDecoder;
4191        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
4192
4193        let err = InListExpr::try_from_proto(&node, &ctx).unwrap_err();
4194        assert!(matches!(
4195            err,
4196            DataFusionError::Internal(msg) if msg.contains("InListExpr is missing required field 'expr'")
4197        ));
4198    }
4199
4200    #[test]
4201    fn try_from_proto_propagates_expr_decode_error() {
4202        let node = in_list_node(
4203            Some(Box::new(column_node("a"))),
4204            vec![column_node("b")],
4205            false,
4206        );
4207        let schema = Schema::empty();
4208        let decoder = StubDecoder::failing_on(1);
4209        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
4210        let err = InListExpr::try_from_proto(&node, &ctx).unwrap_err();
4211        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
4212    }
4213
4214    #[test]
4215    fn try_from_proto_propagates_list_decode_error() {
4216        let node = in_list_node(
4217            Some(Box::new(column_node("a"))),
4218            vec![column_node("b")],
4219            false,
4220        );
4221        let schema = Schema::empty();
4222        // Call 1 is `expr`, Call 2 is the first element of `list`
4223        let decoder = StubDecoder::failing_on(2);
4224        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
4225        let err = InListExpr::try_from_proto(&node, &ctx).unwrap_err();
4226        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 2")));
4227    }
4228}