Skip to main content

datafusion_expr/
execution_props.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
5use crate::var_provider::{VarProvider, VarType};
6use chrono::{DateTime, Utc};
7use datafusion_common::HashMap;
8use datafusion_common::alias::AliasGenerator;
9use datafusion_common::config::ConfigOptions;
10use std::sync::Arc;
11
12/// Holds properties and scratch state used while optimizing a [`LogicalPlan`]
13/// and translating it into an executable physical plan, such as the statement
14/// start time used during simplification.
15///
16/// An [`ExecutionProps`] is created each time a `LogicalPlan` is
17/// prepared for execution (optimized). If the same plan is optimized
18/// multiple times, a new `ExecutionProps` is created each time.
19///
20/// It is important that this structure be cheap to create as it is
21/// done so during predicate pruning and expression simplification
22///
23/// # Relationship with [`TaskContext`]
24///
25/// [`ExecutionProps`] is intentionally distinct from [`TaskContext`].
26/// It is used while optimizing a logical plan and constructing physical
27/// expressions and physical plans, before physical operators are run.
28///
29/// [`TaskContext`] is the runtime context passed to physical operators during
30/// physical-plan execution.
31///
32/// Keeping these structures separate avoids threading execution/runtime state
33/// through planning APIs, and avoids making execution depend on planner-only
34/// scratch state.
35///
36/// [`TaskContext`]: https://docs.rs/datafusion/latest/datafusion/execution/struct.TaskContext.html
37/// [`LogicalPlan`]: crate::LogicalPlan
38#[derive(Clone, Debug)]
39pub struct ExecutionProps {
40    /// The time at which the query execution started. If `None`,
41    /// functions like `now()` will not be simplified during optimization.
42    pub query_execution_start_time: Option<DateTime<Utc>>,
43    /// Alias generator used by subquery optimizer rules
44    pub alias_generator: Arc<AliasGenerator>,
45    /// Snapshot of config options when the query started
46    pub config_options: Option<Arc<ConfigOptions>>,
47    /// Providers for scalar variables
48    pub var_providers: Option<HashMap<VarType, Arc<dyn VarProvider + Send + Sync>>>,
49}
50
51impl Default for ExecutionProps {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57impl ExecutionProps {
58    /// Creates a new execution props
59    pub fn new() -> Self {
60        ExecutionProps {
61            query_execution_start_time: None,
62            alias_generator: Arc::new(AliasGenerator::new()),
63            config_options: None,
64            var_providers: None,
65        }
66    }
67
68    /// Set the query execution start time to use
69    pub fn with_query_execution_start_time(
70        mut self,
71        query_execution_start_time: DateTime<Utc>,
72    ) -> Self {
73        self.query_execution_start_time = Some(query_execution_start_time);
74        self
75    }
76
77    /// Marks the execution of query started timestamp.
78    /// This also instantiates a new alias generator.
79    pub fn mark_start_execution(&mut self, config_options: Arc<ConfigOptions>) -> &Self {
80        self.query_execution_start_time = Some(Utc::now());
81        self.alias_generator = Arc::new(AliasGenerator::new());
82        self.config_options = Some(config_options);
83        &*self
84    }
85
86    /// Registers a variable provider, returning the existing provider, if any
87    pub fn add_var_provider(
88        &mut self,
89        var_type: VarType,
90        provider: Arc<dyn VarProvider + Send + Sync>,
91    ) -> Option<Arc<dyn VarProvider + Send + Sync>> {
92        let mut var_providers = self.var_providers.take().unwrap_or_default();
93
94        let old_provider = var_providers.insert(var_type, provider);
95
96        self.var_providers = Some(var_providers);
97
98        old_provider
99    }
100
101    /// Returns the provider for the `var_type`, if any
102    #[expect(clippy::needless_pass_by_value)]
103    pub fn get_var_provider(
104        &self,
105        var_type: VarType,
106    ) -> Option<Arc<dyn VarProvider + Send + Sync>> {
107        self.var_providers
108            .as_ref()
109            .and_then(|var_providers| var_providers.get(&var_type).cloned())
110    }
111
112    /// Returns the configuration properties for this execution
113    /// if the execution has started
114    pub fn config_options(&self) -> Option<&Arc<ConfigOptions>> {
115        self.config_options.as_ref()
116    }
117}
118
119#[cfg(test)]
120mod test {
121    use super::*;
122
123    #[test]
124    fn debug() {
125        let props = ExecutionProps::new();
126        assert_eq!(
127            "ExecutionProps { query_execution_start_time: None, alias_generator: AliasGenerator { next_id: 1 }, config_options: None, var_providers: None }",
128            format!("{props:?}")
129        );
130    }
131}