datafusion_execution/config.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 std::{collections::HashMap, sync::Arc};
6
7use datafusion_common::{
8 Result, ScalarValue,
9 config::{ConfigExtension, ConfigNonZeroUsize, ConfigOptions, SpillCompression},
10 extensions::Extensions,
11};
12
13/// Configuration options for [`SessionContext`].
14///
15/// Can be passed to [`SessionContext::new_with_config`] to customize the configuration of DataFusion.
16///
17/// Options can be set using namespaces keys with `.` as the separator, where the
18/// namespace determines which configuration struct the value to routed to. All
19/// built-in options are under the `datafusion` namespace.
20///
21/// For example, the key `datafusion.execution.batch_size` will set [ExecutionOptions::batch_size][datafusion_common::config::ExecutionOptions::batch_size],
22/// because [ConfigOptions::execution] is [ExecutionOptions][datafusion_common::config::ExecutionOptions]. Similarly, the key
23/// `datafusion.execution.parquet.pushdown_filters` will set [ParquetOptions::pushdown_filters][datafusion_common::config::ParquetOptions::pushdown_filters],
24/// since [ExecutionOptions::parquet][datafusion_common::config::ExecutionOptions::parquet] is [ParquetOptions][datafusion_common::config::ParquetOptions].
25///
26/// Some options have convenience methods. For example [SessionConfig::with_batch_size] is
27/// shorthand for setting `datafusion.execution.batch_size`.
28///
29/// ```
30/// use datafusion_common::ScalarValue;
31/// use datafusion_execution::config::SessionConfig;
32///
33/// let config = SessionConfig::new()
34/// .set(
35/// "datafusion.execution.batch_size",
36/// &ScalarValue::UInt64(Some(1234)),
37/// )
38/// .set_bool("datafusion.execution.parquet.pushdown_filters", true);
39///
40/// assert_eq!(config.batch_size(), 1234);
41/// assert_eq!(config.options().execution.batch_size.get(), 1234);
42/// assert_eq!(config.options().execution.parquet.pushdown_filters, true);
43/// ```
44///
45/// You can also directly mutate the options via [SessionConfig::options_mut].
46/// So the following is equivalent to the above:
47///
48/// ```
49/// # use datafusion_execution::config::SessionConfig;
50/// # use datafusion_common::config::ConfigNonZeroUsize;
51/// #
52/// let mut config = SessionConfig::new();
53/// config.options_mut().execution.batch_size = ConfigNonZeroUsize::try_new(1234)?;
54/// config.options_mut().execution.parquet.pushdown_filters = true;
55/// #
56/// # assert_eq!(config.batch_size(), 1234);
57/// # assert_eq!(config.options().execution.batch_size.get(), 1234);
58/// # assert_eq!(config.options().execution.parquet.pushdown_filters, true);
59/// # datafusion_common::Result::<()>::Ok(())
60/// ```
61///
62/// ## Built-in options
63///
64/// | Namespace | Config struct |
65/// | --------- | ------------- |
66/// | `datafusion.catalog` | [CatalogOptions][datafusion_common::config::CatalogOptions] |
67/// | `datafusion.execution` | [ExecutionOptions][datafusion_common::config::ExecutionOptions] |
68/// | `datafusion.execution.parquet` | [ParquetOptions][datafusion_common::config::ParquetOptions] |
69/// | `datafusion.optimizer` | [OptimizerOptions][datafusion_common::config::OptimizerOptions] |
70/// | `datafusion.sql_parser` | [SqlParserOptions][datafusion_common::config::SqlParserOptions] |
71/// | `datafusion.explain` | [ExplainOptions][datafusion_common::config::ExplainOptions] |
72///
73/// ## Custom configuration
74///
75/// Configuration options can be extended. See [SessionConfig::with_extension] for details.
76///
77/// [`SessionContext`]: https://docs.rs/datafusion/latest/datafusion/execution/context/struct.SessionContext.html
78/// [`SessionContext::new_with_config`]: https://docs.rs/datafusion/latest/datafusion/execution/context/struct.SessionContext.html#method.new_with_config
79#[derive(Clone, Debug)]
80pub struct SessionConfig {
81 /// Configuration options for the current session.
82 ///
83 /// A new copy is created on write, if there are other outstanding
84 /// references to the same options.
85 options: Arc<ConfigOptions>,
86 /// Opaque extensions, keyed by concrete Rust type. See
87 /// [`with_extension`](Self::with_extension) and
88 /// [`get_extension`](Self::get_extension).
89 extensions: Extensions,
90}
91
92impl Default for SessionConfig {
93 fn default() -> Self {
94 Self {
95 options: Arc::new(ConfigOptions::new()),
96 extensions: Extensions::new(),
97 }
98 }
99}
100
101impl SessionConfig {
102 /// Create an execution config with default setting
103 pub fn new() -> Self {
104 Default::default()
105 }
106
107 /// Create an execution config with config options read from the environment
108 ///
109 /// See [`ConfigOptions::from_env`] for details on how environment variables
110 /// are mapped to config options.
111 pub fn from_env() -> Result<Self> {
112 Ok(ConfigOptions::from_env()?.into())
113 }
114
115 /// Create new ConfigOptions struct, taking values from a string hash map.
116 pub fn from_string_hash_map(settings: &HashMap<String, String>) -> Result<Self> {
117 Ok(ConfigOptions::from_string_hash_map(settings)?.into())
118 }
119
120 /// Return a handle to the configuration options.
121 ///
122 /// Can be used to read the current configuration.
123 ///
124 /// ```
125 /// use datafusion_execution::config::SessionConfig;
126 ///
127 /// let config = SessionConfig::new();
128 /// assert!(config.options().execution.batch_size.get() > 0);
129 /// ```
130 pub fn options(&self) -> &Arc<ConfigOptions> {
131 &self.options
132 }
133
134 /// Return a mutable handle to the configuration options.
135 ///
136 /// Can be used to set configuration options.
137 ///
138 /// ```
139 /// use datafusion_common::config::ConfigNonZeroUsize;
140 /// use datafusion_execution::config::SessionConfig;
141 ///
142 /// let mut config = SessionConfig::new();
143 /// config.options_mut().execution.batch_size = ConfigNonZeroUsize::try_new(1024)?;
144 /// assert_eq!(config.options().execution.batch_size.get(), 1024);
145 /// # datafusion_common::Result::<()>::Ok(())
146 /// ```
147 pub fn options_mut(&mut self) -> &mut ConfigOptions {
148 Arc::make_mut(&mut self.options)
149 }
150
151 /// Set a configuration option
152 pub fn set(self, key: &str, value: &ScalarValue) -> Self {
153 self.set_str(key, &value.to_string())
154 }
155
156 /// Set a boolean configuration option
157 pub fn set_bool(self, key: &str, value: bool) -> Self {
158 self.set_str(key, &value.to_string())
159 }
160
161 /// Set a generic `u64` configuration option
162 pub fn set_u64(self, key: &str, value: u64) -> Self {
163 self.set_str(key, &value.to_string())
164 }
165
166 /// Set a generic `usize` configuration option
167 pub fn set_usize(self, key: &str, value: usize) -> Self {
168 self.set_str(key, &value.to_string())
169 }
170
171 /// Set a generic `str` configuration option
172 pub fn set_str(mut self, key: &str, value: &str) -> Self {
173 self.options_mut().set(key, value).unwrap();
174 self
175 }
176
177 /// Set [`batch_size`]
178 ///
179 /// # Panics
180 ///
181 /// Panics if `n` is zero
182 ///
183 /// [`batch_size`]: datafusion_common::config::ExecutionOptions::batch_size
184 pub fn with_batch_size(mut self, n: usize) -> Self {
185 self.options_mut().execution.batch_size =
186 ConfigNonZeroUsize::try_new(n).expect("batch size must be greater than zero");
187 self
188 }
189
190 /// Set [`target_partitions`]
191 ///
192 /// If `n` is zero, the default value is used instead
193 ///
194 /// [`target_partitions`]: datafusion_common::config::ExecutionOptions::target_partitions
195 pub fn with_target_partitions(mut self, n: usize) -> Self {
196 self.options_mut().execution.target_partitions = if n == 0 {
197 datafusion_common::config::ExecutionOptions::default().target_partitions
198 } else {
199 n
200 };
201 self
202 }
203
204 /// Insert new [ConfigExtension]
205 pub fn with_option_extension<T: ConfigExtension>(mut self, extension: T) -> Self {
206 self.options_mut().extensions.insert(extension);
207 self
208 }
209
210 /// Get [`target_partitions`]
211 ///
212 /// [`target_partitions`]: datafusion_common::config::ExecutionOptions::target_partitions
213 pub fn target_partitions(&self) -> usize {
214 self.options.execution.target_partitions
215 }
216
217 /// Get [`information_schema`]
218 ///
219 /// [`information_schema`]: datafusion_common::config::CatalogOptions::information_schema
220 pub fn information_schema(&self) -> bool {
221 self.options.catalog.information_schema
222 }
223
224 /// Get [`partition_information_schema`]
225 ///
226 /// [`partition_information_schema`]: datafusion_common::config::CatalogOptions::partition_information_schema
227 pub fn partition_information_schema(&self) -> bool {
228 self.options.catalog.partition_information_schema
229 }
230
231 /// Get [`create_default_catalog_and_schema`]
232 ///
233 /// [`create_default_catalog_and_schema`]: datafusion_common::config::CatalogOptions::create_default_catalog_and_schema
234 pub fn create_default_catalog_and_schema(&self) -> bool {
235 self.options.catalog.create_default_catalog_and_schema
236 }
237
238 /// Get [`repartition_joins`]
239 ///
240 /// [`repartition_joins`]: datafusion_common::config::OptimizerOptions::repartition_joins
241 pub fn repartition_joins(&self) -> bool {
242 self.options.optimizer.repartition_joins
243 }
244
245 /// Get [`repartition_aggregations`]
246 ///
247 /// [`repartition_aggregations`]: datafusion_common::config::OptimizerOptions::repartition_aggregations
248 pub fn repartition_aggregations(&self) -> bool {
249 self.options.optimizer.repartition_aggregations
250 }
251
252 /// Get [`repartition_windows`]
253 ///
254 /// [`repartition_windows`]: datafusion_common::config::OptimizerOptions::repartition_windows
255 pub fn repartition_window_functions(&self) -> bool {
256 self.options.optimizer.repartition_windows
257 }
258
259 /// Get [`repartition_sorts`]
260 ///
261 /// [`repartition_sorts`]: datafusion_common::config::OptimizerOptions::repartition_sorts
262 pub fn repartition_sorts(&self) -> bool {
263 self.options.optimizer.repartition_sorts
264 }
265
266 /// Get [`prefer_existing_sort`]
267 ///
268 /// [`prefer_existing_sort`]: datafusion_common::config::OptimizerOptions::prefer_existing_sort
269 pub fn prefer_existing_sort(&self) -> bool {
270 self.options.optimizer.prefer_existing_sort
271 }
272
273 /// Get [`collect_statistics`]
274 ///
275 /// [`collect_statistics`]: datafusion_common::config::ExecutionOptions::collect_statistics
276 pub fn collect_statistics(&self) -> bool {
277 self.options.execution.collect_statistics
278 }
279
280 /// Get [`spill_compression`]
281 ///
282 /// [`spill_compression`]: datafusion_common::config::ExecutionOptions::spill_compression
283 pub fn spill_compression(&self) -> SpillCompression {
284 self.options.execution.spill_compression
285 }
286
287 /// Set [`default_catalog`] and [`default_schema`]
288 ///
289 /// [`default_catalog`]: datafusion_common::config::CatalogOptions::default_catalog
290 /// [`default_schema`]: datafusion_common::config::CatalogOptions::default_schema
291 pub fn with_default_catalog_and_schema(
292 mut self,
293 catalog: impl Into<String>,
294 schema: impl Into<String>,
295 ) -> Self {
296 self.options_mut().catalog.default_catalog = catalog.into();
297 self.options_mut().catalog.default_schema = schema.into();
298 self
299 }
300
301 /// Set [`create_default_catalog_and_schema`]
302 ///
303 /// [`create_default_catalog_and_schema`]: datafusion_common::config::CatalogOptions::create_default_catalog_and_schema
304 pub fn with_create_default_catalog_and_schema(mut self, create: bool) -> Self {
305 self.options_mut().catalog.create_default_catalog_and_schema = create;
306 self
307 }
308
309 /// Set [`partition_information_schema`]
310 ///
311 /// [`partition_information_schema`]: datafusion_common::config::CatalogOptions::partition_information_schema
312 pub fn with_partition_information_schema(mut self, partition: bool) -> Self {
313 self.options_mut().catalog.partition_information_schema = partition;
314 self
315 }
316
317 /// Set [`information_schema`]
318 ///
319 /// [`information_schema`]: datafusion_common::config::CatalogOptions::information_schema
320 pub fn with_information_schema(mut self, enabled: bool) -> Self {
321 self.options_mut().catalog.information_schema = enabled;
322 self
323 }
324
325 /// Set [`repartition_joins`]
326 ///
327 /// [`repartition_joins`]: datafusion_common::config::OptimizerOptions::repartition_joins
328 pub fn with_repartition_joins(mut self, enabled: bool) -> Self {
329 self.options_mut().optimizer.repartition_joins = enabled;
330 self
331 }
332
333 /// Set [`repartition_aggregations`]
334 ///
335 /// [`repartition_aggregations`]: datafusion_common::config::OptimizerOptions::repartition_aggregations
336 pub fn with_repartition_aggregations(mut self, enabled: bool) -> Self {
337 self.options_mut().optimizer.repartition_aggregations = enabled;
338 self
339 }
340
341 /// Set [`repartition_file_min_size`]
342 ///
343 /// [`repartition_file_min_size`]: datafusion_common::config::OptimizerOptions::repartition_file_min_size
344 pub fn with_repartition_file_min_size(mut self, size: usize) -> Self {
345 self.options_mut().optimizer.repartition_file_min_size = size;
346 self
347 }
348
349 /// Set [`allow_symmetric_joins_without_pruning`]
350 ///
351 /// [`allow_symmetric_joins_without_pruning`]: datafusion_common::config::OptimizerOptions::allow_symmetric_joins_without_pruning
352 pub fn with_allow_symmetric_joins_without_pruning(mut self, enabled: bool) -> Self {
353 self.options_mut()
354 .optimizer
355 .allow_symmetric_joins_without_pruning = enabled;
356 self
357 }
358
359 /// Set [`repartition_file_scans`]
360 ///
361 /// [`repartition_file_scans`]: datafusion_common::config::OptimizerOptions::repartition_file_scans
362 pub fn with_repartition_file_scans(mut self, enabled: bool) -> Self {
363 self.options_mut().optimizer.repartition_file_scans = enabled;
364 self
365 }
366
367 /// Set [`repartition_windows`]
368 ///
369 /// [`repartition_windows`]: datafusion_common::config::OptimizerOptions::repartition_windows
370 pub fn with_repartition_windows(mut self, enabled: bool) -> Self {
371 self.options_mut().optimizer.repartition_windows = enabled;
372 self
373 }
374
375 /// Set [`repartition_sorts`]
376 ///
377 /// [`repartition_sorts`]: datafusion_common::config::OptimizerOptions::repartition_sorts
378 pub fn with_repartition_sorts(mut self, enabled: bool) -> Self {
379 self.options_mut().optimizer.repartition_sorts = enabled;
380 self
381 }
382
383 /// Set [`prefer_existing_sort`]
384 ///
385 /// [`prefer_existing_sort`]: datafusion_common::config::OptimizerOptions::prefer_existing_sort
386 pub fn with_prefer_existing_sort(mut self, enabled: bool) -> Self {
387 self.options_mut().optimizer.prefer_existing_sort = enabled;
388 self
389 }
390
391 /// Set [`prefer_existing_union`]
392 ///
393 /// [`prefer_existing_union`]: datafusion_common::config::OptimizerOptions::prefer_existing_union
394 pub fn with_prefer_existing_union(mut self, enabled: bool) -> Self {
395 self.options_mut().optimizer.prefer_existing_union = enabled;
396 self
397 }
398
399 /// Set [`pruning`]
400 ///
401 /// [`pruning`]: datafusion_common::config::ParquetOptions::pruning
402 pub fn with_parquet_pruning(mut self, enabled: bool) -> Self {
403 self.options_mut().execution.parquet.pruning = enabled;
404 self
405 }
406
407 /// Get [`pruning`]
408 ///
409 /// [`pruning`]: datafusion_common::config::ParquetOptions::pruning
410 pub fn parquet_pruning(&self) -> bool {
411 self.options.execution.parquet.pruning
412 }
413
414 /// Get [`bloom_filter_on_read`]
415 ///
416 /// [`bloom_filter_on_read`]: datafusion_common::config::ParquetOptions::bloom_filter_on_read
417 pub fn parquet_bloom_filter_pruning(&self) -> bool {
418 self.options.execution.parquet.bloom_filter_on_read
419 }
420
421 /// Set [`bloom_filter_on_read`]
422 ///
423 /// [`bloom_filter_on_read`]: datafusion_common::config::ParquetOptions::bloom_filter_on_read
424 pub fn with_parquet_bloom_filter_pruning(mut self, enabled: bool) -> Self {
425 self.options_mut().execution.parquet.bloom_filter_on_read = enabled;
426 self
427 }
428
429 /// Get [`enable_page_index`]
430 ///
431 /// [`enable_page_index`]: datafusion_common::config::ParquetOptions::enable_page_index
432 pub fn parquet_page_index_pruning(&self) -> bool {
433 self.options.execution.parquet.enable_page_index
434 }
435
436 /// Set [`enable_page_index`]
437 ///
438 /// [`enable_page_index`]: datafusion_common::config::ParquetOptions::enable_page_index
439 pub fn with_parquet_page_index_pruning(mut self, enabled: bool) -> Self {
440 self.options_mut().execution.parquet.enable_page_index = enabled;
441 self
442 }
443
444 /// Set [`collect_statistics`]
445 ///
446 /// [`collect_statistics`]: datafusion_common::config::ExecutionOptions::collect_statistics
447 pub fn with_collect_statistics(mut self, enabled: bool) -> Self {
448 self.options_mut().execution.collect_statistics = enabled;
449 self
450 }
451
452 /// Get [`batch_size`]
453 ///
454 /// [`batch_size`]: datafusion_common::config::ExecutionOptions::batch_size
455 pub fn batch_size(&self) -> usize {
456 self.options.execution.batch_size.get()
457 }
458
459 /// Set [`coalesce_batches`]
460 ///
461 /// [`coalesce_batches`]: datafusion_common::config::ExecutionOptions::coalesce_batches
462 pub fn with_coalesce_batches(mut self, enabled: bool) -> Self {
463 self.options_mut().execution.coalesce_batches = enabled;
464 self
465 }
466
467 /// Get [`coalesce_batches`]
468 ///
469 /// [`coalesce_batches`]: datafusion_common::config::ExecutionOptions::coalesce_batches
470 pub fn coalesce_batches(&self) -> bool {
471 self.options.execution.coalesce_batches
472 }
473
474 /// Set [`enable_round_robin_repartition`]
475 ///
476 /// [`enable_round_robin_repartition`]: datafusion_common::config::OptimizerOptions::enable_round_robin_repartition
477 pub fn with_round_robin_repartition(mut self, enabled: bool) -> Self {
478 self.options_mut().optimizer.enable_round_robin_repartition = enabled;
479 self
480 }
481
482 /// Get [`enable_round_robin_repartition`]
483 ///
484 /// [`enable_round_robin_repartition`]: datafusion_common::config::OptimizerOptions::enable_round_robin_repartition
485 pub fn round_robin_repartition(&self) -> bool {
486 self.options.optimizer.enable_round_robin_repartition
487 }
488
489 /// Set [`enable_sort_pushdown`]
490 ///
491 /// [`enable_sort_pushdown`]: datafusion_common::config::OptimizerOptions::enable_sort_pushdown
492 pub fn with_enable_sort_pushdown(mut self, enabled: bool) -> Self {
493 self.options_mut().optimizer.enable_sort_pushdown = enabled;
494 self
495 }
496
497 /// Set [`enable_subquery_sort_elimination`]
498 ///
499 /// [`enable_subquery_sort_elimination`]: datafusion_common::config::SqlParserOptions::enable_subquery_sort_elimination
500 pub fn with_enable_subquery_sort_elimination(mut self, enabled: bool) -> Self {
501 self.options_mut()
502 .sql_parser
503 .enable_subquery_sort_elimination = enabled;
504 self
505 }
506
507 /// Set [`sort_spill_reservation_bytes`]
508 ///
509 /// [`sort_spill_reservation_bytes`]: datafusion_common::config::ExecutionOptions::sort_spill_reservation_bytes
510 pub fn with_sort_spill_reservation_bytes(
511 mut self,
512 sort_spill_reservation_bytes: usize,
513 ) -> Self {
514 self.options_mut().execution.sort_spill_reservation_bytes =
515 sort_spill_reservation_bytes;
516 self
517 }
518
519 /// Set [`spill_compression`]
520 ///
521 /// [`spill_compression`]: datafusion_common::config::ExecutionOptions::spill_compression
522 pub fn with_spill_compression(mut self, spill_compression: SpillCompression) -> Self {
523 self.options_mut().execution.spill_compression = spill_compression;
524 self
525 }
526
527 /// Set [`sort_in_place_threshold_bytes`]
528 ///
529 /// [`sort_in_place_threshold_bytes`]: datafusion_common::config::ExecutionOptions::sort_in_place_threshold_bytes
530 pub fn with_sort_in_place_threshold_bytes(
531 mut self,
532 sort_in_place_threshold_bytes: usize,
533 ) -> Self {
534 self.options_mut().execution.sort_in_place_threshold_bytes =
535 sort_in_place_threshold_bytes;
536 self
537 }
538
539 /// Set [`enforce_batch_size_in_joins`]
540 ///
541 /// [`enforce_batch_size_in_joins`]: datafusion_common::config::ExecutionOptions::enforce_batch_size_in_joins
542 pub fn with_enforce_batch_size_in_joins(
543 mut self,
544 enforce_batch_size_in_joins: bool,
545 ) -> Self {
546 self.options_mut().execution.enforce_batch_size_in_joins =
547 enforce_batch_size_in_joins;
548 self
549 }
550
551 /// Get [`enforce_batch_size_in_joins`]
552 ///
553 /// [`enforce_batch_size_in_joins`]: datafusion_common::config::ExecutionOptions::enforce_batch_size_in_joins
554 pub fn enforce_batch_size_in_joins(&self) -> bool {
555 self.options.execution.enforce_batch_size_in_joins
556 }
557
558 /// Set [`enable_ansi_mode`]
559 ///
560 /// [`enable_ansi_mode`]: datafusion_common::config::ExecutionOptions::enable_ansi_mode
561 pub fn with_enable_ansi_mode(mut self, enable_ansi_mode: bool) -> Self {
562 self.options_mut().execution.enable_ansi_mode = enable_ansi_mode;
563 self
564 }
565
566 /// Convert configuration options to name-value pairs with values
567 /// converted to strings.
568 ///
569 /// Note that this method will eventually be deprecated and
570 /// replaced by [`options`].
571 ///
572 /// [`options`]: Self::options
573 pub fn to_props(&self) -> HashMap<String, String> {
574 let entries = self.options.entries();
575 let mut map = HashMap::with_capacity(entries.len());
576 // copy configs from config_options
577 for entry in entries {
578 map.insert(entry.key, entry.value.unwrap_or_default());
579 }
580
581 map
582 }
583
584 /// Add extensions.
585 ///
586 /// Extensions can be used to attach extra data to the session config -- e.g. tracing information or caches.
587 /// Extensions are opaque and the types are unknown to DataFusion itself, which makes them extremely flexible. [^1]
588 ///
589 /// Extensions are stored within an [`Arc`] so they do NOT require [`Clone`]. The are immutable. If you need to
590 /// modify their state over their lifetime -- e.g. for caches -- you need to establish some form of interior mutability.
591 ///
592 /// Extensions are indexed by their type `T`. If multiple values of the same type are provided, only the last one
593 /// will be kept.
594 ///
595 /// You may use [`get_extension`](Self::get_extension) to retrieve extensions.
596 ///
597 /// # Example
598 /// ```
599 /// use datafusion_execution::config::SessionConfig;
600 /// use std::sync::Arc;
601 ///
602 /// // application-specific extension types
603 /// struct Ext1(u8);
604 /// struct Ext2(u8);
605 /// struct Ext3(u8);
606 ///
607 /// let ext1a = Arc::new(Ext1(10));
608 /// let ext1b = Arc::new(Ext1(11));
609 /// let ext2 = Arc::new(Ext2(2));
610 ///
611 /// let cfg = SessionConfig::default()
612 /// // will only remember the last Ext1
613 /// .with_extension(Arc::clone(&ext1a))
614 /// .with_extension(Arc::clone(&ext1b))
615 /// .with_extension(Arc::clone(&ext2));
616 ///
617 /// let ext1_received = cfg.get_extension::<Ext1>().unwrap();
618 /// assert!(!Arc::ptr_eq(&ext1_received, &ext1a));
619 /// assert!(Arc::ptr_eq(&ext1_received, &ext1b));
620 ///
621 /// let ext2_received = cfg.get_extension::<Ext2>().unwrap();
622 /// assert!(Arc::ptr_eq(&ext2_received, &ext2));
623 ///
624 /// assert!(cfg.get_extension::<Ext3>().is_none());
625 /// ```
626 ///
627 /// [^1]: Compare that to [`ConfigOptions`] which only supports [`ScalarValue`] payloads.
628 pub fn with_extension<T>(mut self, ext: Arc<T>) -> Self
629 where
630 T: Send + Sync + 'static,
631 {
632 self.set_extension(ext);
633 self
634 }
635
636 /// Set extension. Pretty much the same as [`with_extension`](Self::with_extension), but take
637 /// mutable reference instead of owning it. Useful if you want to add another extension after
638 /// the [`SessionConfig`] is created.
639 ///
640 /// # Example
641 /// ```
642 /// use datafusion_execution::config::SessionConfig;
643 /// use std::sync::Arc;
644 ///
645 /// // application-specific extension types
646 /// struct Ext1(u8);
647 /// struct Ext2(u8);
648 /// struct Ext3(u8);
649 ///
650 /// let ext1a = Arc::new(Ext1(10));
651 /// let ext1b = Arc::new(Ext1(11));
652 /// let ext2 = Arc::new(Ext2(2));
653 ///
654 /// let mut cfg = SessionConfig::default();
655 ///
656 /// // will only remember the last Ext1
657 /// cfg.set_extension(Arc::clone(&ext1a));
658 /// cfg.set_extension(Arc::clone(&ext1b));
659 /// cfg.set_extension(Arc::clone(&ext2));
660 ///
661 /// let ext1_received = cfg.get_extension::<Ext1>().unwrap();
662 /// assert!(!Arc::ptr_eq(&ext1_received, &ext1a));
663 /// assert!(Arc::ptr_eq(&ext1_received, &ext1b));
664 ///
665 /// let ext2_received = cfg.get_extension::<Ext2>().unwrap();
666 /// assert!(Arc::ptr_eq(&ext2_received, &ext2));
667 ///
668 /// assert!(cfg.get_extension::<Ext3>().is_none());
669 /// ```
670 pub fn set_extension<T>(&mut self, ext: Arc<T>)
671 where
672 T: Send + Sync + 'static,
673 {
674 self.extensions.insert_arc(ext);
675 }
676
677 /// Get extension, if any for the specified type `T` exists.
678 ///
679 /// See [`with_extension`](Self::with_extension) on how to add attach extensions.
680 pub fn get_extension<T>(&self) -> Option<Arc<T>>
681 where
682 T: Send + Sync + 'static,
683 {
684 self.extensions.get_arc::<T>()
685 }
686
687 /// Change the extension of type `T` in place, and return what `f` returns.
688 ///
689 /// If there is no extension of type `T`, `f` gets `T::default()`, which is
690 /// then attached. If the extension is shared with another config, it is
691 /// cloned first, so the other config does not change.
692 ///
693 /// Use this, not [`with_extension`](Self::with_extension), when more than
694 /// one part of an application adds to the same extension. `with_extension`
695 /// replaces the extension, so it discards what other parts added.
696 ///
697 /// # Example
698 /// ```
699 /// use datafusion_execution::config::SessionConfig;
700 ///
701 /// #[derive(Clone, Default)]
702 /// struct Names(Vec<&'static str>);
703 ///
704 /// let mut cfg = SessionConfig::default();
705 /// cfg.update_extension(|names: &mut Names| names.0.push("a"));
706 /// cfg.update_extension(|names: &mut Names| names.0.push("b"));
707 ///
708 /// assert_eq!(cfg.get_extension::<Names>().unwrap().0, ["a", "b"]);
709 /// ```
710 pub fn update_extension<T, R>(&mut self, f: impl FnOnce(&mut T) -> R) -> R
711 where
712 T: Clone + Default + Send + Sync + 'static,
713 {
714 let mut ext = self.get_extension::<T>().unwrap_or_default();
715 let result = f(Arc::make_mut(&mut ext));
716 self.set_extension(ext);
717 result
718 }
719}
720
721impl From<ConfigOptions> for SessionConfig {
722 fn from(options: ConfigOptions) -> Self {
723 let options = Arc::new(options);
724 Self {
725 options,
726 ..Default::default()
727 }
728 }
729}