lance_datafusion/
planner.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright The Lance Authors
3
4//! Exec plan planner
5
6use std::borrow::Cow;
7use std::collections::{BTreeSet, VecDeque};
8use std::sync::Arc;
9
10use crate::expr::safe_coerce_scalar;
11use crate::logical_expr::{coerce_filter_type_to_boolean, get_as_string_scalar_opt, resolve_expr};
12use crate::sql::{parse_sql_expr, parse_sql_filter};
13use arrow::compute::CastOptions;
14use arrow_array::ListArray;
15use arrow_buffer::OffsetBuffer;
16use arrow_schema::{DataType as ArrowDataType, Field, SchemaRef, TimeUnit};
17use arrow_select::concat::concat;
18use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion, TreeNodeVisitor};
19use datafusion::common::DFSchema;
20use datafusion::config::ConfigOptions;
21use datafusion::error::Result as DFResult;
22use datafusion::execution::config::SessionConfig;
23use datafusion::execution::context::SessionState;
24use datafusion::execution::runtime_env::RuntimeEnvBuilder;
25use datafusion::execution::session_state::SessionStateBuilder;
26use datafusion::logical_expr::expr::ScalarFunction;
27use datafusion::logical_expr::planner::{ExprPlanner, PlannerResult, RawFieldAccessExpr};
28use datafusion::logical_expr::{
29    AggregateUDF, ColumnarValue, GetFieldAccess, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl,
30    Signature, Volatility, WindowUDF,
31};
32use datafusion::optimizer::simplify_expressions::SimplifyContext;
33use datafusion::sql::planner::{ContextProvider, ParserOptions, PlannerContext, SqlToRel};
34use datafusion::sql::sqlparser::ast::{
35    AccessExpr, Array as SQLArray, BinaryOperator, DataType as SQLDataType, ExactNumberInfo,
36    Expr as SQLExpr, Function, FunctionArg, FunctionArgExpr, FunctionArguments, Ident,
37    ObjectNamePart, Subscript, TimezoneInfo, UnaryOperator, Value, ValueWithSpan,
38};
39use datafusion::{
40    common::Column,
41    logical_expr::{col, Between, BinaryExpr, Like, Operator},
42    physical_expr::execution_props::ExecutionProps,
43    physical_plan::PhysicalExpr,
44    prelude::Expr,
45    scalar::ScalarValue,
46};
47use datafusion_functions::core::getfield::GetFieldFunc;
48use lance_arrow::cast::cast_with_options;
49use lance_core::datatypes::Schema;
50use lance_core::error::LanceOptionExt;
51use snafu::location;
52
53use lance_core::{Error, Result};
54
55#[derive(Debug, Clone)]
56struct CastListF16Udf {
57    signature: Signature,
58}
59
60impl CastListF16Udf {
61    pub fn new() -> Self {
62        Self {
63            signature: Signature::any(1, Volatility::Immutable),
64        }
65    }
66}
67
68impl ScalarUDFImpl for CastListF16Udf {
69    fn as_any(&self) -> &dyn std::any::Any {
70        self
71    }
72
73    fn name(&self) -> &str {
74        "_cast_list_f16"
75    }
76
77    fn signature(&self) -> &Signature {
78        &self.signature
79    }
80
81    fn return_type(&self, arg_types: &[ArrowDataType]) -> DFResult<ArrowDataType> {
82        let input = &arg_types[0];
83        match input {
84            ArrowDataType::FixedSizeList(field, size) => {
85                if field.data_type() != &ArrowDataType::Float32
86                    && field.data_type() != &ArrowDataType::Float16
87                {
88                    return Err(datafusion::error::DataFusionError::Execution(
89                        "cast_list_f16 only supports list of float32 or float16".to_string(),
90                    ));
91                }
92                Ok(ArrowDataType::FixedSizeList(
93                    Arc::new(Field::new(
94                        field.name(),
95                        ArrowDataType::Float16,
96                        field.is_nullable(),
97                    )),
98                    *size,
99                ))
100            }
101            ArrowDataType::List(field) => {
102                if field.data_type() != &ArrowDataType::Float32
103                    && field.data_type() != &ArrowDataType::Float16
104                {
105                    return Err(datafusion::error::DataFusionError::Execution(
106                        "cast_list_f16 only supports list of float32 or float16".to_string(),
107                    ));
108                }
109                Ok(ArrowDataType::List(Arc::new(Field::new(
110                    field.name(),
111                    ArrowDataType::Float16,
112                    field.is_nullable(),
113                ))))
114            }
115            _ => Err(datafusion::error::DataFusionError::Execution(
116                "cast_list_f16 only supports FixedSizeList/List arguments".to_string(),
117            )),
118        }
119    }
120
121    fn invoke_with_args(&self, func_args: ScalarFunctionArgs) -> DFResult<ColumnarValue> {
122        let ColumnarValue::Array(arr) = &func_args.args[0] else {
123            return Err(datafusion::error::DataFusionError::Execution(
124                "cast_list_f16 only supports array arguments".to_string(),
125            ));
126        };
127
128        let to_type = match arr.data_type() {
129            ArrowDataType::FixedSizeList(field, size) => ArrowDataType::FixedSizeList(
130                Arc::new(Field::new(
131                    field.name(),
132                    ArrowDataType::Float16,
133                    field.is_nullable(),
134                )),
135                *size,
136            ),
137            ArrowDataType::List(field) => ArrowDataType::List(Arc::new(Field::new(
138                field.name(),
139                ArrowDataType::Float16,
140                field.is_nullable(),
141            ))),
142            _ => {
143                return Err(datafusion::error::DataFusionError::Execution(
144                    "cast_list_f16 only supports array arguments".to_string(),
145                ));
146            }
147        };
148
149        let res = cast_with_options(arr.as_ref(), &to_type, &CastOptions::default())?;
150        Ok(ColumnarValue::Array(res))
151    }
152}
153
154// Adapter that instructs datafusion how lance expects expressions to be interpreted
155struct LanceContextProvider {
156    options: datafusion::config::ConfigOptions,
157    state: SessionState,
158    expr_planners: Vec<Arc<dyn ExprPlanner>>,
159}
160
161impl Default for LanceContextProvider {
162    fn default() -> Self {
163        let config = SessionConfig::new();
164        let runtime = RuntimeEnvBuilder::new().build_arc().unwrap();
165        let mut state_builder = SessionStateBuilder::new()
166            .with_config(config)
167            .with_runtime_env(runtime)
168            .with_default_features();
169
170        // SessionState does not expose expr_planners, so we need to get the default ones from
171        // the builder and store them to return from get_expr_planners
172
173        // unwrap safe because with_default_features sets expr_planners
174        let expr_planners = state_builder.expr_planners().as_ref().unwrap().clone();
175
176        Self {
177            options: ConfigOptions::default(),
178            state: state_builder.build(),
179            expr_planners,
180        }
181    }
182}
183
184impl ContextProvider for LanceContextProvider {
185    fn get_table_source(
186        &self,
187        name: datafusion::sql::TableReference,
188    ) -> DFResult<Arc<dyn datafusion::logical_expr::TableSource>> {
189        Err(datafusion::error::DataFusionError::NotImplemented(format!(
190            "Attempt to reference inner table {} not supported",
191            name
192        )))
193    }
194
195    fn get_aggregate_meta(&self, name: &str) -> Option<Arc<AggregateUDF>> {
196        self.state.aggregate_functions().get(name).cloned()
197    }
198
199    fn get_window_meta(&self, name: &str) -> Option<Arc<WindowUDF>> {
200        self.state.window_functions().get(name).cloned()
201    }
202
203    fn get_function_meta(&self, f: &str) -> Option<Arc<ScalarUDF>> {
204        match f {
205            // TODO: cast should go thru CAST syntax instead of UDF
206            // Going thru UDF makes it hard for the optimizer to find no-ops
207            "_cast_list_f16" => Some(Arc::new(ScalarUDF::new_from_impl(CastListF16Udf::new()))),
208            _ => self.state.scalar_functions().get(f).cloned(),
209        }
210    }
211
212    fn get_variable_type(&self, _: &[String]) -> Option<ArrowDataType> {
213        // Variables (things like @@LANGUAGE) not supported
214        None
215    }
216
217    fn options(&self) -> &datafusion::config::ConfigOptions {
218        &self.options
219    }
220
221    fn udf_names(&self) -> Vec<String> {
222        self.state.scalar_functions().keys().cloned().collect()
223    }
224
225    fn udaf_names(&self) -> Vec<String> {
226        self.state.aggregate_functions().keys().cloned().collect()
227    }
228
229    fn udwf_names(&self) -> Vec<String> {
230        self.state.window_functions().keys().cloned().collect()
231    }
232
233    fn get_expr_planners(&self) -> &[Arc<dyn ExprPlanner>] {
234        &self.expr_planners
235    }
236}
237
238pub struct Planner {
239    schema: SchemaRef,
240    context_provider: LanceContextProvider,
241    enable_relations: bool,
242}
243
244impl Planner {
245    pub fn new(schema: SchemaRef) -> Self {
246        Self {
247            schema,
248            context_provider: LanceContextProvider::default(),
249            enable_relations: false,
250        }
251    }
252
253    /// If passed with `true`, then the first identifier in column reference
254    /// is parsed as the relation. For example, `table.field.inner` will be
255    /// read as the nested field `field.inner` (`inner` on struct field `field`)
256    /// on the `table` relation. If `false` (the default), then no relations
257    /// are used and all identifiers are assumed to be a nested column path.
258    pub fn with_enable_relations(mut self, enable_relations: bool) -> Self {
259        self.enable_relations = enable_relations;
260        self
261    }
262
263    fn column(&self, idents: &[Ident]) -> Expr {
264        fn handle_remaining_idents(expr: &mut Expr, idents: &[Ident]) {
265            for ident in idents {
266                *expr = Expr::ScalarFunction(ScalarFunction {
267                    args: vec![
268                        std::mem::take(expr),
269                        Expr::Literal(ScalarValue::Utf8(Some(ident.value.clone())), None),
270                    ],
271                    func: Arc::new(ScalarUDF::new_from_impl(GetFieldFunc::default())),
272                });
273            }
274        }
275
276        if self.enable_relations && idents.len() > 1 {
277            // Create qualified column reference (relation.column)
278            let relation = &idents[0].value;
279            let column_name = &idents[1].value;
280            let column = Expr::Column(Column::new(Some(relation.clone()), column_name.clone()));
281            let mut result = column;
282            handle_remaining_idents(&mut result, &idents[2..]);
283            result
284        } else {
285            // Default behavior - treat as struct field access
286            let mut column = col(&idents[0].value);
287            handle_remaining_idents(&mut column, &idents[1..]);
288            column
289        }
290    }
291
292    fn binary_op(&self, op: &BinaryOperator) -> Result<Operator> {
293        Ok(match op {
294            BinaryOperator::Plus => Operator::Plus,
295            BinaryOperator::Minus => Operator::Minus,
296            BinaryOperator::Multiply => Operator::Multiply,
297            BinaryOperator::Divide => Operator::Divide,
298            BinaryOperator::Modulo => Operator::Modulo,
299            BinaryOperator::StringConcat => Operator::StringConcat,
300            BinaryOperator::Gt => Operator::Gt,
301            BinaryOperator::Lt => Operator::Lt,
302            BinaryOperator::GtEq => Operator::GtEq,
303            BinaryOperator::LtEq => Operator::LtEq,
304            BinaryOperator::Eq => Operator::Eq,
305            BinaryOperator::NotEq => Operator::NotEq,
306            BinaryOperator::And => Operator::And,
307            BinaryOperator::Or => Operator::Or,
308            _ => {
309                return Err(Error::invalid_input(
310                    format!("Operator {op} is not supported"),
311                    location!(),
312                ));
313            }
314        })
315    }
316
317    fn binary_expr(&self, left: &SQLExpr, op: &BinaryOperator, right: &SQLExpr) -> Result<Expr> {
318        Ok(Expr::BinaryExpr(BinaryExpr::new(
319            Box::new(self.parse_sql_expr(left)?),
320            self.binary_op(op)?,
321            Box::new(self.parse_sql_expr(right)?),
322        )))
323    }
324
325    fn unary_expr(&self, op: &UnaryOperator, expr: &SQLExpr) -> Result<Expr> {
326        Ok(match op {
327            UnaryOperator::Not | UnaryOperator::PGBitwiseNot => {
328                Expr::Not(Box::new(self.parse_sql_expr(expr)?))
329            }
330
331            UnaryOperator::Minus => {
332                use datafusion::logical_expr::lit;
333                match expr {
334                    SQLExpr::Value(ValueWithSpan { value: Value::Number(n, _), ..}) => match n.parse::<i64>() {
335                        Ok(n) => lit(-n),
336                        Err(_) => lit(-n
337                            .parse::<f64>()
338                            .map_err(|_e| {
339                                Error::invalid_input(
340                                    format!("negative operator can be only applied to integer and float operands, got: {n}"),
341                                    location!(),
342                                )
343                            })?),
344                    },
345                    _ => {
346                        Expr::Negative(Box::new(self.parse_sql_expr(expr)?))
347                    }
348                }
349            }
350
351            _ => {
352                return Err(Error::invalid_input(
353                    format!("Unary operator '{:?}' is not supported", op),
354                    location!(),
355                ));
356            }
357        })
358    }
359
360    // See datafusion `sqlToRel::parse_sql_number()`
361    fn number(&self, value: &str, negative: bool) -> Result<Expr> {
362        use datafusion::logical_expr::lit;
363        let value: Cow<str> = if negative {
364            Cow::Owned(format!("-{}", value))
365        } else {
366            Cow::Borrowed(value)
367        };
368        if let Ok(n) = value.parse::<i64>() {
369            Ok(lit(n))
370        } else {
371            value.parse::<f64>().map(lit).map_err(|_| {
372                Error::invalid_input(
373                    format!("'{value}' is not supported number value."),
374                    location!(),
375                )
376            })
377        }
378    }
379
380    fn value(&self, value: &Value) -> Result<Expr> {
381        Ok(match value {
382            Value::Number(v, _) => self.number(v.as_str(), false)?,
383            Value::SingleQuotedString(s) => Expr::Literal(ScalarValue::Utf8(Some(s.clone())), None),
384            Value::HexStringLiteral(hsl) => {
385                Expr::Literal(ScalarValue::Binary(Self::try_decode_hex_literal(hsl)), None)
386            }
387            Value::DoubleQuotedString(s) => Expr::Literal(ScalarValue::Utf8(Some(s.clone())), None),
388            Value::Boolean(v) => Expr::Literal(ScalarValue::Boolean(Some(*v)), None),
389            Value::Null => Expr::Literal(ScalarValue::Null, None),
390            _ => todo!(),
391        })
392    }
393
394    fn parse_function_args(&self, func_args: &FunctionArg) -> Result<Expr> {
395        match func_args {
396            FunctionArg::Unnamed(FunctionArgExpr::Expr(expr)) => self.parse_sql_expr(expr),
397            _ => Err(Error::invalid_input(
398                format!("Unsupported function args: {:?}", func_args),
399                location!(),
400            )),
401        }
402    }
403
404    // We now use datafusion to parse functions.  This allows us to use datafusion's
405    // entire collection of functions (previously we had just hard-coded support for two functions).
406    //
407    // Unfortunately, one of those two functions was is_valid and the reason we needed it was because
408    // this is a function that comes from duckdb.  Datafusion does not consider is_valid to be a function
409    // but rather an AST node (Expr::IsNotNull) and so we need to handle this case specially.
410    fn legacy_parse_function(&self, func: &Function) -> Result<Expr> {
411        match &func.args {
412            FunctionArguments::List(args) => {
413                if func.name.0.len() != 1 {
414                    return Err(Error::invalid_input(
415                        format!("Function name must have 1 part, got: {:?}", func.name.0),
416                        location!(),
417                    ));
418                }
419                Ok(Expr::IsNotNull(Box::new(
420                    self.parse_function_args(&args.args[0])?,
421                )))
422            }
423            _ => Err(Error::invalid_input(
424                format!("Unsupported function args: {:?}", &func.args),
425                location!(),
426            )),
427        }
428    }
429
430    fn parse_function(&self, function: SQLExpr) -> Result<Expr> {
431        if let SQLExpr::Function(function) = &function {
432            if let Some(ObjectNamePart::Identifier(name)) = &function.name.0.first() {
433                if &name.value == "is_valid" {
434                    return self.legacy_parse_function(function);
435                }
436            }
437        }
438        let sql_to_rel = SqlToRel::new_with_options(
439            &self.context_provider,
440            ParserOptions {
441                parse_float_as_decimal: false,
442                enable_ident_normalization: false,
443                support_varchar_with_length: false,
444                enable_options_value_normalization: false,
445                collect_spans: false,
446                map_varchar_to_utf8view: false,
447            },
448        );
449
450        let mut planner_context = PlannerContext::default();
451        let schema = DFSchema::try_from(self.schema.as_ref().clone())?;
452        sql_to_rel
453            .sql_to_expr(function, &schema, &mut planner_context)
454            .map_err(|e| Error::invalid_input(format!("Error parsing function: {e}"), location!()))
455    }
456
457    fn parse_type(&self, data_type: &SQLDataType) -> Result<ArrowDataType> {
458        const SUPPORTED_TYPES: [&str; 13] = [
459            "int [unsigned]",
460            "tinyint [unsigned]",
461            "smallint [unsigned]",
462            "bigint [unsigned]",
463            "float",
464            "double",
465            "string",
466            "binary",
467            "date",
468            "timestamp(precision)",
469            "datetime(precision)",
470            "decimal(precision,scale)",
471            "boolean",
472        ];
473        match data_type {
474            SQLDataType::String(_) => Ok(ArrowDataType::Utf8),
475            SQLDataType::Binary(_) => Ok(ArrowDataType::Binary),
476            SQLDataType::Float(_) => Ok(ArrowDataType::Float32),
477            SQLDataType::Double(_) => Ok(ArrowDataType::Float64),
478            SQLDataType::Boolean => Ok(ArrowDataType::Boolean),
479            SQLDataType::TinyInt(_) => Ok(ArrowDataType::Int8),
480            SQLDataType::SmallInt(_) => Ok(ArrowDataType::Int16),
481            SQLDataType::Int(_) | SQLDataType::Integer(_) => Ok(ArrowDataType::Int32),
482            SQLDataType::BigInt(_) => Ok(ArrowDataType::Int64),
483            SQLDataType::TinyIntUnsigned(_) => Ok(ArrowDataType::UInt8),
484            SQLDataType::SmallIntUnsigned(_) => Ok(ArrowDataType::UInt16),
485            SQLDataType::IntUnsigned(_) | SQLDataType::IntegerUnsigned(_) => {
486                Ok(ArrowDataType::UInt32)
487            }
488            SQLDataType::BigIntUnsigned(_) => Ok(ArrowDataType::UInt64),
489            SQLDataType::Date => Ok(ArrowDataType::Date32),
490            SQLDataType::Timestamp(resolution, tz) => {
491                match tz {
492                    TimezoneInfo::None => {}
493                    _ => {
494                        return Err(Error::invalid_input(
495                            "Timezone not supported in timestamp".to_string(),
496                            location!(),
497                        ));
498                    }
499                };
500                let time_unit = match resolution {
501                    // Default to microsecond to match PyArrow
502                    None => TimeUnit::Microsecond,
503                    Some(0) => TimeUnit::Second,
504                    Some(3) => TimeUnit::Millisecond,
505                    Some(6) => TimeUnit::Microsecond,
506                    Some(9) => TimeUnit::Nanosecond,
507                    _ => {
508                        return Err(Error::invalid_input(
509                            format!("Unsupported datetime resolution: {:?}", resolution),
510                            location!(),
511                        ));
512                    }
513                };
514                Ok(ArrowDataType::Timestamp(time_unit, None))
515            }
516            SQLDataType::Datetime(resolution) => {
517                let time_unit = match resolution {
518                    None => TimeUnit::Microsecond,
519                    Some(0) => TimeUnit::Second,
520                    Some(3) => TimeUnit::Millisecond,
521                    Some(6) => TimeUnit::Microsecond,
522                    Some(9) => TimeUnit::Nanosecond,
523                    _ => {
524                        return Err(Error::invalid_input(
525                            format!("Unsupported datetime resolution: {:?}", resolution),
526                            location!(),
527                        ));
528                    }
529                };
530                Ok(ArrowDataType::Timestamp(time_unit, None))
531            }
532            SQLDataType::Decimal(number_info) => match number_info {
533                ExactNumberInfo::PrecisionAndScale(precision, scale) => {
534                    Ok(ArrowDataType::Decimal128(*precision as u8, *scale as i8))
535                }
536                _ => Err(Error::invalid_input(
537                    format!(
538                        "Must provide precision and scale for decimal: {:?}",
539                        number_info
540                    ),
541                    location!(),
542                )),
543            },
544            _ => Err(Error::invalid_input(
545                format!(
546                    "Unsupported data type: {:?}. Supported types: {:?}",
547                    data_type, SUPPORTED_TYPES
548                ),
549                location!(),
550            )),
551        }
552    }
553
554    fn plan_field_access(&self, mut field_access_expr: RawFieldAccessExpr) -> Result<Expr> {
555        let df_schema = DFSchema::try_from(self.schema.as_ref().clone())?;
556        for planner in self.context_provider.get_expr_planners() {
557            match planner.plan_field_access(field_access_expr, &df_schema)? {
558                PlannerResult::Planned(expr) => return Ok(expr),
559                PlannerResult::Original(expr) => {
560                    field_access_expr = expr;
561                }
562            }
563        }
564        Err(Error::invalid_input(
565            "Field access could not be planned",
566            location!(),
567        ))
568    }
569
570    fn parse_sql_expr(&self, expr: &SQLExpr) -> Result<Expr> {
571        match expr {
572            SQLExpr::Identifier(id) => {
573                // Users can pass string literals wrapped in `"`.
574                // (Normally SQL only allows single quotes.)
575                if id.quote_style == Some('"') {
576                    Ok(Expr::Literal(
577                        ScalarValue::Utf8(Some(id.value.clone())),
578                        None,
579                    ))
580                // Users can wrap identifiers with ` to reference non-standard
581                // names, such as uppercase or spaces.
582                } else if id.quote_style == Some('`') {
583                    Ok(Expr::Column(Column::from_name(id.value.clone())))
584                } else {
585                    Ok(self.column(vec![id.clone()].as_slice()))
586                }
587            }
588            SQLExpr::CompoundIdentifier(ids) => Ok(self.column(ids.as_slice())),
589            SQLExpr::BinaryOp { left, op, right } => self.binary_expr(left, op, right),
590            SQLExpr::UnaryOp { op, expr } => self.unary_expr(op, expr),
591            SQLExpr::Value(value) => self.value(&value.value),
592            SQLExpr::Array(SQLArray { elem, .. }) => {
593                let mut values = vec![];
594
595                let array_literal_error = |pos: usize, value: &_| {
596                    Err(Error::invalid_input(
597                        format!(
598                            "Expected a literal value in array, instead got {} at position {}",
599                            value, pos
600                        ),
601                        location!(),
602                    ))
603                };
604
605                for (pos, expr) in elem.iter().enumerate() {
606                    match expr {
607                        SQLExpr::Value(value) => {
608                            if let Expr::Literal(value, _) = self.value(&value.value)? {
609                                values.push(value);
610                            } else {
611                                return array_literal_error(pos, expr);
612                            }
613                        }
614                        SQLExpr::UnaryOp {
615                            op: UnaryOperator::Minus,
616                            expr,
617                        } => {
618                            if let SQLExpr::Value(ValueWithSpan {
619                                value: Value::Number(number, _),
620                                ..
621                            }) = expr.as_ref()
622                            {
623                                if let Expr::Literal(value, _) = self.number(number, true)? {
624                                    values.push(value);
625                                } else {
626                                    return array_literal_error(pos, expr);
627                                }
628                            } else {
629                                return array_literal_error(pos, expr);
630                            }
631                        }
632                        _ => {
633                            return array_literal_error(pos, expr);
634                        }
635                    }
636                }
637
638                let field = if !values.is_empty() {
639                    let data_type = values[0].data_type();
640
641                    for value in &mut values {
642                        if value.data_type() != data_type {
643                            *value = safe_coerce_scalar(value, &data_type).ok_or_else(|| Error::invalid_input(
644                                format!("Array expressions must have a consistent datatype. Expected: {}, got: {}", data_type, value.data_type()),
645                                location!()
646                            ))?;
647                        }
648                    }
649                    Field::new("item", data_type, true)
650                } else {
651                    Field::new("item", ArrowDataType::Null, true)
652                };
653
654                let values = values
655                    .into_iter()
656                    .map(|v| v.to_array().map_err(Error::from))
657                    .collect::<Result<Vec<_>>>()?;
658                let array_refs = values.iter().map(|v| v.as_ref()).collect::<Vec<_>>();
659                let values = concat(&array_refs)?;
660                let values = ListArray::try_new(
661                    field.into(),
662                    OffsetBuffer::from_lengths([values.len()]),
663                    values,
664                    None,
665                )?;
666
667                Ok(Expr::Literal(ScalarValue::List(Arc::new(values)), None))
668            }
669            // For example, DATE '2020-01-01'
670            SQLExpr::TypedString { data_type, value } => {
671                let value = value.clone().into_string().expect_ok()?;
672                Ok(Expr::Cast(datafusion::logical_expr::Cast {
673                    expr: Box::new(Expr::Literal(ScalarValue::Utf8(Some(value)), None)),
674                    data_type: self.parse_type(data_type)?,
675                }))
676            }
677            SQLExpr::IsFalse(expr) => Ok(Expr::IsFalse(Box::new(self.parse_sql_expr(expr)?))),
678            SQLExpr::IsNotFalse(expr) => Ok(Expr::IsNotFalse(Box::new(self.parse_sql_expr(expr)?))),
679            SQLExpr::IsTrue(expr) => Ok(Expr::IsTrue(Box::new(self.parse_sql_expr(expr)?))),
680            SQLExpr::IsNotTrue(expr) => Ok(Expr::IsNotTrue(Box::new(self.parse_sql_expr(expr)?))),
681            SQLExpr::IsNull(expr) => Ok(Expr::IsNull(Box::new(self.parse_sql_expr(expr)?))),
682            SQLExpr::IsNotNull(expr) => Ok(Expr::IsNotNull(Box::new(self.parse_sql_expr(expr)?))),
683            SQLExpr::InList {
684                expr,
685                list,
686                negated,
687            } => {
688                let value_expr = self.parse_sql_expr(expr)?;
689                let list_exprs = list
690                    .iter()
691                    .map(|e| self.parse_sql_expr(e))
692                    .collect::<Result<Vec<_>>>()?;
693                Ok(value_expr.in_list(list_exprs, *negated))
694            }
695            SQLExpr::Nested(inner) => self.parse_sql_expr(inner.as_ref()),
696            SQLExpr::Function(_) => self.parse_function(expr.clone()),
697            SQLExpr::ILike {
698                negated,
699                expr,
700                pattern,
701                escape_char,
702                any: _,
703            } => Ok(Expr::Like(Like::new(
704                *negated,
705                Box::new(self.parse_sql_expr(expr)?),
706                Box::new(self.parse_sql_expr(pattern)?),
707                escape_char.as_ref().and_then(|c| c.chars().next()),
708                true,
709            ))),
710            SQLExpr::Like {
711                negated,
712                expr,
713                pattern,
714                escape_char,
715                any: _,
716            } => Ok(Expr::Like(Like::new(
717                *negated,
718                Box::new(self.parse_sql_expr(expr)?),
719                Box::new(self.parse_sql_expr(pattern)?),
720                escape_char.as_ref().and_then(|c| c.chars().next()),
721                false,
722            ))),
723            SQLExpr::Cast {
724                expr, data_type, ..
725            } => Ok(Expr::Cast(datafusion::logical_expr::Cast {
726                expr: Box::new(self.parse_sql_expr(expr)?),
727                data_type: self.parse_type(data_type)?,
728            })),
729            SQLExpr::JsonAccess { .. } => Err(Error::invalid_input(
730                "JSON access is not supported",
731                location!(),
732            )),
733            SQLExpr::CompoundFieldAccess { root, access_chain } => {
734                let mut expr = self.parse_sql_expr(root)?;
735
736                for access in access_chain {
737                    let field_access = match access {
738                        // x.y or x['y']
739                        AccessExpr::Dot(SQLExpr::Identifier(Ident { value: s, .. }))
740                        | AccessExpr::Subscript(Subscript::Index {
741                            index:
742                                SQLExpr::Value(ValueWithSpan {
743                                    value:
744                                        Value::SingleQuotedString(s) | Value::DoubleQuotedString(s),
745                                    ..
746                                }),
747                        }) => GetFieldAccess::NamedStructField {
748                            name: ScalarValue::from(s.as_str()),
749                        },
750                        AccessExpr::Subscript(Subscript::Index { index }) => {
751                            let key = Box::new(self.parse_sql_expr(index)?);
752                            GetFieldAccess::ListIndex { key }
753                        }
754                        AccessExpr::Subscript(Subscript::Slice { .. }) => {
755                            return Err(Error::invalid_input(
756                                "Slice subscript is not supported",
757                                location!(),
758                            ));
759                        }
760                        _ => {
761                            // Handle other cases like JSON access
762                            // Note: JSON access is not supported in lance
763                            return Err(Error::invalid_input(
764                                "Only dot notation or index access is supported for field access",
765                                location!(),
766                            ));
767                        }
768                    };
769
770                    let field_access_expr = RawFieldAccessExpr { expr, field_access };
771                    expr = self.plan_field_access(field_access_expr)?;
772                }
773
774                Ok(expr)
775            }
776            SQLExpr::Between {
777                expr,
778                negated,
779                low,
780                high,
781            } => {
782                // Parse the main expression and bounds
783                let expr = self.parse_sql_expr(expr)?;
784                let low = self.parse_sql_expr(low)?;
785                let high = self.parse_sql_expr(high)?;
786
787                let between = Expr::Between(Between::new(
788                    Box::new(expr),
789                    *negated,
790                    Box::new(low),
791                    Box::new(high),
792                ));
793                Ok(between)
794            }
795            _ => Err(Error::invalid_input(
796                format!("Expression '{expr}' is not supported SQL in lance"),
797                location!(),
798            )),
799        }
800    }
801
802    /// Create Logical [Expr] from a SQL filter clause.
803    ///
804    /// Note: the returned expression must be passed through [optimize_expr()]
805    /// before being passed to [create_physical_expr()].
806    pub fn parse_filter(&self, filter: &str) -> Result<Expr> {
807        // Allow sqlparser to parse filter as part of ONE SQL statement.
808        let ast_expr = parse_sql_filter(filter)?;
809        let expr = self.parse_sql_expr(&ast_expr)?;
810        let schema = Schema::try_from(self.schema.as_ref())?;
811        let resolved = resolve_expr(&expr, &schema).map_err(|e| {
812            Error::invalid_input(
813                format!("Error resolving filter expression {filter}: {e}"),
814                location!(),
815            )
816        })?;
817
818        Ok(coerce_filter_type_to_boolean(resolved))
819    }
820
821    /// Create Logical [Expr] from a SQL expression.
822    ///
823    /// Note: the returned expression must be passed through [optimize_filter()]
824    /// before being passed to [create_physical_expr()].
825    pub fn parse_expr(&self, expr: &str) -> Result<Expr> {
826        let ast_expr = parse_sql_expr(expr)?;
827        let expr = self.parse_sql_expr(&ast_expr)?;
828        let schema = Schema::try_from(self.schema.as_ref())?;
829        let resolved = resolve_expr(&expr, &schema)?;
830        Ok(resolved)
831    }
832
833    /// Try to decode bytes from hex literal string.
834    ///
835    /// Copied from datafusion because this is not public.
836    ///
837    /// TODO: use SqlToRel from Datafusion directly?
838    fn try_decode_hex_literal(s: &str) -> Option<Vec<u8>> {
839        let hex_bytes = s.as_bytes();
840        let mut decoded_bytes = Vec::with_capacity(hex_bytes.len().div_ceil(2));
841
842        let start_idx = hex_bytes.len() % 2;
843        if start_idx > 0 {
844            // The first byte is formed of only one char.
845            decoded_bytes.push(Self::try_decode_hex_char(hex_bytes[0])?);
846        }
847
848        for i in (start_idx..hex_bytes.len()).step_by(2) {
849            let high = Self::try_decode_hex_char(hex_bytes[i])?;
850            let low = Self::try_decode_hex_char(hex_bytes[i + 1])?;
851            decoded_bytes.push((high << 4) | low);
852        }
853
854        Some(decoded_bytes)
855    }
856
857    /// Try to decode a byte from a hex char.
858    ///
859    /// None will be returned if the input char is hex-invalid.
860    const fn try_decode_hex_char(c: u8) -> Option<u8> {
861        match c {
862            b'A'..=b'F' => Some(c - b'A' + 10),
863            b'a'..=b'f' => Some(c - b'a' + 10),
864            b'0'..=b'9' => Some(c - b'0'),
865            _ => None,
866        }
867    }
868
869    /// Optimize the filter expression and coerce data types.
870    pub fn optimize_expr(&self, expr: Expr) -> Result<Expr> {
871        let df_schema = Arc::new(DFSchema::try_from(self.schema.as_ref().clone())?);
872
873        // DataFusion needs the simplify and coerce passes to be applied before
874        // expressions can be handled by the physical planner.
875        let props = ExecutionProps::default();
876        let simplify_context = SimplifyContext::new(&props).with_schema(df_schema.clone());
877        let simplifier =
878            datafusion::optimizer::simplify_expressions::ExprSimplifier::new(simplify_context);
879
880        let expr = simplifier.simplify(expr)?;
881        let expr = simplifier.coerce(expr, &df_schema)?;
882
883        Ok(expr)
884    }
885
886    /// Create the [`PhysicalExpr`] from a logical [`Expr`]
887    pub fn create_physical_expr(&self, expr: &Expr) -> Result<Arc<dyn PhysicalExpr>> {
888        let df_schema = Arc::new(DFSchema::try_from(self.schema.as_ref().clone())?);
889        Ok(datafusion::physical_expr::create_physical_expr(
890            expr,
891            df_schema.as_ref(),
892            &Default::default(),
893        )?)
894    }
895
896    /// Collect the columns in the expression.
897    ///
898    /// The columns are returned in sorted order.
899    ///
900    /// If the expr refers to nested columns these will be returned
901    /// as dotted paths (x.y.z)
902    pub fn column_names_in_expr(expr: &Expr) -> Vec<String> {
903        let mut visitor = ColumnCapturingVisitor {
904            current_path: VecDeque::new(),
905            columns: BTreeSet::new(),
906        };
907        expr.visit(&mut visitor).unwrap();
908        visitor.columns.into_iter().collect()
909    }
910}
911
912struct ColumnCapturingVisitor {
913    // Current column path. If this is empty, we are not in a column expression.
914    current_path: VecDeque<String>,
915    columns: BTreeSet<String>,
916}
917
918impl TreeNodeVisitor<'_> for ColumnCapturingVisitor {
919    type Node = Expr;
920
921    fn f_down(&mut self, node: &Self::Node) -> DFResult<TreeNodeRecursion> {
922        match node {
923            Expr::Column(Column { name, .. }) => {
924                let mut path = name.clone();
925                for part in self.current_path.drain(..) {
926                    path.push('.');
927                    path.push_str(&part);
928                }
929                self.columns.insert(path);
930                self.current_path.clear();
931            }
932            Expr::ScalarFunction(udf) => {
933                if udf.name() == GetFieldFunc::default().name() {
934                    if let Some(name) = get_as_string_scalar_opt(&udf.args[1]) {
935                        self.current_path.push_front(name.to_string())
936                    } else {
937                        self.current_path.clear();
938                    }
939                } else {
940                    self.current_path.clear();
941                }
942            }
943            _ => {
944                self.current_path.clear();
945            }
946        }
947
948        Ok(TreeNodeRecursion::Continue)
949    }
950}
951
952#[cfg(test)]
953mod tests {
954
955    use crate::logical_expr::ExprExt;
956
957    use super::*;
958
959    use arrow::datatypes::Float64Type;
960    use arrow_array::{
961        ArrayRef, BooleanArray, Float32Array, Int32Array, Int64Array, RecordBatch, StringArray,
962        StructArray, TimestampMicrosecondArray, TimestampMillisecondArray,
963        TimestampNanosecondArray, TimestampSecondArray,
964    };
965    use arrow_schema::{DataType, Fields, Schema};
966    use datafusion::{
967        logical_expr::{lit, Cast},
968        prelude::{array_element, get_field},
969    };
970    use datafusion_functions::core::expr_ext::FieldAccessor;
971
972    #[test]
973    fn test_parse_filter_simple() {
974        let schema = Arc::new(Schema::new(vec![
975            Field::new("i", DataType::Int32, false),
976            Field::new("s", DataType::Utf8, true),
977            Field::new(
978                "st",
979                DataType::Struct(Fields::from(vec![
980                    Field::new("x", DataType::Float32, false),
981                    Field::new("y", DataType::Float32, false),
982                ])),
983                true,
984            ),
985        ]));
986
987        let planner = Planner::new(schema.clone());
988
989        let expected = col("i")
990            .gt(lit(3_i32))
991            .and(col("st").field_newstyle("x").lt_eq(lit(5.0_f32)))
992            .and(
993                col("s")
994                    .eq(lit("str-4"))
995                    .or(col("s").in_list(vec![lit("str-4"), lit("str-5")], false)),
996            );
997
998        // double quotes
999        let expr = planner
1000            .parse_filter("i > 3 AND st.x <= 5.0 AND (s == 'str-4' OR s in ('str-4', 'str-5'))")
1001            .unwrap();
1002        assert_eq!(expr, expected);
1003
1004        // single quote
1005        let expr = planner
1006            .parse_filter("i > 3 AND st.x <= 5.0 AND (s = 'str-4' OR s in ('str-4', 'str-5'))")
1007            .unwrap();
1008
1009        let physical_expr = planner.create_physical_expr(&expr).unwrap();
1010
1011        let batch = RecordBatch::try_new(
1012            schema,
1013            vec![
1014                Arc::new(Int32Array::from_iter_values(0..10)) as ArrayRef,
1015                Arc::new(StringArray::from_iter_values(
1016                    (0..10).map(|v| format!("str-{}", v)),
1017                )),
1018                Arc::new(StructArray::from(vec![
1019                    (
1020                        Arc::new(Field::new("x", DataType::Float32, false)),
1021                        Arc::new(Float32Array::from_iter_values((0..10).map(|v| v as f32)))
1022                            as ArrayRef,
1023                    ),
1024                    (
1025                        Arc::new(Field::new("y", DataType::Float32, false)),
1026                        Arc::new(Float32Array::from_iter_values(
1027                            (0..10).map(|v| (v * 10) as f32),
1028                        )),
1029                    ),
1030                ])),
1031            ],
1032        )
1033        .unwrap();
1034        let predicates = physical_expr.evaluate(&batch).unwrap();
1035        assert_eq!(
1036            predicates.into_array(0).unwrap().as_ref(),
1037            &BooleanArray::from(vec![
1038                false, false, false, false, true, true, false, false, false, false
1039            ])
1040        );
1041    }
1042
1043    #[test]
1044    fn test_nested_col_refs() {
1045        let schema = Arc::new(Schema::new(vec![
1046            Field::new("s0", DataType::Utf8, true),
1047            Field::new(
1048                "st",
1049                DataType::Struct(Fields::from(vec![
1050                    Field::new("s1", DataType::Utf8, true),
1051                    Field::new(
1052                        "st",
1053                        DataType::Struct(Fields::from(vec![Field::new(
1054                            "s2",
1055                            DataType::Utf8,
1056                            true,
1057                        )])),
1058                        true,
1059                    ),
1060                ])),
1061                true,
1062            ),
1063        ]));
1064
1065        let planner = Planner::new(schema);
1066
1067        fn assert_column_eq(planner: &Planner, expr: &str, expected: &Expr) {
1068            let expr = planner.parse_filter(&format!("{expr} = 'val'")).unwrap();
1069            assert!(matches!(
1070                expr,
1071                Expr::BinaryExpr(BinaryExpr {
1072                    left: _,
1073                    op: Operator::Eq,
1074                    right: _
1075                })
1076            ));
1077            if let Expr::BinaryExpr(BinaryExpr { left, .. }) = expr {
1078                assert_eq!(left.as_ref(), expected);
1079            }
1080        }
1081
1082        let expected = Expr::Column(Column::new_unqualified("s0"));
1083        assert_column_eq(&planner, "s0", &expected);
1084        assert_column_eq(&planner, "`s0`", &expected);
1085
1086        let expected = Expr::ScalarFunction(ScalarFunction {
1087            func: Arc::new(ScalarUDF::new_from_impl(GetFieldFunc::default())),
1088            args: vec![
1089                Expr::Column(Column::new_unqualified("st")),
1090                Expr::Literal(ScalarValue::Utf8(Some("s1".to_string())), None),
1091            ],
1092        });
1093        assert_column_eq(&planner, "st.s1", &expected);
1094        assert_column_eq(&planner, "`st`.`s1`", &expected);
1095        assert_column_eq(&planner, "st.`s1`", &expected);
1096
1097        let expected = Expr::ScalarFunction(ScalarFunction {
1098            func: Arc::new(ScalarUDF::new_from_impl(GetFieldFunc::default())),
1099            args: vec![
1100                Expr::ScalarFunction(ScalarFunction {
1101                    func: Arc::new(ScalarUDF::new_from_impl(GetFieldFunc::default())),
1102                    args: vec![
1103                        Expr::Column(Column::new_unqualified("st")),
1104                        Expr::Literal(ScalarValue::Utf8(Some("st".to_string())), None),
1105                    ],
1106                }),
1107                Expr::Literal(ScalarValue::Utf8(Some("s2".to_string())), None),
1108            ],
1109        });
1110
1111        assert_column_eq(&planner, "st.st.s2", &expected);
1112        assert_column_eq(&planner, "`st`.`st`.`s2`", &expected);
1113        assert_column_eq(&planner, "st.st.`s2`", &expected);
1114        assert_column_eq(&planner, "st['st'][\"s2\"]", &expected);
1115    }
1116
1117    #[test]
1118    fn test_nested_list_refs() {
1119        let schema = Arc::new(Schema::new(vec![Field::new(
1120            "l",
1121            DataType::List(Arc::new(Field::new(
1122                "item",
1123                DataType::Struct(Fields::from(vec![Field::new("f1", DataType::Utf8, true)])),
1124                true,
1125            ))),
1126            true,
1127        )]));
1128
1129        let planner = Planner::new(schema);
1130
1131        let expected = array_element(col("l"), lit(0_i64));
1132        let expr = planner.parse_expr("l[0]").unwrap();
1133        assert_eq!(expr, expected);
1134
1135        let expected = get_field(array_element(col("l"), lit(0_i64)), "f1");
1136        let expr = planner.parse_expr("l[0]['f1']").unwrap();
1137        assert_eq!(expr, expected);
1138
1139        // FIXME: This should work, but sqlparser doesn't recognize anything
1140        // after the period for some reason.
1141        // let expr = planner.parse_expr("l[0].f1").unwrap();
1142        // assert_eq!(expr, expected);
1143    }
1144
1145    #[test]
1146    fn test_negative_expressions() {
1147        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int64, false)]));
1148
1149        let planner = Planner::new(schema.clone());
1150
1151        let expected = col("x")
1152            .gt(lit(-3_i64))
1153            .and(col("x").lt(-(lit(-5_i64) + lit(3_i64))));
1154
1155        let expr = planner.parse_filter("x > -3 AND x < -(-5 + 3)").unwrap();
1156
1157        assert_eq!(expr, expected);
1158
1159        let physical_expr = planner.create_physical_expr(&expr).unwrap();
1160
1161        let batch = RecordBatch::try_new(
1162            schema,
1163            vec![Arc::new(Int64Array::from_iter_values(-5..5)) as ArrayRef],
1164        )
1165        .unwrap();
1166        let predicates = physical_expr.evaluate(&batch).unwrap();
1167        assert_eq!(
1168            predicates.into_array(0).unwrap().as_ref(),
1169            &BooleanArray::from(vec![
1170                false, false, false, true, true, true, true, false, false, false
1171            ])
1172        );
1173    }
1174
1175    #[test]
1176    fn test_negative_array_expressions() {
1177        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int64, false)]));
1178
1179        let planner = Planner::new(schema);
1180
1181        let expected = Expr::Literal(
1182            ScalarValue::List(Arc::new(
1183                ListArray::from_iter_primitive::<Float64Type, _, _>(vec![Some(
1184                    [-1_f64, -2.0, -3.0, -4.0, -5.0].map(Some),
1185                )]),
1186            )),
1187            None,
1188        );
1189
1190        let expr = planner
1191            .parse_expr("[-1.0, -2.0, -3.0, -4.0, -5.0]")
1192            .unwrap();
1193
1194        assert_eq!(expr, expected);
1195    }
1196
1197    #[test]
1198    fn test_sql_like() {
1199        let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, true)]));
1200
1201        let planner = Planner::new(schema.clone());
1202
1203        let expected = col("s").like(lit("str-4"));
1204        // single quote
1205        let expr = planner.parse_filter("s LIKE 'str-4'").unwrap();
1206        assert_eq!(expr, expected);
1207        let physical_expr = planner.create_physical_expr(&expr).unwrap();
1208
1209        let batch = RecordBatch::try_new(
1210            schema,
1211            vec![Arc::new(StringArray::from_iter_values(
1212                (0..10).map(|v| format!("str-{}", v)),
1213            ))],
1214        )
1215        .unwrap();
1216        let predicates = physical_expr.evaluate(&batch).unwrap();
1217        assert_eq!(
1218            predicates.into_array(0).unwrap().as_ref(),
1219            &BooleanArray::from(vec![
1220                false, false, false, false, true, false, false, false, false, false
1221            ])
1222        );
1223    }
1224
1225    #[test]
1226    fn test_not_like() {
1227        let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, true)]));
1228
1229        let planner = Planner::new(schema.clone());
1230
1231        let expected = col("s").not_like(lit("str-4"));
1232        // single quote
1233        let expr = planner.parse_filter("s NOT LIKE 'str-4'").unwrap();
1234        assert_eq!(expr, expected);
1235        let physical_expr = planner.create_physical_expr(&expr).unwrap();
1236
1237        let batch = RecordBatch::try_new(
1238            schema,
1239            vec![Arc::new(StringArray::from_iter_values(
1240                (0..10).map(|v| format!("str-{}", v)),
1241            ))],
1242        )
1243        .unwrap();
1244        let predicates = physical_expr.evaluate(&batch).unwrap();
1245        assert_eq!(
1246            predicates.into_array(0).unwrap().as_ref(),
1247            &BooleanArray::from(vec![
1248                true, true, true, true, false, true, true, true, true, true
1249            ])
1250        );
1251    }
1252
1253    #[test]
1254    fn test_sql_is_in() {
1255        let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, true)]));
1256
1257        let planner = Planner::new(schema.clone());
1258
1259        let expected = col("s").in_list(vec![lit("str-4"), lit("str-5")], false);
1260        // single quote
1261        let expr = planner.parse_filter("s IN ('str-4', 'str-5')").unwrap();
1262        assert_eq!(expr, expected);
1263        let physical_expr = planner.create_physical_expr(&expr).unwrap();
1264
1265        let batch = RecordBatch::try_new(
1266            schema,
1267            vec![Arc::new(StringArray::from_iter_values(
1268                (0..10).map(|v| format!("str-{}", v)),
1269            ))],
1270        )
1271        .unwrap();
1272        let predicates = physical_expr.evaluate(&batch).unwrap();
1273        assert_eq!(
1274            predicates.into_array(0).unwrap().as_ref(),
1275            &BooleanArray::from(vec![
1276                false, false, false, false, true, true, false, false, false, false
1277            ])
1278        );
1279    }
1280
1281    #[test]
1282    fn test_sql_is_null() {
1283        let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, true)]));
1284
1285        let planner = Planner::new(schema.clone());
1286
1287        let expected = col("s").is_null();
1288        let expr = planner.parse_filter("s IS NULL").unwrap();
1289        assert_eq!(expr, expected);
1290        let physical_expr = planner.create_physical_expr(&expr).unwrap();
1291
1292        let batch = RecordBatch::try_new(
1293            schema,
1294            vec![Arc::new(StringArray::from_iter((0..10).map(|v| {
1295                if v % 3 == 0 {
1296                    Some(format!("str-{}", v))
1297                } else {
1298                    None
1299                }
1300            })))],
1301        )
1302        .unwrap();
1303        let predicates = physical_expr.evaluate(&batch).unwrap();
1304        assert_eq!(
1305            predicates.into_array(0).unwrap().as_ref(),
1306            &BooleanArray::from(vec![
1307                false, true, true, false, true, true, false, true, true, false
1308            ])
1309        );
1310
1311        let expr = planner.parse_filter("s IS NOT NULL").unwrap();
1312        let physical_expr = planner.create_physical_expr(&expr).unwrap();
1313        let predicates = physical_expr.evaluate(&batch).unwrap();
1314        assert_eq!(
1315            predicates.into_array(0).unwrap().as_ref(),
1316            &BooleanArray::from(vec![
1317                true, false, false, true, false, false, true, false, false, true,
1318            ])
1319        );
1320    }
1321
1322    #[test]
1323    fn test_sql_invert() {
1324        let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Boolean, true)]));
1325
1326        let planner = Planner::new(schema.clone());
1327
1328        let expr = planner.parse_filter("NOT s").unwrap();
1329        let physical_expr = planner.create_physical_expr(&expr).unwrap();
1330
1331        let batch = RecordBatch::try_new(
1332            schema,
1333            vec![Arc::new(BooleanArray::from_iter(
1334                (0..10).map(|v| Some(v % 3 == 0)),
1335            ))],
1336        )
1337        .unwrap();
1338        let predicates = physical_expr.evaluate(&batch).unwrap();
1339        assert_eq!(
1340            predicates.into_array(0).unwrap().as_ref(),
1341            &BooleanArray::from(vec![
1342                false, true, true, false, true, true, false, true, true, false
1343            ])
1344        );
1345    }
1346
1347    #[test]
1348    fn test_sql_cast() {
1349        let cases = &[
1350            (
1351                "x = cast('2021-01-01 00:00:00' as timestamp)",
1352                ArrowDataType::Timestamp(TimeUnit::Microsecond, None),
1353            ),
1354            (
1355                "x = cast('2021-01-01 00:00:00' as timestamp(0))",
1356                ArrowDataType::Timestamp(TimeUnit::Second, None),
1357            ),
1358            (
1359                "x = cast('2021-01-01 00:00:00.123' as timestamp(9))",
1360                ArrowDataType::Timestamp(TimeUnit::Nanosecond, None),
1361            ),
1362            (
1363                "x = cast('2021-01-01 00:00:00.123' as datetime(9))",
1364                ArrowDataType::Timestamp(TimeUnit::Nanosecond, None),
1365            ),
1366            ("x = cast('2021-01-01' as date)", ArrowDataType::Date32),
1367            (
1368                "x = cast('1.238' as decimal(9,3))",
1369                ArrowDataType::Decimal128(9, 3),
1370            ),
1371            ("x = cast(1 as float)", ArrowDataType::Float32),
1372            ("x = cast(1 as double)", ArrowDataType::Float64),
1373            ("x = cast(1 as tinyint)", ArrowDataType::Int8),
1374            ("x = cast(1 as smallint)", ArrowDataType::Int16),
1375            ("x = cast(1 as int)", ArrowDataType::Int32),
1376            ("x = cast(1 as integer)", ArrowDataType::Int32),
1377            ("x = cast(1 as bigint)", ArrowDataType::Int64),
1378            ("x = cast(1 as tinyint unsigned)", ArrowDataType::UInt8),
1379            ("x = cast(1 as smallint unsigned)", ArrowDataType::UInt16),
1380            ("x = cast(1 as int unsigned)", ArrowDataType::UInt32),
1381            ("x = cast(1 as integer unsigned)", ArrowDataType::UInt32),
1382            ("x = cast(1 as bigint unsigned)", ArrowDataType::UInt64),
1383            ("x = cast(1 as boolean)", ArrowDataType::Boolean),
1384            ("x = cast(1 as string)", ArrowDataType::Utf8),
1385        ];
1386
1387        for (sql, expected_data_type) in cases {
1388            let schema = Arc::new(Schema::new(vec![Field::new(
1389                "x",
1390                expected_data_type.clone(),
1391                true,
1392            )]));
1393            let planner = Planner::new(schema.clone());
1394            let expr = planner.parse_filter(sql).unwrap();
1395
1396            // Get the thing after 'cast(` but before ' as'.
1397            let expected_value_str = sql
1398                .split("cast(")
1399                .nth(1)
1400                .unwrap()
1401                .split(" as")
1402                .next()
1403                .unwrap();
1404            // Remove any quote marks
1405            let expected_value_str = expected_value_str.trim_matches('\'');
1406
1407            match expr {
1408                Expr::BinaryExpr(BinaryExpr { right, .. }) => match right.as_ref() {
1409                    Expr::Cast(Cast { expr, data_type }) => {
1410                        match expr.as_ref() {
1411                            Expr::Literal(ScalarValue::Utf8(Some(value_str)), _) => {
1412                                assert_eq!(value_str, expected_value_str);
1413                            }
1414                            Expr::Literal(ScalarValue::Int64(Some(value)), _) => {
1415                                assert_eq!(*value, 1);
1416                            }
1417                            _ => panic!("Expected cast to be applied to literal"),
1418                        }
1419                        assert_eq!(data_type, expected_data_type);
1420                    }
1421                    _ => panic!("Expected right to be a cast"),
1422                },
1423                _ => panic!("Expected binary expression"),
1424            }
1425        }
1426    }
1427
1428    #[test]
1429    fn test_sql_literals() {
1430        let cases = &[
1431            (
1432                "x = timestamp '2021-01-01 00:00:00'",
1433                ArrowDataType::Timestamp(TimeUnit::Microsecond, None),
1434            ),
1435            (
1436                "x = timestamp(0) '2021-01-01 00:00:00'",
1437                ArrowDataType::Timestamp(TimeUnit::Second, None),
1438            ),
1439            (
1440                "x = timestamp(9) '2021-01-01 00:00:00.123'",
1441                ArrowDataType::Timestamp(TimeUnit::Nanosecond, None),
1442            ),
1443            ("x = date '2021-01-01'", ArrowDataType::Date32),
1444            ("x = decimal(9,3) '1.238'", ArrowDataType::Decimal128(9, 3)),
1445        ];
1446
1447        for (sql, expected_data_type) in cases {
1448            let schema = Arc::new(Schema::new(vec![Field::new(
1449                "x",
1450                expected_data_type.clone(),
1451                true,
1452            )]));
1453            let planner = Planner::new(schema.clone());
1454            let expr = planner.parse_filter(sql).unwrap();
1455
1456            let expected_value_str = sql.split('\'').nth(1).unwrap();
1457
1458            match expr {
1459                Expr::BinaryExpr(BinaryExpr { right, .. }) => match right.as_ref() {
1460                    Expr::Cast(Cast { expr, data_type }) => {
1461                        match expr.as_ref() {
1462                            Expr::Literal(ScalarValue::Utf8(Some(value_str)), _) => {
1463                                assert_eq!(value_str, expected_value_str);
1464                            }
1465                            _ => panic!("Expected cast to be applied to literal"),
1466                        }
1467                        assert_eq!(data_type, expected_data_type);
1468                    }
1469                    _ => panic!("Expected right to be a cast"),
1470                },
1471                _ => panic!("Expected binary expression"),
1472            }
1473        }
1474    }
1475
1476    #[test]
1477    fn test_sql_array_literals() {
1478        let cases = [
1479            (
1480                "x = [1, 2, 3]",
1481                ArrowDataType::List(Arc::new(Field::new("item", ArrowDataType::Int64, true))),
1482            ),
1483            (
1484                "x = [1, 2, 3]",
1485                ArrowDataType::FixedSizeList(
1486                    Arc::new(Field::new("item", ArrowDataType::Int64, true)),
1487                    3,
1488                ),
1489            ),
1490        ];
1491
1492        for (sql, expected_data_type) in cases {
1493            let schema = Arc::new(Schema::new(vec![Field::new(
1494                "x",
1495                expected_data_type.clone(),
1496                true,
1497            )]));
1498            let planner = Planner::new(schema.clone());
1499            let expr = planner.parse_filter(sql).unwrap();
1500            let expr = planner.optimize_expr(expr).unwrap();
1501
1502            match expr {
1503                Expr::BinaryExpr(BinaryExpr { right, .. }) => match right.as_ref() {
1504                    Expr::Literal(value, _) => {
1505                        assert_eq!(&value.data_type(), &expected_data_type);
1506                    }
1507                    _ => panic!("Expected right to be a literal"),
1508                },
1509                _ => panic!("Expected binary expression"),
1510            }
1511        }
1512    }
1513
1514    #[test]
1515    fn test_sql_between() {
1516        use arrow_array::{Float64Array, Int32Array, TimestampMicrosecondArray};
1517        use arrow_schema::{DataType, Field, Schema, TimeUnit};
1518        use std::sync::Arc;
1519
1520        let schema = Arc::new(Schema::new(vec![
1521            Field::new("x", DataType::Int32, false),
1522            Field::new("y", DataType::Float64, false),
1523            Field::new(
1524                "ts",
1525                DataType::Timestamp(TimeUnit::Microsecond, None),
1526                false,
1527            ),
1528        ]));
1529
1530        let planner = Planner::new(schema.clone());
1531
1532        // Test integer BETWEEN
1533        let expr = planner
1534            .parse_filter("x BETWEEN CAST(3 AS INT) AND CAST(7 AS INT)")
1535            .unwrap();
1536        let physical_expr = planner.create_physical_expr(&expr).unwrap();
1537
1538        // Create timestamp array with values representing:
1539        // 2024-01-01 00:00:00 to 2024-01-01 00:00:09 (in microseconds)
1540        let base_ts = 1704067200000000_i64; // 2024-01-01 00:00:00
1541        let ts_array = TimestampMicrosecondArray::from_iter_values(
1542            (0..10).map(|i| base_ts + i * 1_000_000), // Each value is 1 second apart
1543        );
1544
1545        let batch = RecordBatch::try_new(
1546            schema,
1547            vec![
1548                Arc::new(Int32Array::from_iter_values(0..10)) as ArrayRef,
1549                Arc::new(Float64Array::from_iter_values((0..10).map(|v| v as f64))),
1550                Arc::new(ts_array),
1551            ],
1552        )
1553        .unwrap();
1554
1555        let predicates = physical_expr.evaluate(&batch).unwrap();
1556        assert_eq!(
1557            predicates.into_array(0).unwrap().as_ref(),
1558            &BooleanArray::from(vec![
1559                false, false, false, true, true, true, true, true, false, false
1560            ])
1561        );
1562
1563        // Test NOT BETWEEN
1564        let expr = planner
1565            .parse_filter("x NOT BETWEEN CAST(3 AS INT) AND CAST(7 AS INT)")
1566            .unwrap();
1567        let physical_expr = planner.create_physical_expr(&expr).unwrap();
1568
1569        let predicates = physical_expr.evaluate(&batch).unwrap();
1570        assert_eq!(
1571            predicates.into_array(0).unwrap().as_ref(),
1572            &BooleanArray::from(vec![
1573                true, true, true, false, false, false, false, false, true, true
1574            ])
1575        );
1576
1577        // Test floating point BETWEEN
1578        let expr = planner.parse_filter("y BETWEEN 2.5 AND 6.5").unwrap();
1579        let physical_expr = planner.create_physical_expr(&expr).unwrap();
1580
1581        let predicates = physical_expr.evaluate(&batch).unwrap();
1582        assert_eq!(
1583            predicates.into_array(0).unwrap().as_ref(),
1584            &BooleanArray::from(vec![
1585                false, false, false, true, true, true, true, false, false, false
1586            ])
1587        );
1588
1589        // Test timestamp BETWEEN
1590        let expr = planner
1591            .parse_filter(
1592                "ts BETWEEN timestamp '2024-01-01 00:00:03' AND timestamp '2024-01-01 00:00:07'",
1593            )
1594            .unwrap();
1595        let physical_expr = planner.create_physical_expr(&expr).unwrap();
1596
1597        let predicates = physical_expr.evaluate(&batch).unwrap();
1598        assert_eq!(
1599            predicates.into_array(0).unwrap().as_ref(),
1600            &BooleanArray::from(vec![
1601                false, false, false, true, true, true, true, true, false, false
1602            ])
1603        );
1604    }
1605
1606    #[test]
1607    fn test_sql_comparison() {
1608        // Create a batch with all data types
1609        let batch: Vec<(&str, ArrayRef)> = vec![
1610            (
1611                "timestamp_s",
1612                Arc::new(TimestampSecondArray::from_iter_values(0..10)),
1613            ),
1614            (
1615                "timestamp_ms",
1616                Arc::new(TimestampMillisecondArray::from_iter_values(0..10)),
1617            ),
1618            (
1619                "timestamp_us",
1620                Arc::new(TimestampMicrosecondArray::from_iter_values(0..10)),
1621            ),
1622            (
1623                "timestamp_ns",
1624                Arc::new(TimestampNanosecondArray::from_iter_values(4995..5005)),
1625            ),
1626        ];
1627        let batch = RecordBatch::try_from_iter(batch).unwrap();
1628
1629        let planner = Planner::new(batch.schema());
1630
1631        // Each expression is meant to select the final 5 rows
1632        let expressions = &[
1633            "timestamp_s >= TIMESTAMP '1970-01-01 00:00:05'",
1634            "timestamp_ms >= TIMESTAMP '1970-01-01 00:00:00.005'",
1635            "timestamp_us >= TIMESTAMP '1970-01-01 00:00:00.000005'",
1636            "timestamp_ns >= TIMESTAMP '1970-01-01 00:00:00.000005'",
1637        ];
1638
1639        let expected: ArrayRef = Arc::new(BooleanArray::from_iter(
1640            std::iter::repeat_n(Some(false), 5).chain(std::iter::repeat_n(Some(true), 5)),
1641        ));
1642        for expression in expressions {
1643            // convert to physical expression
1644            let logical_expr = planner.parse_filter(expression).unwrap();
1645            let logical_expr = planner.optimize_expr(logical_expr).unwrap();
1646            let physical_expr = planner.create_physical_expr(&logical_expr).unwrap();
1647
1648            // Evaluate and assert they have correct results
1649            let result = physical_expr.evaluate(&batch).unwrap();
1650            let result = result.into_array(batch.num_rows()).unwrap();
1651            assert_eq!(&expected, &result, "unexpected result for {}", expression);
1652        }
1653    }
1654
1655    #[test]
1656    fn test_columns_in_expr() {
1657        let expr = col("s0").gt(lit("value")).and(
1658            col("st")
1659                .field("st")
1660                .field("s2")
1661                .eq(lit("value"))
1662                .or(col("st")
1663                    .field("s1")
1664                    .in_list(vec![lit("value 1"), lit("value 2")], false)),
1665        );
1666
1667        let columns = Planner::column_names_in_expr(&expr);
1668        assert_eq!(columns, vec!["s0", "st.s1", "st.st.s2"]);
1669    }
1670
1671    #[test]
1672    fn test_parse_binary_expr() {
1673        let bin_str = "x'616263'";
1674
1675        let schema = Arc::new(Schema::new(vec![Field::new(
1676            "binary",
1677            DataType::Binary,
1678            true,
1679        )]));
1680        let planner = Planner::new(schema);
1681        let expr = planner.parse_expr(bin_str).unwrap();
1682        assert_eq!(
1683            expr,
1684            Expr::Literal(ScalarValue::Binary(Some(vec![b'a', b'b', b'c'])), None)
1685        );
1686    }
1687
1688    #[test]
1689    fn test_lance_context_provider_expr_planners() {
1690        let ctx_provider = LanceContextProvider::default();
1691        assert!(!ctx_provider.get_expr_planners().is_empty());
1692    }
1693}