Skip to main content

datafusion_expr/
simplify.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//! Structs to provide the information needed for expression simplification.
6
7use std::sync::Arc;
8
9use arrow::datatypes::DataType;
10use chrono::{DateTime, Utc};
11use datafusion_common::config::ConfigOptions;
12use datafusion_common::{DFSchema, DFSchemaRef, Result};
13
14use crate::{Expr, ExprSchemable};
15
16/// Provides simplification information based on schema, query execution time,
17/// and configuration options.
18///
19/// # Example
20/// See the `simplify_demo` in the [`expr_api` example]
21///
22/// [`expr_api` example]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/query_planning/expr_api.rs
23#[derive(Debug, Clone)]
24pub struct SimplifyContext {
25    schema: DFSchemaRef,
26    query_execution_start_time: Option<DateTime<Utc>>,
27    config_options: Arc<ConfigOptions>,
28}
29
30/// Builder for [`SimplifyContext`].
31#[derive(Debug, Default)]
32pub struct SimplifyContextBuilder {
33    schema: Option<DFSchemaRef>,
34    query_execution_start_time: Option<DateTime<Utc>>,
35    config_options: Option<Arc<ConfigOptions>>,
36}
37
38impl Default for SimplifyContext {
39    fn default() -> Self {
40        Self {
41            schema: Arc::new(DFSchema::empty()),
42            query_execution_start_time: None,
43            config_options: Arc::new(ConfigOptions::default()),
44        }
45    }
46}
47
48impl SimplifyContext {
49    /// Returns a builder for [`SimplifyContext`].
50    pub fn builder() -> SimplifyContextBuilder {
51        SimplifyContextBuilder::default()
52    }
53
54    #[deprecated(
55        since = "54.0.0",
56        note = "Use SimplifyContextBuilder if you intend to use non-default values."
57    )]
58    /// Set the [`ConfigOptions`] for this context
59    pub fn with_config_options(mut self, config_options: Arc<ConfigOptions>) -> Self {
60        self.config_options = config_options;
61        self
62    }
63
64    #[deprecated(
65        since = "54.0.0",
66        note = "Use SimplifyContextBuilder if you intend to use non-default values."
67    )]
68    /// Set the schema for this context
69    pub fn with_schema(mut self, schema: DFSchemaRef) -> Self {
70        self.schema = schema;
71        self
72    }
73
74    #[deprecated(
75        since = "54.0.0",
76        note = "Use SimplifyContextBuilder if you intend to use non-default values."
77    )]
78    /// Set the query execution start time
79    pub fn with_query_execution_start_time(
80        mut self,
81        query_execution_start_time: Option<DateTime<Utc>>,
82    ) -> Self {
83        self.query_execution_start_time = query_execution_start_time;
84        self
85    }
86
87    #[deprecated(
88        since = "54.0.0",
89        note = "Use SimplifyContextBuilder if you intend to use non-default values."
90    )]
91    /// Set the query execution start to the current time
92    pub fn with_current_time(mut self) -> Self {
93        self.query_execution_start_time = Some(Utc::now());
94        self
95    }
96
97    /// Returns the schema
98    pub fn schema(&self) -> &DFSchemaRef {
99        &self.schema
100    }
101
102    /// Returns true if this Expr has boolean type
103    pub fn is_boolean_type(&self, expr: &Expr) -> Result<bool> {
104        Ok(expr.get_type(&self.schema)? == DataType::Boolean)
105    }
106
107    /// Returns true if expr is nullable
108    pub fn nullable(&self, expr: &Expr) -> Result<bool> {
109        expr.nullable(self.schema.as_ref())
110    }
111
112    /// Returns data type of this expr needed for determining optimized int type of a value
113    pub fn get_data_type(&self, expr: &Expr) -> Result<DataType> {
114        expr.get_type(&self.schema)
115    }
116
117    /// Returns the time at which the query execution started.
118    /// If `None`, time-dependent functions like `now()` will not be simplified.
119    pub fn query_execution_start_time(&self) -> Option<DateTime<Utc>> {
120        self.query_execution_start_time
121    }
122
123    /// Returns the configuration options for the session.
124    pub fn config_options(&self) -> &Arc<ConfigOptions> {
125        &self.config_options
126    }
127}
128
129impl SimplifyContextBuilder {
130    /// Set the [`ConfigOptions`] for this context.
131    pub fn with_config_options(mut self, config_options: Arc<ConfigOptions>) -> Self {
132        self.config_options = Some(config_options);
133        self
134    }
135
136    /// Set the schema for this context.
137    pub fn with_schema(mut self, schema: DFSchemaRef) -> Self {
138        self.schema = Some(schema);
139        self
140    }
141
142    /// Set the query execution start time.
143    pub fn with_query_execution_start_time(
144        mut self,
145        query_execution_start_time: Option<DateTime<Utc>>,
146    ) -> Self {
147        self.query_execution_start_time = query_execution_start_time;
148        self
149    }
150
151    /// Set the query execution start to the current time.
152    pub fn with_current_time(mut self) -> Self {
153        self.query_execution_start_time = Some(Utc::now());
154        self
155    }
156
157    /// Build a [`SimplifyContext`], filling in any unspecified fields with defaults.
158    pub fn build(self) -> SimplifyContext {
159        SimplifyContext {
160            schema: self.schema.unwrap_or_else(|| Arc::new(DFSchema::empty())),
161            query_execution_start_time: self.query_execution_start_time,
162            config_options: self
163                .config_options
164                .unwrap_or_else(|| Arc::new(ConfigOptions::default())),
165        }
166    }
167}
168
169/// Was the expression simplified?
170#[derive(Debug)]
171pub enum ExprSimplifyResult {
172    /// The function call was simplified to an entirely new Expr
173    Simplified(Expr),
174    /// The function call could not be simplified, and the arguments
175    /// are return unmodified.
176    Original(Vec<Expr>),
177}
178
179/// Maximum compiled regex size allowed during constant evaluation in the
180/// planner. Larger regexes are deferred to execution so that planning cannot
181/// spend the runtime regex engine's substantially larger compilation budget.
182pub const REGEX_PLANNING_SIZE_LIMIT_BYTES: usize = 256 * 1024;
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    #[test]
189    fn simplify_context_builder_builds_default_context() {
190        let context = SimplifyContext::builder().build();
191        let default_options = ConfigOptions::default();
192
193        assert_eq!(context.schema().as_ref(), &DFSchema::empty());
194        assert_eq!(context.query_execution_start_time(), None);
195        assert_eq!(
196            context.config_options().optimizer.max_passes,
197            default_options.optimizer.max_passes
198        );
199    }
200
201    #[test]
202    fn simplify_context_builder_uses_overrides() {
203        let schema = Arc::new(DFSchema::empty());
204        let config_options = Arc::new(ConfigOptions::default());
205        let current_time = Utc::now();
206
207        let context = SimplifyContext::builder()
208            .with_schema(Arc::clone(&schema))
209            .with_config_options(Arc::clone(&config_options))
210            .with_query_execution_start_time(Some(current_time))
211            .build();
212
213        assert_eq!(context.schema().as_ref(), schema.as_ref());
214        assert_eq!(context.query_execution_start_time(), Some(current_time));
215        assert!(Arc::ptr_eq(context.config_options(), &config_options));
216    }
217}