Skip to main content

datafusion_session/
session.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 async_trait::async_trait;
6use datafusion_common::config::{ConfigOptions, TableOptions};
7use datafusion_common::{DFSchema, Result};
8use datafusion_execution::TaskContext;
9use datafusion_execution::config::SessionConfig;
10use datafusion_execution::runtime_env::RuntimeEnv;
11use datafusion_expr::execution_props::ExecutionProps;
12use datafusion_expr::registry::ExtensionTypeRegistryRef;
13use datafusion_expr::{
14    AggregateUDF, Expr, HigherOrderUDF, LogicalPlan, ScalarUDF, WindowUDF,
15};
16use datafusion_physical_plan::operator_statistics::StatisticsRegistry;
17use datafusion_physical_plan::{ExecutionPlan, PhysicalExpr};
18
19use crate::CatalogProviderList;
20use parking_lot::{Mutex, RwLock};
21use std::any::Any;
22use std::collections::HashMap;
23use std::sync::{Arc, Weak};
24
25use crate::{PhysicalOptimizerRule, QueryPlanner, UnsupportedQueryPlanner};
26
27/// Interface for accessing [`SessionState`] from the catalog and data source.
28///
29/// This trait provides access to the information needed to plan and execute
30/// queries, such as configuration, functions, and runtime environment. See the
31/// documentation on [`SessionState`] for more information.
32///
33/// Historically, the `SessionState` struct was passed directly to catalog
34/// traits such as [`TableProvider`], which required a direct dependency on the
35/// DataFusion core. The interface required is now defined by this trait. See
36/// [#10782] for more details.
37///
38/// [#10782]: https://github.com/apache/datafusion/issues/10782
39///
40/// # Migration from `SessionState`
41///
42/// Using trait methods is preferred, as the implementation may change in future
43/// versions. However, you can downcast a `Session` to a `SessionState` as shown
44/// in the example below. If you find yourself needing to do this, please open
45/// an issue on the DataFusion repository so we can extend the trait to provide
46/// the required information.
47///
48/// ```
49/// # use datafusion_session::Session;
50/// # use datafusion_common::{Result, exec_datafusion_err};
51/// # struct SessionState {}
52/// // Given a `Session` reference, get the concrete `SessionState` reference
53/// // Note: this may stop working in future versions,
54/// fn session_state_from_session(session: &dyn Session) -> Result<&SessionState> {
55///     session
56///         .as_any()
57///         .downcast_ref::<SessionState>()
58///         .ok_or_else(|| {
59///             exec_datafusion_err!("Failed to downcast Session to SessionState")
60///         })
61/// }
62/// ```
63///
64/// [`SessionState`]: https://docs.rs/datafusion/latest/datafusion/execution/session_state/struct.SessionState.html
65/// [`TableProvider`]: https://docs.rs/datafusion/latest/datafusion/catalog/trait.TableProvider.html
66#[async_trait]
67pub trait Session: Send + Sync {
68    /// Return the session ID
69    fn session_id(&self) -> &str;
70
71    /// Return the [`SessionConfig`]
72    fn config(&self) -> &SessionConfig;
73
74    /// Return the catalogs registered with this session.
75    fn catalog_list(&self) -> Arc<dyn CatalogProviderList>;
76
77    /// return the [`ConfigOptions`]
78    fn config_options(&self) -> &ConfigOptions {
79        self.config().options()
80    }
81
82    /// Return the query planner for this session.
83    ///
84    /// # Warning
85    ///
86    /// The default implementation returns an [`UnsupportedQueryPlanner`], so
87    /// [`Session::create_physical_plan`] will fail. Sessions that support
88    /// physical planning should override this method (for example by returning
89    /// `SessionState::query_planner`).
90    fn query_planner(&self) -> Arc<dyn QueryPlanner + Send + Sync> {
91        Arc::new(UnsupportedQueryPlanner)
92    }
93
94    /// Optimize a logical plan.
95    ///
96    /// # Warning
97    ///
98    /// The default implementation returns the plan **unchanged**, applying no
99    /// logical optimizations whatsoever. This is almost never what you want:
100    /// without optimization, queries execute in their naive, unoptimized form
101    /// and may be dramatically slower or fail to run at all. The default exists
102    /// only so this crate need not depend on the optimizer; any real session
103    /// should override this method (for example by delegating to
104    /// `SessionState::optimize`).
105    fn optimize(&self, plan: &LogicalPlan) -> Result<LogicalPlan> {
106        Ok(plan.clone())
107    }
108
109    /// Return the physical optimizer rules for this session.
110    ///
111    /// # Warning
112    ///
113    /// The default implementation returns **no rules**. This is almost never
114    /// what you want: DataFusion relies on physical optimizer rules for
115    /// correctness-critical rewrites (such as inserting the repartitioning and
116    /// coalescing needed for parallel and multi-partition execution), so a
117    /// session with no rules will produce plans that are inefficient or that
118    /// fail to execute. The default exists only so this crate need not depend
119    /// on the optimizer; any real session should override this method (for
120    /// example by returning `SessionState::physical_optimizers`).
121    fn physical_optimizers(&self) -> &[Arc<dyn PhysicalOptimizerRule + Send + Sync>] {
122        &[]
123    }
124
125    /// Return the optional statistics registry used during physical optimization.
126    fn statistics_registry(&self) -> Option<&StatisticsRegistry> {
127        None
128    }
129
130    /// Creates a physical [`ExecutionPlan`] plan from a [`LogicalPlan`].
131    ///
132    /// Note: this will optimize the provided plan first.
133    ///
134    /// This function will error for [`LogicalPlan`]s such as catalog DDL like
135    /// `CREATE TABLE`, which do not have corresponding physical plans and must
136    /// be handled by another layer, typically the `SessionContext`.
137    async fn create_physical_plan(
138        &self,
139        logical_plan: &LogicalPlan,
140    ) -> Result<Arc<dyn ExecutionPlan>>;
141
142    /// Create a [`PhysicalExpr`] from an [`Expr`] after applying type
143    /// coercion, and function rewrites.
144    ///
145    /// Note: The expression is not simplified or otherwise optimized: `a = 1 + 2`
146    /// will not be simplified to `a = 3` as this is a more involved process.
147    /// See the [expr_api] example for how to simplify expressions.
148    ///
149    /// [expr_api]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/query_planning/expr_api.rs
150    fn create_physical_expr(
151        &self,
152        expr: Expr,
153        df_schema: &DFSchema,
154    ) -> Result<Arc<dyn PhysicalExpr>>;
155
156    /// Return reference to scalar_functions
157    fn scalar_functions(&self) -> &HashMap<String, Arc<ScalarUDF>>;
158
159    /// Return reference to higher_order_functions
160    fn higher_order_functions(&self) -> &HashMap<String, Arc<HigherOrderUDF>>;
161
162    /// Return reference to aggregate_functions
163    fn aggregate_functions(&self) -> &HashMap<String, Arc<AggregateUDF>>;
164
165    /// Return reference to window functions
166    fn window_functions(&self) -> &HashMap<String, Arc<WindowUDF>>;
167
168    /// Return a reference to the extension type registry
169    fn extension_type_registry(&self) -> &ExtensionTypeRegistryRef;
170
171    /// Return the runtime env
172    fn runtime_env(&self) -> &Arc<RuntimeEnv>;
173
174    /// Return the execution properties
175    fn execution_props(&self) -> &ExecutionProps;
176
177    fn as_any(&self) -> &dyn Any;
178
179    /// Return the table options
180    fn table_options(&self) -> &TableOptions;
181
182    /// return the TableOptions options with its extensions
183    fn default_table_options(&self) -> TableOptions {
184        self.table_options()
185            .combine_with_session_config(self.config_options())
186    }
187
188    /// Returns a mutable reference to [`TableOptions`]
189    fn table_options_mut(&mut self) -> &mut TableOptions;
190
191    /// Get a new TaskContext to run in this session
192    fn task_ctx(&self) -> Arc<TaskContext>;
193}
194
195/// Create a new task context instance from Session
196impl From<&dyn Session> for TaskContext {
197    fn from(state: &dyn Session) -> Self {
198        let task_id = None;
199        TaskContext::new(
200            task_id,
201            state.session_id().to_string(),
202            state.config().clone(),
203            state.scalar_functions().clone(),
204            state.higher_order_functions().clone(),
205            state.aggregate_functions().clone(),
206            state.window_functions().clone(),
207            Arc::clone(state.runtime_env()),
208        )
209    }
210}
211type SessionRefLock = Arc<Mutex<Option<Weak<RwLock<dyn Session>>>>>;
212/// The state store that stores the reference of the runtime session state.
213#[derive(Debug)]
214pub struct SessionStore {
215    session: SessionRefLock,
216}
217
218impl SessionStore {
219    /// Create a new [SessionStore]
220    pub fn new() -> Self {
221        Self {
222            session: Arc::new(Mutex::new(None)),
223        }
224    }
225
226    /// Set the session state of the store
227    pub fn with_state(&self, state: Weak<RwLock<dyn Session>>) {
228        let mut lock = self.session.lock();
229        *lock = Some(state);
230    }
231
232    /// Get the current session of the store
233    pub fn get_session(&self) -> Weak<RwLock<dyn Session>> {
234        self.session.lock().clone().unwrap()
235    }
236}
237
238impl Default for SessionStore {
239    fn default() -> Self {
240        Self::new()
241    }
242}