1use crate::{
6 config::SessionConfig, memory_pool::MemoryPool, registry::FunctionRegistry,
7 runtime_env::RuntimeEnv,
8};
9use datafusion_common::{Result, internal_datafusion_err, plan_datafusion_err};
10use datafusion_expr::planner::ExprPlanner;
11use datafusion_expr::{AggregateUDF, HigherOrderUDF, ScalarUDF, WindowUDF};
12use std::collections::HashSet;
13use std::{collections::HashMap, sync::Arc};
14
15#[derive(Debug)]
39pub struct TaskContext {
40 session_id: String,
42 task_id: Option<String>,
44 session_config: SessionConfig,
46 scalar_functions: HashMap<String, Arc<ScalarUDF>>,
48 higher_order_functions: HashMap<String, Arc<HigherOrderUDF>>,
50 aggregate_functions: HashMap<String, Arc<AggregateUDF>>,
52 window_functions: HashMap<String, Arc<WindowUDF>>,
54 runtime: Arc<RuntimeEnv>,
56}
57
58impl Default for TaskContext {
59 fn default() -> Self {
60 let runtime = Arc::new(RuntimeEnv::default());
61
62 Self {
64 session_id: "DEFAULT".to_string(),
65 task_id: None,
66 session_config: SessionConfig::new(),
67 scalar_functions: HashMap::new(),
68 higher_order_functions: HashMap::new(),
69 aggregate_functions: HashMap::new(),
70 window_functions: HashMap::new(),
71 runtime,
72 }
73 }
74}
75
76impl TaskContext {
77 #[expect(clippy::too_many_arguments)]
83 pub fn new(
84 task_id: Option<String>,
85 session_id: String,
86 session_config: SessionConfig,
87 scalar_functions: HashMap<String, Arc<ScalarUDF>>,
88 higher_order_functions: HashMap<String, Arc<HigherOrderUDF>>,
89 aggregate_functions: HashMap<String, Arc<AggregateUDF>>,
90 window_functions: HashMap<String, Arc<WindowUDF>>,
91 runtime: Arc<RuntimeEnv>,
92 ) -> Self {
93 Self {
94 session_id,
95 task_id,
96 session_config,
97 scalar_functions,
98 higher_order_functions,
99 aggregate_functions,
100 window_functions,
101 runtime,
102 }
103 }
104
105 pub fn session_config(&self) -> &SessionConfig {
107 &self.session_config
108 }
109
110 pub fn session_id(&self) -> String {
112 self.session_id.clone()
113 }
114
115 pub fn task_id(&self) -> Option<String> {
117 self.task_id.clone()
118 }
119
120 pub fn memory_pool(&self) -> &Arc<dyn MemoryPool> {
122 &self.runtime.memory_pool
123 }
124
125 pub fn runtime_env(&self) -> Arc<RuntimeEnv> {
127 Arc::clone(&self.runtime)
128 }
129
130 pub fn scalar_functions(&self) -> &HashMap<String, Arc<ScalarUDF>> {
131 &self.scalar_functions
132 }
133
134 pub fn higher_order_functions(&self) -> &HashMap<String, Arc<HigherOrderUDF>> {
135 &self.higher_order_functions
136 }
137
138 pub fn aggregate_functions(&self) -> &HashMap<String, Arc<AggregateUDF>> {
139 &self.aggregate_functions
140 }
141
142 pub fn window_functions(&self) -> &HashMap<String, Arc<WindowUDF>> {
143 &self.window_functions
144 }
145
146 pub fn with_session_config(mut self, session_config: SessionConfig) -> Self {
148 self.session_config = session_config;
149 self
150 }
151
152 pub fn with_runtime(mut self, runtime: Arc<RuntimeEnv>) -> Self {
154 self.runtime = runtime;
155 self
156 }
157
158 pub fn with_task_id(mut self, task_id: String) -> Self {
160 self.task_id = Some(task_id);
161 self
162 }
163}
164
165impl FunctionRegistry for TaskContext {
166 fn udfs(&self) -> HashSet<String> {
167 self.scalar_functions.keys().cloned().collect()
168 }
169
170 fn udf(&self, name: &str) -> Result<Arc<ScalarUDF>> {
171 let result = self.scalar_functions.get(name);
172
173 result.cloned().ok_or_else(|| {
174 plan_datafusion_err!("There is no UDF named \"{name}\" in the TaskContext")
175 })
176 }
177
178 fn higher_order_function(&self, name: &str) -> Result<Arc<HigherOrderUDF>> {
179 let result = self.higher_order_functions.get(name);
180
181 result.cloned().ok_or_else(|| {
182 plan_datafusion_err!(
183 "There is no higher-order function named \"{name}\" in the TaskContext"
184 )
185 })
186 }
187
188 fn udaf(&self, name: &str) -> Result<Arc<AggregateUDF>> {
189 let result = self.aggregate_functions.get(name);
190
191 result.cloned().ok_or_else(|| {
192 plan_datafusion_err!("There is no UDAF named \"{name}\" in the TaskContext")
193 })
194 }
195
196 fn udwf(&self, name: &str) -> Result<Arc<WindowUDF>> {
197 let result = self.window_functions.get(name);
198
199 result.cloned().ok_or_else(|| {
200 internal_datafusion_err!(
201 "There is no UDWF named \"{name}\" in the TaskContext"
202 )
203 })
204 }
205 fn register_udaf(
206 &mut self,
207 udaf: Arc<AggregateUDF>,
208 ) -> Result<Option<Arc<AggregateUDF>>> {
209 udaf.aliases().iter().for_each(|alias| {
210 self.aggregate_functions
211 .insert(alias.clone(), Arc::clone(&udaf));
212 });
213 Ok(self.aggregate_functions.insert(udaf.name().into(), udaf))
214 }
215 fn register_udwf(&mut self, udwf: Arc<WindowUDF>) -> Result<Option<Arc<WindowUDF>>> {
216 udwf.aliases().iter().for_each(|alias| {
217 self.window_functions
218 .insert(alias.clone(), Arc::clone(&udwf));
219 });
220 Ok(self.window_functions.insert(udwf.name().into(), udwf))
221 }
222 fn register_udf(&mut self, udf: Arc<ScalarUDF>) -> Result<Option<Arc<ScalarUDF>>> {
223 udf.aliases().iter().for_each(|alias| {
224 self.scalar_functions
225 .insert(alias.clone(), Arc::clone(&udf));
226 });
227 Ok(self.scalar_functions.insert(udf.name().into(), udf))
228 }
229
230 fn register_higher_order_function(
231 &mut self,
232 function: Arc<HigherOrderUDF>,
233 ) -> Result<Option<Arc<HigherOrderUDF>>> {
234 function.aliases().iter().for_each(|alias| {
235 self.higher_order_functions
236 .insert(alias.clone(), Arc::clone(&function));
237 });
238 Ok(self
239 .higher_order_functions
240 .insert(function.name().into(), function))
241 }
242
243 fn expr_planners(&self) -> Vec<Arc<dyn ExprPlanner>> {
244 vec![]
245 }
246
247 fn higher_order_function_names(&self) -> HashSet<String> {
248 self.higher_order_functions.keys().cloned().collect()
249 }
250
251 fn udafs(&self) -> HashSet<String> {
252 self.aggregate_functions.keys().cloned().collect()
253 }
254
255 fn udwfs(&self) -> HashSet<String> {
256 self.window_functions.keys().cloned().collect()
257 }
258}
259
260pub trait TaskContextProvider {
262 fn task_ctx(&self) -> Arc<TaskContext>;
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268 use datafusion_common::{
269 config::{ConfigExtension, ConfigOptions, Extensions},
270 extensions_options,
271 };
272
273 extensions_options! {
274 struct TestExtension {
275 value: usize, default = 42
276 option_value: Option<usize>, default = None
277 }
278 }
279
280 impl ConfigExtension for TestExtension {
281 const PREFIX: &'static str = "test";
282 }
283
284 #[test]
285 fn task_context_extensions() -> Result<()> {
286 let runtime = Arc::new(RuntimeEnv::default());
287 let mut extensions = Extensions::new();
288 extensions.insert(TestExtension::default());
289
290 let mut config = ConfigOptions::new().with_extensions(extensions);
291 config.set("test.value", "24")?;
292 config.set("test.option_value", "42")?;
293 let session_config = SessionConfig::from(config);
294
295 let task_context = TaskContext::new(
296 Some("task_id".to_string()),
297 "session_id".to_string(),
298 session_config,
299 HashMap::default(),
300 HashMap::default(),
301 HashMap::default(),
302 HashMap::default(),
303 runtime,
304 );
305
306 let test = task_context
307 .session_config()
308 .options()
309 .extensions
310 .get::<TestExtension>();
311 assert!(test.is_some());
312
313 assert_eq!(test.unwrap().value, 24);
314 assert_eq!(test.unwrap().option_value, Some(42));
315
316 Ok(())
317 }
318
319 #[test]
320 fn task_context_extensions_default() -> Result<()> {
321 let runtime = Arc::new(RuntimeEnv::default());
322 let mut extensions = Extensions::new();
323 extensions.insert(TestExtension::default());
324
325 let config = ConfigOptions::new().with_extensions(extensions);
326 let session_config = SessionConfig::from(config);
327
328 let task_context = TaskContext::new(
329 Some("task_id".to_string()),
330 "session_id".to_string(),
331 session_config,
332 HashMap::default(),
333 HashMap::default(),
334 HashMap::default(),
335 HashMap::default(),
336 runtime,
337 );
338
339 let test = task_context
340 .session_config()
341 .options()
342 .extensions
343 .get::<TestExtension>();
344 assert!(test.is_some());
345
346 assert_eq!(test.unwrap().value, 42);
347 assert_eq!(test.unwrap().option_value, None);
348
349 Ok(())
350 }
351}