Skip to main content

datafusion_common/
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
5//! Runtime configuration, via [`ConfigOptions`]
6
7use arrow_ipc::CompressionType;
8
9#[cfg(feature = "parquet_encryption")]
10use crate::encryption::{FileDecryptionProperties, FileEncryptionProperties};
11use crate::error::{_config_datafusion_err, _config_err};
12use crate::format::{ExplainAnalyzeCategories, ExplainFormat, MetricType};
13use crate::parquet_config::{
14    DFParquetCompression, DFParquetEncoding, DFParquetStatistics, DFParquetWriterVersion,
15    DFTimeUnit, RowGroupRangeAssignment,
16};
17use crate::parsers::{CompressionTypeVariant, CsvQuoteStyle};
18use crate::utils::get_available_parallelism;
19use crate::{DataFusionError, Result};
20#[cfg(feature = "parquet_encryption")]
21use hex;
22use std::any::Any;
23use std::borrow::Cow;
24use std::collections::{BTreeMap, HashMap};
25use std::error::Error;
26use std::fmt::{self, Display};
27use std::num::NonZeroUsize;
28use std::str::FromStr;
29#[cfg(feature = "parquet_encryption")]
30use std::sync::Arc;
31
32/// A macro that wraps a configuration struct and automatically derives
33/// [`Default`] and [`ConfigField`] for it, allowing it to be used
34/// in the [`ConfigOptions`] configuration tree.
35///
36/// `transform` is used to normalize values before parsing.
37///
38/// For example,
39///
40/// ```ignore
41/// config_namespace! {
42///    /// Amazing config
43///    pub struct MyConfig {
44///        /// Field 1 doc
45///        field1: String, transform = str::to_lowercase, default = "".to_string()
46///
47///        /// Field 2 doc
48///        field2: usize, default = 232
49///
50///        /// Field 3 doc
51///        field3: Option<usize>, default = None
52///    }
53/// }
54/// ```
55///
56/// Will generate
57///
58/// ```ignore
59/// /// Amazing config
60/// #[derive(Debug, Clone)]
61/// #[non_exhaustive]
62/// pub struct MyConfig {
63///     /// Field 1 doc
64///     field1: String,
65///     /// Field 2 doc
66///     field2: usize,
67///     /// Field 3 doc
68///     field3: Option<usize>,
69/// }
70/// impl ConfigField for MyConfig {
71///     fn set(&mut self, key: &str, value: &str) -> Result<()> {
72///         let (key, rem) = key.split_once('.').unwrap_or((key, ""));
73///         match key {
74///             "field1" => {
75///                 let value = str::to_lowercase(value);
76///                 self.field1.set(rem, value.as_ref())
77///             },
78///             "field2" => self.field2.set(rem, value.as_ref()),
79///             "field3" => self.field3.set(rem, value.as_ref()),
80///             _ => _internal_err!(
81///                 "Config value \"{}\" not found on MyConfig",
82///                 key
83///             ),
84///         }
85///     }
86///
87///     fn visit<V: Visit>(&self, v: &mut V, key_prefix: &str, _description: &'static str) {
88///         let key = format!("{}.field1", key_prefix);
89///         let desc = "Field 1 doc";
90///         self.field1.visit(v, key.as_str(), desc);
91///         let key = format!("{}.field2", key_prefix);
92///         let desc = "Field 2 doc";
93///         self.field2.visit(v, key.as_str(), desc);
94///         let key = format!("{}.field3", key_prefix);
95///         let desc = "Field 3 doc";
96///         self.field3.visit(v, key.as_str(), desc);
97///     }
98/// }
99///
100/// impl Default for MyConfig {
101///     fn default() -> Self {
102///         Self {
103///             field1: "".to_string(),
104///             field2: 232,
105///             field3: None,
106///         }
107///     }
108/// }
109/// ```
110///
111/// NB: Misplaced commas may result in nonsensical errors
112#[macro_export]
113macro_rules! config_namespace {
114    (
115        $(#[doc = $struct_d:tt])* // Struct-level documentation attributes
116        $(#[deprecated($($struct_depr:tt)*)])? // Optional struct-level deprecated attribute
117        $(#[allow($($struct_de:tt)*)])?
118        $vis:vis struct $struct_name:ident {
119            $(
120                $(#[doc = $d:tt])* // Field-level documentation attributes
121                $(#[deprecated($($field_depr:tt)*)])? // Optional field-level deprecated attribute
122                $(#[allow($($field_de:tt)*)])?
123                $field_vis:vis $field_name:ident : $field_type:ty,
124                $(warn = $warn:expr,)?
125                $(transform = $transform:expr,)?
126                default = $default:expr
127            )*$(,)*
128        }
129    ) => {
130        $(#[doc = $struct_d])* // Apply struct documentation
131        $(#[deprecated($($struct_depr)*)])? // Apply struct deprecation
132        $(#[allow($($struct_de)*)])?
133        #[derive(Debug, Clone, PartialEq)]
134        $vis struct $struct_name {
135            $(
136                $(#[doc = $d])* // Apply field documentation
137                $(#[deprecated($($field_depr)*)])? // Apply field deprecation
138                $(#[allow($($field_de)*)])?
139                $field_vis $field_name: $field_type,
140            )*
141        }
142
143        impl $crate::config::ConfigField for $struct_name {
144            fn set(&mut self, key: &str, value: &str) -> $crate::error::Result<()> {
145                let (key, rem) = key.split_once('.').unwrap_or((key, ""));
146                match key {
147                    $(
148                        stringify!($field_name) => {
149                            // Safely apply deprecated attribute if present
150                            // $(#[allow(deprecated)])?
151                            {
152                                $(let value = $transform(value);)? // Apply transformation if specified
153                                let ret = self.$field_name.set(rem, value.as_ref());
154
155                                $(if !$warn.is_empty() {
156                                    let default: $field_type = $default;
157                                    if default != self.$field_name {
158                                        log::warn!($warn);
159                                    }
160                                })? // Log warning if specified, and the value is not the default
161                                ret
162                            }
163                        },
164                    )*
165                    _ => return $crate::error::_config_err!(
166                        "Config value \"{}\" not found on {}", key, stringify!($struct_name)
167                    )
168                }
169            }
170
171            fn visit<V: $crate::config::Visit>(&self, v: &mut V, key_prefix: &str, _description: &'static str) {
172                $(
173                    let key = format!(concat!("{}.", stringify!($field_name)), key_prefix);
174                    let desc = concat!($($d),*).trim();
175                    self.$field_name.visit(v, key.as_str(), desc);
176                )*
177            }
178
179            fn reset(&mut self, key: &str) -> $crate::error::Result<()> {
180                let (key, rem) = key.split_once('.').unwrap_or((key, ""));
181                match key {
182                    $(
183                        stringify!($field_name) => {
184                                    {
185                                if rem.is_empty() {
186                                    let default_value: $field_type = $default;
187                                    self.$field_name = default_value;
188                                    Ok(())
189                                } else {
190                                    self.$field_name.reset(rem)
191                                }
192                            }
193                        },
194                    )*
195                    _ => $crate::error::_config_err!(
196                        "Config value \"{}\" not found on {}",
197                        key,
198                        stringify!($struct_name)
199                    ),
200                }
201            }
202        }
203        impl Default for $struct_name {
204            fn default() -> Self {
205                Self {
206                    $($field_name: $default),*
207                }
208            }
209        }
210    }
211}
212
213config_namespace! {
214    /// Options related to catalog and directory scanning
215    ///
216    /// See also: [`SessionConfig`]
217    ///
218    /// [`SessionConfig`]: https://docs.rs/datafusion/latest/datafusion/prelude/struct.SessionConfig.html
219    pub struct CatalogOptions {
220        /// Whether the default catalog and schema should be created automatically.
221        pub create_default_catalog_and_schema: bool, default = true
222
223        /// The default catalog name - this impacts what SQL queries use if not specified
224        pub default_catalog: String, default = "datafusion".to_string()
225
226        /// The default schema name - this impacts what SQL queries use if not specified
227        pub default_schema: String, default = "public".to_string()
228
229        /// Should DataFusion provide access to `information_schema`
230        /// virtual tables for displaying schema information
231        pub information_schema: bool, default = false
232
233        /// When set together with `information_schema`, the `information_schema`
234        /// of each catalog only describes the objects in that catalog. When not
235        /// set, the `information_schema` of each catalog describes all catalogs.
236        pub partition_information_schema: bool, default = false
237
238        /// Location scanned to load tables for `default` schema
239        pub location: Option<String>, default = None
240
241        /// Type of `TableProvider` to use when loading `default` schema
242        pub format: Option<String>, default = None
243
244        /// Default value for `format.has_header` for `CREATE EXTERNAL TABLE`
245        /// if not specified explicitly in the statement.
246        pub has_header: bool, default = true
247
248        /// Specifies whether newlines in (quoted) CSV values are supported.
249        ///
250        /// This is the default value for `format.newlines_in_values` for `CREATE EXTERNAL TABLE`
251        /// if not specified explicitly in the statement.
252        ///
253        /// Parsing newlines in quoted values may be affected by execution behaviour such as
254        /// parallel file scanning. Setting this to `true` ensures that newlines in values are
255        /// parsed successfully, which may reduce performance.
256        pub newlines_in_values: bool, default = false
257    }
258}
259
260config_namespace! {
261    /// Options related to SQL parser
262    ///
263    /// See also: [`SessionConfig`]
264    ///
265    /// [`SessionConfig`]: https://docs.rs/datafusion/latest/datafusion/prelude/struct.SessionConfig.html
266    pub struct SqlParserOptions {
267        /// When set to true, SQL parser will parse float as decimal type
268        pub parse_float_as_decimal: bool, default = false
269
270        /// When set to true, SQL parser will normalize ident (convert ident to lowercase when not quoted)
271        pub enable_ident_normalization: bool, default = true
272
273        /// When set to true, SQL parser will normalize options value (convert value to lowercase).
274        /// Note that this option is ignored and will be removed in the future. All case-insensitive values
275        /// are normalized automatically.
276        pub enable_options_value_normalization: bool, warn = "`enable_options_value_normalization` is deprecated and ignored", default = false
277
278        /// Configure the SQL dialect used by DataFusion's parser.
279        /// The configuration reference lists the supported values from [`Dialect::available`].
280        pub dialect: Dialect, default = Dialect::Generic
281        // no need to lowercase because `sqlparser::dialect_from_str`] is case-insensitive
282
283        /// If true, permit lengths for `VARCHAR` such as `VARCHAR(20)`, but
284        /// ignore the length. If false, error if a `VARCHAR` with a length is
285        /// specified. The Arrow type system does not have a notion of maximum
286        /// string length and thus DataFusion can not enforce such limits.
287        pub support_varchar_with_length: bool, default = true
288
289        /// If true, string types (VARCHAR, CHAR, Text, and String) are mapped to `Utf8View` during SQL planning.
290        /// If false, they are mapped to `Utf8`.
291        /// Default is true.
292        pub map_string_types_to_utf8view: bool, default = true
293
294        /// When set to true, the source locations relative to the original SQL
295        /// query (i.e. [`Span`](https://docs.rs/sqlparser/latest/sqlparser/tokenizer/struct.Span.html)) will be collected
296        /// and recorded in the logical plan nodes.
297        pub collect_spans: bool, default = false
298
299        /// Specifies the recursion depth limit when parsing complex SQL Queries
300        pub recursion_limit: ConfigNonZeroUsize, default = non_zero_usize_default(51)
301
302        /// Specifies the default null ordering for query results. There are 4 options:
303        /// - `nulls_max`: Nulls appear last in ascending order.
304        /// - `nulls_min`: Nulls appear first in ascending order.
305        /// - `nulls_first`: Nulls always be first in any order.
306        /// - `nulls_last`: Nulls always be last in any order.
307        ///
308        /// By default, `nulls_max` is used to follow Postgres's behavior.
309        /// postgres rule: <https://www.postgresql.org/docs/current/queries-order.html>
310        pub default_null_ordering: String, default = "nulls_max".to_string()
311
312        /// When set to true, DataFusion may remove `ORDER BY` clauses from
313        /// subqueries or CTEs during SQL planning when their ordering cannot
314        /// affect the result, such as when no `LIMIT` or other
315        /// order-sensitive operator depends on them.
316        ///
317        /// Disable this option to preserve explicit subquery ordering in the
318        /// planned query.
319        pub enable_subquery_sort_elimination: bool, default = true
320    }
321}
322
323/// Metadata for a SQL dialect supported by DataFusion configuration.
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325#[non_exhaustive]
326pub struct DialectInfo {
327    pub dialect: Dialect,
328    pub canonical_name: &'static str,
329    pub display_name: &'static str,
330    pub aliases: &'static [&'static str],
331}
332
333// Keep this key in sync with the `SqlParserOptions::dialect` config path.
334const SQL_PARSER_DIALECT_CONFIG_KEY: &str = "datafusion.sql_parser.dialect";
335
336macro_rules! dialect_display_list {
337    ($($display_name:literal),+ $(,)?) => {
338        dialect_display_list!(@acc [] $($display_name),+)
339    };
340    (@acc [$($acc:tt)*] $last:literal) => {
341        concat!($($acc)* $last)
342    };
343    (@acc [$($acc:tt)*] $next:literal, $($rest:literal),+) => {
344        dialect_display_list!(@acc [$($acc)* $next, ", ",] $($rest),+)
345    };
346}
347
348macro_rules! dialect_metadata {
349    (
350        default: $default_variant:ident;
351        $(
352            $variant:ident {
353                canonical_name: $canonical_name:literal,
354                display_name: $display_name:literal,
355                aliases: [$($alias:literal),* $(,)?],
356            }
357        ),+ $(,)?
358    ) => {
359        /// This is the SQL dialect used by DataFusion's parser.
360        /// This mirrors [sqlparser::dialect::Dialect](https://docs.rs/sqlparser/latest/sqlparser/dialect/trait.Dialect.html)
361        /// trait in order to offer an easier API and avoid adding the `sqlparser` dependency
362        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
363        pub enum Dialect {
364            $($variant,)+
365        }
366
367        impl Default for Dialect {
368            fn default() -> Self {
369                Self::$default_variant
370            }
371        }
372
373        const DIALECT_INFOS: &[DialectInfo] = &[
374            $(
375                DialectInfo {
376                    dialect: Dialect::$variant,
377                    canonical_name: $canonical_name,
378                    display_name: $display_name,
379                    aliases: &[$($alias),*],
380                },
381            )+
382        ];
383
384        const AVAILABLE_DIALECTS: &str = dialect_display_list!($($display_name),+);
385        const DIALECT_CONFIG_DESCRIPTION: &str = concat!(
386            "Configure the SQL dialect used by DataFusion's parser; supported values include: ",
387            dialect_display_list!($($display_name),+),
388            "."
389        );
390    };
391}
392
393dialect_metadata! {
394    default: Generic;
395    Generic {
396        canonical_name: "generic",
397        display_name: "Generic",
398        aliases: [],
399    },
400    MySQL {
401        canonical_name: "mysql",
402        display_name: "MySQL",
403        aliases: [],
404    },
405    PostgreSQL {
406        canonical_name: "postgresql",
407        display_name: "PostgreSQL",
408        aliases: ["postgres"],
409    },
410    Hive {
411        canonical_name: "hive",
412        display_name: "Hive",
413        aliases: [],
414    },
415    SQLite {
416        canonical_name: "sqlite",
417        display_name: "SQLite",
418        aliases: [],
419    },
420    Snowflake {
421        canonical_name: "snowflake",
422        display_name: "Snowflake",
423        aliases: [],
424    },
425    Redshift {
426        canonical_name: "redshift",
427        display_name: "Redshift",
428        aliases: [],
429    },
430    MsSQL {
431        canonical_name: "mssql",
432        display_name: "MsSQL",
433        aliases: [],
434    },
435    ClickHouse {
436        canonical_name: "clickhouse",
437        display_name: "ClickHouse",
438        aliases: [],
439    },
440    BigQuery {
441        canonical_name: "bigquery",
442        display_name: "BigQuery",
443        aliases: [],
444    },
445    Ansi {
446        canonical_name: "ansi",
447        display_name: "Ansi",
448        aliases: [],
449    },
450    DuckDB {
451        canonical_name: "duckdb",
452        display_name: "DuckDB",
453        aliases: [],
454    },
455    Databricks {
456        canonical_name: "databricks",
457        display_name: "Databricks",
458        aliases: [],
459    },
460    Spark {
461        canonical_name: "spark",
462        display_name: "Spark",
463        aliases: ["sparksql"],
464    },
465}
466
467impl Dialect {
468    /// Return metadata for all supported dialects.
469    pub fn metadata() -> &'static [DialectInfo] {
470        DIALECT_INFOS
471    }
472
473    /// Return all supported dialect names, for use in error messages.
474    pub fn available() -> &'static str {
475        AVAILABLE_DIALECTS
476    }
477
478    fn info(&self) -> &'static DialectInfo {
479        DIALECT_INFOS
480            .iter()
481            .find(|info| info.dialect == *self)
482            .expect("all Dialect variants are listed in DIALECT_INFOS")
483    }
484}
485
486impl AsRef<str> for Dialect {
487    fn as_ref(&self) -> &str {
488        self.info().canonical_name
489    }
490}
491
492impl FromStr for Dialect {
493    type Err = DataFusionError;
494
495    fn from_str(s: &str) -> Result<Self, Self::Err> {
496        for info in DIALECT_INFOS {
497            if info.canonical_name.eq_ignore_ascii_case(s)
498                || info
499                    .aliases
500                    .iter()
501                    .any(|alias| alias.eq_ignore_ascii_case(s))
502            {
503                return Ok(info.dialect);
504            }
505        }
506
507        Err(DataFusionError::Configuration(format!(
508            "Invalid Dialect: {s}. Expected one of: {}",
509            Self::available()
510        )))
511    }
512}
513
514impl ConfigField for Dialect {
515    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
516        let description = if key == SQL_PARSER_DIALECT_CONFIG_KEY {
517            DIALECT_CONFIG_DESCRIPTION
518        } else {
519            description
520        };
521        v.some(key, self, description)
522    }
523
524    fn set(&mut self, _: &str, value: &str) -> Result<()> {
525        *self = Self::from_str(value)?;
526        Ok(())
527    }
528}
529
530impl Display for Dialect {
531    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532        let str = self.as_ref();
533        write!(f, "{str}")
534    }
535}
536
537#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
538pub enum SpillCompression {
539    Zstd,
540    Lz4Frame,
541    #[default]
542    Uncompressed,
543}
544
545impl FromStr for SpillCompression {
546    type Err = DataFusionError;
547
548    fn from_str(s: &str) -> Result<Self, Self::Err> {
549        match s.to_ascii_lowercase().as_str() {
550            "zstd" => Ok(Self::Zstd),
551            "lz4_frame" => Ok(Self::Lz4Frame),
552            "uncompressed" | "" => Ok(Self::Uncompressed),
553            other => Err(DataFusionError::Configuration(format!(
554                "Invalid Spill file compression type: {other}. Expected one of: zstd, lz4_frame, uncompressed"
555            ))),
556        }
557    }
558}
559
560impl ConfigField for SpillCompression {
561    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
562        v.some(key, self, description)
563    }
564
565    fn set(&mut self, _: &str, value: &str) -> Result<()> {
566        *self = SpillCompression::from_str(value)?;
567        Ok(())
568    }
569}
570
571impl Display for SpillCompression {
572    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
573        let str = match self {
574            Self::Zstd => "zstd",
575            Self::Lz4Frame => "lz4_frame",
576            Self::Uncompressed => "uncompressed",
577        };
578        write!(f, "{str}")
579    }
580}
581
582/// A `usize` configuration value that rejects zero when set from strings.
583///
584/// Use this for options where zero is never a meaningful runtime value.
585/// Invalid values return a configuration error through [`ConfigField`].
586#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
587pub struct ConfigNonZeroUsize(NonZeroUsize);
588
589/// Private helper for hard-coded defaults in `config_namespace!`, which cannot
590/// use `?`. All external construction should use [`ConfigNonZeroUsize::try_new`].
591const fn non_zero_usize_default(value: usize) -> ConfigNonZeroUsize {
592    match NonZeroUsize::new(value) {
593        Some(value) => ConfigNonZeroUsize(value),
594        None => panic!("value must be greater than 0"),
595    }
596}
597
598impl ConfigNonZeroUsize {
599    /// Creates a [`ConfigNonZeroUsize`], returning a configuration error if
600    /// `value` is zero.
601    pub fn try_new(value: usize) -> Result<Self> {
602        NonZeroUsize::new(value)
603            .map(Self)
604            .ok_or_else(|| _config_datafusion_err!("value must be greater than 0"))
605    }
606
607    /// Returns the wrapped `usize`.
608    pub const fn get(self) -> usize {
609        self.0.get()
610    }
611}
612
613impl From<ConfigNonZeroUsize> for usize {
614    fn from(value: ConfigNonZeroUsize) -> Self {
615        value.get()
616    }
617}
618
619impl FromStr for ConfigNonZeroUsize {
620    type Err = DataFusionError;
621
622    fn from_str(s: &str) -> Result<Self, Self::Err> {
623        Self::try_new(default_config_transform(s)?)
624    }
625}
626
627impl ConfigField for ConfigNonZeroUsize {
628    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
629        v.some(key, self, description)
630    }
631
632    fn set(&mut self, key: &str, value: &str) -> Result<()> {
633        if !key.is_empty() {
634            return _config_err!(
635                "Config field batch_size is a scalar ConfigNonZeroUsize and does not have nested field \"{}\"",
636                key
637            );
638        }
639
640        *self = ConfigNonZeroUsize::from_str(value)?;
641        Ok(())
642    }
643
644    fn reset(&mut self, key: &str) -> Result<()> {
645        if key.is_empty() {
646            Ok(())
647        } else {
648            _config_err!(
649                "Config field batch_size is a scalar ConfigNonZeroUsize and does not have nested field \"{}\"",
650                key
651            )
652        }
653    }
654}
655
656impl Display for ConfigNonZeroUsize {
657    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
658        write!(f, "{}", self.get())
659    }
660}
661
662/// A `usize` configuration value that rejects 0 and 1 when set from strings.
663///
664/// Use this for options whose consumer divides the value in half to size an
665/// internal buffer (e.g. a bounded channel capacity): values below 2 would
666/// round down to a zero-capacity buffer and panic. Invalid values return a
667/// configuration error through [`ConfigField`] instead.
668#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
669pub struct ConfigMinTwoUsize(usize);
670
671/// Private helper for hard-coded defaults in `config_namespace!`, which cannot
672/// use `?`. All external construction should use [`ConfigMinTwoUsize::try_new`].
673const fn min_two_usize_default(value: usize) -> ConfigMinTwoUsize {
674    if value >= 2 {
675        ConfigMinTwoUsize(value)
676    } else {
677        panic!("value must be at least 2")
678    }
679}
680
681impl ConfigMinTwoUsize {
682    /// Creates a [`ConfigMinTwoUsize`], returning a configuration error if
683    /// `value` is less than 2.
684    pub fn try_new(value: usize) -> Result<Self> {
685        if value >= 2 {
686            Ok(Self(value))
687        } else {
688            _config_err!("value must be at least 2")
689        }
690    }
691
692    /// Returns the wrapped `usize`.
693    pub const fn get(self) -> usize {
694        self.0
695    }
696}
697
698impl From<ConfigMinTwoUsize> for usize {
699    fn from(value: ConfigMinTwoUsize) -> Self {
700        value.get()
701    }
702}
703
704impl FromStr for ConfigMinTwoUsize {
705    type Err = DataFusionError;
706
707    fn from_str(s: &str) -> Result<Self, Self::Err> {
708        Self::try_new(default_config_transform(s)?)
709    }
710}
711
712impl ConfigField for ConfigMinTwoUsize {
713    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
714        v.some(key, self, description)
715    }
716
717    fn set(&mut self, key: &str, value: &str) -> Result<()> {
718        if !key.is_empty() {
719            return _config_err!(
720                "Config field max_buffered_batches_per_output_file is a scalar ConfigMinTwoUsize and does not have nested field \"{}\"",
721                key
722            );
723        }
724
725        *self = ConfigMinTwoUsize::from_str(value)?;
726        Ok(())
727    }
728
729    fn reset(&mut self, key: &str) -> Result<()> {
730        if key.is_empty() {
731            Ok(())
732        } else {
733            _config_err!(
734                "Config field max_buffered_batches_per_output_file is a scalar ConfigMinTwoUsize and does not have nested field \"{}\"",
735                key
736            )
737        }
738    }
739}
740
741impl Display for ConfigMinTwoUsize {
742    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
743        write!(f, "{}", self.get())
744    }
745}
746
747/// Used for [`OptimizerOptions::default_filter_selectivity`] to represent
748/// an integer percentage value, when valid values are 0 to 100 inclusive.
749#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
750pub struct ConfigFilterSelectivity(u8);
751
752/// Private helper for hard-coded defaults in `config_namespace!`, which cannot
753/// use `?`. All external construction should use
754/// [`ConfigFilterSelectivity::try_new`].
755const fn filter_selectivity_default(value: u8) -> ConfigFilterSelectivity {
756    if value <= 100 {
757        ConfigFilterSelectivity(value)
758    } else {
759        panic!("value must be between 0 and 100")
760    }
761}
762
763impl ConfigFilterSelectivity {
764    fn try_from_i64(value: i64) -> Result<Self> {
765        if (0..=100).contains(&value) {
766            Ok(Self(value as u8))
767        } else {
768            _config_err!("value must be between 0 and 100, got {value}")
769        }
770    }
771
772    /// Creates a [`ConfigFilterSelectivity`], returning a configuration error
773    /// if `value` is greater than 100.
774    pub fn try_new(value: u8) -> Result<Self> {
775        Self::try_from_i64(i64::from(value))
776    }
777
778    /// Returns the wrapped `u8`.
779    pub const fn get(self) -> u8 {
780        self.0
781    }
782}
783
784impl From<ConfigFilterSelectivity> for u8 {
785    fn from(value: ConfigFilterSelectivity) -> Self {
786        value.get()
787    }
788}
789
790impl FromStr for ConfigFilterSelectivity {
791    type Err = DataFusionError;
792
793    fn from_str(s: &str) -> Result<Self, Self::Err> {
794        Self::try_from_i64(default_config_transform::<i64>(s)?)
795    }
796}
797
798impl ConfigField for ConfigFilterSelectivity {
799    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
800        v.some(key, self, description)
801    }
802
803    fn set(&mut self, key: &str, value: &str) -> Result<()> {
804        if !key.is_empty() {
805            return _config_err!(
806                "Config field default_filter_selectivity is a scalar ConfigFilterSelectivity and does not have nested field \"{}\"",
807                key
808            );
809        }
810
811        *self = ConfigFilterSelectivity::from_str(value)?;
812        Ok(())
813    }
814
815    fn reset(&mut self, key: &str) -> Result<()> {
816        if key.is_empty() {
817            Ok(())
818        } else {
819            _config_err!(
820                "Config field default_filter_selectivity is a scalar ConfigFilterSelectivity and does not have nested field \"{}\"",
821                key
822            )
823        }
824    }
825}
826
827impl Display for ConfigFilterSelectivity {
828    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
829        write!(f, "{}", self.get())
830    }
831}
832
833/// Policy for handling duplicate keys in Spark-compatible map-construction
834/// functions (`map_from_arrays`, `map_from_entries`, `str_to_map`). Mirrors
835/// Spark's [`spark.sql.mapKeyDedupPolicy`](https://github.com/apache/spark/blob/cf3a34e19dfcf70e2d679217ff1ba21302212472/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala#L4961).
836#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
837pub enum MapKeyDedupPolicy {
838    /// Raise `[DUPLICATED_MAP_KEY]` at runtime on any duplicate key.
839    #[default]
840    Exception,
841    /// Keep the last occurrence of each duplicate key.
842    LastWin,
843}
844
845impl FromStr for MapKeyDedupPolicy {
846    type Err = DataFusionError;
847
848    fn from_str(s: &str) -> Result<Self, Self::Err> {
849        match s.to_ascii_uppercase().as_str() {
850            "EXCEPTION" => Ok(Self::Exception),
851            "LAST_WIN" => Ok(Self::LastWin),
852            other => Err(DataFusionError::Configuration(format!(
853                "Invalid MapKeyDedupPolicy: {other}. Expected one of: EXCEPTION, LAST_WIN"
854            ))),
855        }
856    }
857}
858
859impl ConfigField for MapKeyDedupPolicy {
860    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
861        v.some(key, self, description)
862    }
863
864    fn set(&mut self, _: &str, value: &str) -> Result<()> {
865        *self = MapKeyDedupPolicy::from_str(value)?;
866        Ok(())
867    }
868}
869
870impl Display for MapKeyDedupPolicy {
871    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
872        let str = match self {
873            Self::Exception => "EXCEPTION",
874            Self::LastWin => "LAST_WIN",
875        };
876        write!(f, "{str}")
877    }
878}
879
880impl From<SpillCompression> for Option<CompressionType> {
881    fn from(c: SpillCompression) -> Self {
882        match c {
883            SpillCompression::Zstd => Some(CompressionType::ZSTD),
884            SpillCompression::Lz4Frame => Some(CompressionType::LZ4_FRAME),
885            SpillCompression::Uncompressed => None,
886        }
887    }
888}
889
890/// The directory name Hive compliant writers use in place of a null partition value, and the
891/// default for [`ExecutionOptions::listing_table_hive_default_partition_name`].
892pub const HIVE_DEFAULT_PARTITION_NAME: &str = "__HIVE_DEFAULT_PARTITION__";
893
894config_namespace! {
895    /// Options related to query execution
896    ///
897    /// See also: [`SessionConfig`]
898    ///
899    /// [`SessionConfig`]: https://docs.rs/datafusion/latest/datafusion/prelude/struct.SessionConfig.html
900    pub struct ExecutionOptions {
901        /// Default batch size while creating new batches, it's especially useful for
902        /// buffer-in-memory batches since creating tiny batches would result in too much
903        /// metadata memory consumption
904        pub batch_size: ConfigNonZeroUsize, default = non_zero_usize_default(8192)
905
906        /// A perfect hash join (see `HashJoinExec` for more details) will be considered
907        /// if the range of keys (max - min) on the build side is < this threshold.
908        /// This provides a fast path for joins with very small key ranges,
909        /// bypassing the density check.
910        ///
911        /// Currently only supports cases where build_side.num_rows() < u32::MAX.
912        /// Support for build_side.num_rows() >= u32::MAX will be added in the future.
913        pub perfect_hash_join_small_build_threshold: usize, default = 1024
914
915        /// The minimum required density of join keys on the build side to consider a
916        /// perfect hash join (see `HashJoinExec` for more details). Density is calculated as:
917        /// `(number of rows) / (max_key - min_key + 1)`.
918        /// A perfect hash join may be used if the actual key density > this
919        /// value.
920        ///
921        /// Currently only supports cases where build_side.num_rows() < u32::MAX.
922        /// Support for build_side.num_rows() >= u32::MAX will be added in the future.
923        pub perfect_hash_join_min_key_density: f64, default = 0.15
924
925        /// When set to true, record batches will be examined between each operator and
926        /// small batches will be coalesced into larger batches. This is helpful when there
927        /// are highly selective filters or joins that could produce tiny output batches. The
928        /// target batch size is determined by the configuration setting
929        pub coalesce_batches: bool, default = true
930
931        /// Should DataFusion collect statistics when first creating a table.
932        /// Has no effect after the table is created. Defaults to true.
933        pub collect_statistics: bool, default = true
934
935        /// Number of partitions for query execution. Increasing partitions can increase
936        /// concurrency.
937        ///
938        /// Defaults to the number of CPU cores on the system
939        pub target_partitions: usize, transform = ExecutionOptions::normalized_parallelism, default = get_available_parallelism()
940
941        /// The default time zone
942        ///
943        /// Some functions, e.g. `now`, return timestamps in this time zone.
944        /// This is also used to interpret timezone-naive timestamps in
945        /// comparisons and subtraction with timezone-aware timestamps.
946        pub time_zone: Option<ConfigTimeZone>, default = None
947
948        /// Parquet options
949        pub parquet: ParquetOptions, default = Default::default()
950
951        /// Fan-out during initial physical planning.
952        ///
953        /// This is mostly use to plan `UNION` children in parallel.
954        ///
955        /// Defaults to the number of CPU cores on the system
956        pub planning_concurrency: usize, transform = ExecutionOptions::normalized_parallelism, default = get_available_parallelism()
957
958        /// When set to true, skips verifying that the schema produced by
959        /// planning the input of `LogicalPlan::Aggregate` exactly matches the
960        /// schema of the input plan.
961        ///
962        /// When set to false, if the schema does not match exactly
963        /// (including nullability and metadata), a planning error will be raised.
964        ///
965        /// This is used to workaround bugs in the planner that are now caught by
966        /// the new schema verification step.
967        pub skip_physical_aggregate_schema_check: bool, default = false
968
969        /// Whether aggregation uses the implementation from the major refactor
970        /// completed in the 56.0.0 release. When set to `false`, aggregation
971        /// falls back to the implementation used before 55.0.0.
972        ///
973        /// The fallback exists only as a workaround for bugs in the new
974        /// implementation and will be removed, together with this option, after
975        /// the 56.0.0 release.
976        ///
977        /// See <https://github.com/apache/datafusion/issues/22710> for details.
978        pub enable_migration_aggregate: bool, default = true
979
980        /// Sets the compression codec used when spilling data to disk.
981        ///
982        /// Since datafusion writes spill files using the Arrow IPC Stream format,
983        /// only codecs supported by the Arrow IPC Stream Writer are allowed.
984        /// Valid values are: uncompressed, lz4_frame, zstd.
985        /// Note: lz4_frame offers faster (de)compression, but typically results in
986        /// larger spill files. In contrast, zstd achieves
987        /// higher compression ratios at the cost of slower (de)compression speed.
988        pub spill_compression: SpillCompression, default = SpillCompression::Uncompressed
989
990        /// Specifies the reserved memory for each spillable sort operation to
991        /// facilitate an in-memory merge.
992        ///
993        /// When a sort operation spills to disk, the in-memory data must be
994        /// sorted and merged before being written to a file. This setting reserves
995        /// a specific amount of memory for that in-memory sort/merge process.
996        ///
997        /// Note: This setting is irrelevant if the sort operation cannot spill
998        /// (i.e., if there's no `DiskManager` configured).
999        pub sort_spill_reservation_bytes: usize, default = 10 * 1024 * 1024
1000
1001        /// When sorting, below what size should data be concatenated
1002        /// and sorted in a single RecordBatch rather than sorted in
1003        /// batches and merged.
1004        pub sort_in_place_threshold_bytes: usize, default = 1024 * 1024
1005
1006        /// Maximum buffer capacity (in bytes) per partition for BufferExec
1007        /// inserted during sort pushdown optimization.
1008        ///
1009        /// When PushdownSort eliminates a SortExec under SortPreservingMergeExec,
1010        /// a BufferExec is inserted to replace SortExec's buffering role. This
1011        /// prevents I/O stalls by allowing the scan to run ahead of the merge.
1012        ///
1013        /// This uses strictly less memory than the SortExec it replaces (which
1014        /// buffers the entire partition). The buffer respects the global memory
1015        /// pool limit. Setting this to a large value is safe — actual memory
1016        /// usage is bounded by partition size and global memory limits.
1017        pub sort_pushdown_buffer_capacity: usize, default = 1024 * 1024 * 1024
1018
1019        /// Maximum size in bytes for individual spill files before rotating to a new file.
1020        ///
1021        /// When operators spill data to disk (e.g., RepartitionExec), they write
1022        /// multiple batches to the same file until this size limit is reached, then rotate
1023        /// to a new file. This reduces syscall overhead compared to one-file-per-batch
1024        /// while preventing files from growing too large.
1025        ///
1026        /// A larger value reduces file creation overhead but may hold more disk space.
1027        /// A smaller value creates more files but allows finer-grained space reclamation
1028        /// as files can be deleted once fully consumed.
1029        ///
1030        /// Now only `RepartitionExec` supports this spill file rotation feature, other spilling operators
1031        /// may create spill files larger than the limit.
1032        ///
1033        /// Default: 128 MB
1034        pub max_spill_file_size_bytes: ConfigNonZeroUsize, default = non_zero_usize_default(128 * 1024 * 1024)
1035
1036        /// Enables the memory-limited fallback for `NestedLoopJoinExec` join
1037        /// types that emit unmatched left rows in the final output (LEFT, LEFT
1038        /// SEMI, LEFT ANTI, LEFT MARK, FULL) when the right side has multiple
1039        /// partitions.
1040        ///
1041        /// This fallback shares left-side state (the current left chunk, the
1042        /// visited bitmap and the probe-thread counter) across all right-side
1043        /// partitions, which assumes every partition runs in the same process.
1044        /// Distributed engines that execute each output partition as an
1045        /// independent task (e.g. Ballista, datafusion-distributed) give each
1046        /// task its own copy
1047        /// of this state and poll only one partition, so the cross-partition
1048        /// counter never reaches zero and the fallback would stall. Such
1049        /// engines should set this to `false`: the coordinated fallback is then
1050        /// disabled for left-emitting multi-partition joins, which instead fail
1051        /// with a resource-exhaustion error under memory pressure rather than
1052        /// deadlocking. Single-partition and non-left-emitting joins are
1053        /// unaffected and always keep the fallback.
1054        pub enable_nlj_coordinated_fallback: bool, default = true
1055
1056        /// Number of files to read in parallel when inferring schema and statistics
1057        pub meta_fetch_concurrency: ConfigNonZeroUsize, default = non_zero_usize_default(32)
1058
1059        /// Guarantees a minimum level of output files running in parallel.
1060        /// RecordBatches will be distributed in round robin fashion to each
1061        /// parallel writer. Each writer is closed and a new file opened once
1062        /// soft_max_rows_per_output_file or soft_max_bytes_per_output_file is reached.
1063        pub minimum_parallel_output_files: ConfigNonZeroUsize, default = non_zero_usize_default(4)
1064
1065        /// Target number of rows in output files when writing multiple.
1066        /// This is a soft max, so it can be exceeded slightly. There also
1067        /// will be one file smaller than the limit if the total
1068        /// number of rows written is not roughly divisible by the soft max
1069        pub soft_max_rows_per_output_file: ConfigNonZeroUsize, default = non_zero_usize_default(50000000)
1070
1071        /// Target encoded size in bytes of output files when writing multiple.
1072        /// Writers asynchronously report the cumulative encoded size as they
1073        /// process RecordBatches. The final file size may exceed this limit due
1074        /// to batches buffered before the limit is observed, the size of a batch,
1075        /// and file metadata written when the file is finalized.
1076        pub soft_max_bytes_per_output_file: ConfigNonZeroUsize, default = non_zero_usize_default(4294967295)
1077
1078        /// This is the maximum number of RecordBatches buffered
1079        /// for each output file being worked. Higher values can potentially
1080        /// give faster write performance at the cost of higher peak
1081        /// memory consumption.
1082        ///
1083        /// This budget is split evenly between two independent points in the
1084        /// write pipeline (see the demuxer diagram in #7791): how many files
1085        /// can be in flight from the demuxer to a writer task, and how many
1086        /// RecordBatches are buffered for a single file's writer. Must be at
1087        /// least 2 so each half gets at least 1 unit of buffering - 0 or 1
1088        /// would leave one side with a zero-capacity channel and panic at
1089        /// write time.
1090        pub max_buffered_batches_per_output_file: ConfigMinTwoUsize, default = min_two_usize_default(2)
1091
1092        /// Should sub directories be ignored when scanning directories for data
1093        /// files. Defaults to true (ignores subdirectories), consistent with
1094        /// Hive. Note that this setting does not affect reading partitioned
1095        /// tables (e.g. `/table/year=2021/month=01/data.parquet`).
1096        pub listing_table_ignore_subdirectory: bool, default = true
1097
1098        /// Should a `ListingTable` created through the `ListingTableFactory` infer table
1099        /// partitions from Hive compliant directories. Defaults to true (partition columns are
1100        /// inferred and will be represented in the table schema).
1101        pub listing_table_factory_infer_partitions: bool, default = true
1102
1103        /// The directory name Hive compliant writers use in place of a null partition
1104        /// value, e.g. `/table/date=__HIVE_DEFAULT_PARTITION__/data.parquet`. Partition
1105        /// values equal to this name are read as NULL, as Hive, Spark and Impala do, and
1106        /// partitioned writes reject them. Corresponds to Hive's
1107        /// `hive.exec.default.partition.name`. Set this to the empty string to read and
1108        /// write such values as the literal directory name instead.
1109        pub listing_table_hive_default_partition_name: String, default = HIVE_DEFAULT_PARTITION_NAME.to_string()
1110
1111        /// Should DataFusion support recursive CTEs
1112        pub enable_recursive_ctes: bool, default = true
1113
1114        /// Attempt to eliminate sorts by packing & sorting files with non-overlapping
1115        /// statistics into the same file groups.
1116        /// Currently experimental
1117        pub split_file_groups_by_statistics: bool, default = false
1118
1119        /// Should DataFusion keep the columns used for partition_by in the output RecordBatches
1120        pub keep_partition_by_columns: bool, default = false
1121
1122        /// When `true` (the default), DataFusion's built-in file scans
1123        /// dynamically rebalance files across partitions at query execution
1124        /// time: a partition that goes idle reads files (or byte-range morsels)
1125        /// originally assigned to a sibling partition, which keeps all
1126        /// partitions busy in a single process.
1127        ///
1128        /// Executors that depend on the plan-time partition assignment — such as
1129        /// Ballista and datafusion-distributed, which run each partition as an
1130        /// isolated task and never poll the siblings — should set this to
1131        /// `false` so each partition reads only its own file group and no
1132        /// runtime reassignment occurs.
1133        pub enable_file_stream_work_stealing: bool, default = true
1134
1135        /// Aggregation ratio (number of distinct groups / number of input rows)
1136        /// threshold for skipping partial aggregation. If the value is greater
1137        /// then partial aggregation will skip aggregation for further input
1138        pub skip_partial_aggregation_probe_ratio_threshold: f64, default = 0.8
1139
1140        /// Number of input rows partial aggregation partition should process, before
1141        /// aggregation ratio check and trying to switch to skipping aggregation mode
1142        pub skip_partial_aggregation_probe_rows_threshold: usize, default = 100_000
1143
1144        /// Should DataFusion use row number estimates at the input to decide
1145        /// whether increasing parallelism is beneficial or not. By default,
1146        /// only exact row numbers (not estimates) are used for this decision.
1147        /// Setting this flag to `true` will likely produce better plans.
1148        /// if the source of statistics is accurate.
1149        /// We plan to make this the default in the future.
1150        pub use_row_number_estimates_to_optimize_partitioning: bool, default = false
1151
1152        /// Should DataFusion enforce batch size in joins or not. By default,
1153        /// DataFusion will not enforce batch size in joins. Enforcing batch size
1154        /// in joins can reduce memory usage when joining large
1155        /// tables with a highly-selective join filter, but is also slightly slower.
1156        /// Note: this option currently only applies to the symmetric hash join.
1157        pub enforce_batch_size_in_joins: bool, default = false
1158
1159        /// Size (bytes) of data buffer DataFusion uses when writing output files.
1160        /// This affects the size of the data chunks that are uploaded to remote
1161        /// object stores (e.g. AWS S3). If very large (>= 100 GiB) output files are being
1162        /// written, it may be necessary to increase this size to avoid errors from
1163        /// the remote end point.
1164        pub objectstore_writer_buffer_size: usize, default = 10 * 1024 * 1024
1165
1166        /// Whether to enable ANSI SQL mode.
1167        ///
1168        /// The flag is experimental and relevant only for DataFusion Spark built-in functions
1169        ///
1170        /// When `enable_ansi_mode` is set to `true`, the query engine follows ANSI SQL
1171        /// semantics for expressions, casting, and error handling. This means:
1172        /// - **Strict type coercion rules:** implicit casts between incompatible types are disallowed.
1173        /// - **Standard SQL arithmetic behavior:** operations such as division by zero,
1174        ///   numeric overflow, or invalid casts raise runtime errors rather than returning
1175        ///   `NULL` or adjusted values.
1176        /// - **Consistent ANSI behavior** for string concatenation, comparisons, and `NULL` handling.
1177        ///
1178        /// When `enable_ansi_mode` is `false` (the default), the engine uses a more permissive,
1179        /// non-ANSI mode designed for user convenience and backward compatibility. In this mode:
1180        /// - Implicit casts between types are allowed (e.g., string to integer when possible).
1181        /// - Arithmetic operations are more lenient — for example, `abs()` on the minimum
1182        ///   representable integer value returns the input value instead of raising overflow.
1183        /// - Division by zero or invalid casts may return `NULL` instead of failing.
1184        ///
1185        /// # Default
1186        /// `false` — ANSI SQL mode is disabled by default.
1187        pub enable_ansi_mode: bool, default = false
1188
1189        /// How many bytes to buffer in the probe side of hash joins while the build side is
1190        /// concurrently being built.
1191        ///
1192        /// Without this, hash joins will wait until the full materialization of the build side
1193        /// before polling the probe side. This is useful in scenarios where the query is not
1194        /// completely CPU bounded, allowing to do some early work concurrently and reducing the
1195        /// latency of the query.
1196        ///
1197        /// Note that when hash join buffering is enabled, the probe side will start eagerly
1198        /// polling data, not giving time for the producer side of dynamic filters to produce any
1199        /// meaningful predicate. Queries with dynamic filters might see performance degradation.
1200        ///
1201        /// Disabled by default, set to a number greater than 0 for enabling it.
1202        pub hash_join_buffering_capacity: usize, default = 0
1203    }
1204}
1205
1206config_namespace! {
1207    /// Options for content-defined chunking (CDC) when writing parquet files.
1208    /// Mirrors `parquet::file::properties::CdcOptions`.
1209    ///
1210    /// Carried as a [`ParquetCdcOptions`] in [`ParquetOptions::content_defined_chunking`]
1211    /// with an explicit `enabled` flag, so it can be toggled with dotted config
1212    /// keys (`content_defined_chunking.enabled = true|false`) and the result is
1213    /// independent of the order in which the keys are set.
1214    pub struct ParquetCdcOptions {
1215        /// (writing) EXPERIMENTAL: Enable content-defined chunking (CDC) when writing
1216        /// parquet files. When enabled, parallel writing is automatically disabled
1217        /// since the chunker state must persist across row groups.
1218        pub enabled: bool, default = false
1219
1220        /// Minimum chunk size in bytes. The rolling hash will not trigger a split
1221        /// until this many bytes have been accumulated. Default is 256 KiB.
1222        pub min_chunk_size: usize, default = 256 * 1024
1223
1224        /// Maximum chunk size in bytes. A split is forced when the accumulated
1225        /// size exceeds this value. Default is 1 MiB.
1226        pub max_chunk_size: usize, default = 1024 * 1024
1227
1228        /// Normalization level. Increasing this improves deduplication ratio
1229        /// but increases fragmentation. Recommended range is [-3, 3], default is 0.
1230        pub norm_level: i32, default = 0
1231    }
1232}
1233
1234impl ParquetCdcOptions {
1235    /// Returns enabled CDC options with the default chunking parameters.
1236    ///
1237    /// Shorthand for `ParquetCdcOptions { enabled: true, ..Default::default() }`;
1238    /// combine with struct-update syntax to override parameters, e.g.
1239    /// `ParquetCdcOptions { min_chunk_size: 4096, ..ParquetCdcOptions::enabled() }`.
1240    pub fn enabled() -> Self {
1241        Self {
1242            enabled: true,
1243            ..Default::default()
1244        }
1245    }
1246
1247    /// Returns disabled CDC options (equivalent to [`ParquetCdcOptions::default`]).
1248    pub fn disabled() -> Self {
1249        Self::default()
1250    }
1251}
1252
1253/// Target maximum size of a Parquet row group in bytes.
1254///
1255/// Wraps a `usize` so the "must be greater than zero" constraint (arrow-rs
1256/// panics on a zero byte limit) is validated when the config is set, rather
1257/// than when the writer properties are built.
1258#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1259pub struct MaxRowGroupBytes(usize);
1260
1261impl MaxRowGroupBytes {
1262    /// Creates a `MaxRowGroupBytes`, rejecting zero.
1263    pub fn try_new(value: usize) -> Result<Self> {
1264        if value == 0 {
1265            return Err(DataFusionError::Configuration(
1266                "max_row_group_bytes must be greater than 0".to_string(),
1267            ));
1268        }
1269        Ok(Self(value))
1270    }
1271
1272    /// Returns the configured byte limit.
1273    pub fn get(&self) -> usize {
1274        self.0
1275    }
1276}
1277
1278impl FromStr for MaxRowGroupBytes {
1279    type Err = DataFusionError;
1280
1281    fn from_str(s: &str) -> Result<Self, Self::Err> {
1282        let value = s.parse::<usize>().map_err(|_| {
1283            DataFusionError::Configuration(format!(
1284                "Invalid max_row_group_bytes: '{s}'. Expected a positive integer."
1285            ))
1286        })?;
1287        Self::try_new(value)
1288    }
1289}
1290
1291impl Display for MaxRowGroupBytes {
1292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1293        write!(f, "{}", self.0)
1294    }
1295}
1296
1297/// `ConfigField` for `Option<MaxRowGroupBytes>`. A custom impl (rather than the
1298/// blanket `Option<F>` one) so an invalid value is rejected without leaving the
1299/// option in an invalid intermediate state on error. `MaxRowGroupBytes`
1300/// deliberately does not implement `Default`, so the blanket impl does not apply.
1301impl ConfigField for Option<MaxRowGroupBytes> {
1302    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
1303        match self {
1304            Some(s) => v.some(key, s, description),
1305            None => v.none(key, description),
1306        }
1307    }
1308
1309    fn set(&mut self, _key: &str, value: &str) -> Result<()> {
1310        *self = Some(MaxRowGroupBytes::from_str(value)?);
1311        Ok(())
1312    }
1313
1314    fn reset(&mut self, _key: &str) -> Result<()> {
1315        *self = None;
1316        Ok(())
1317    }
1318}
1319
1320config_namespace! {
1321    /// Options for reading and writing parquet files
1322    ///
1323    /// See also: [`SessionConfig`]
1324    ///
1325    /// [`SessionConfig`]: https://docs.rs/datafusion/latest/datafusion/prelude/struct.SessionConfig.html
1326    pub struct ParquetOptions {
1327        // The following options affect reading parquet files
1328
1329        /// (reading) If true, reads the Parquet data page level metadata (the
1330        /// Page Index), if present, to reduce the I/O and number of
1331        /// rows decoded.
1332        pub enable_page_index: bool, default = true
1333
1334        /// (reading) If true, the parquet reader attempts to skip entire row groups based
1335        /// on the predicate in the query and the metadata (min/max values) stored in
1336        /// the parquet file
1337        pub pruning: bool, default = true
1338
1339        /// (reading) If true, the parquet reader skip the optional embedded metadata that may be in
1340        /// the file Schema. This setting can help avoid schema conflicts when querying
1341        /// multiple parquet files with schemas containing compatible types but different metadata.
1342        /// Arrow extension types (the `ARROW:extension:name` and `ARROW:extension:metadata`
1343        /// field metadata) are kept, because they are part of the type of a column
1344        pub skip_metadata: bool, default = true
1345
1346        /// (reading) If specified, the parquet reader will try and fetch the last `size_hint`
1347        /// bytes of the parquet file optimistically. If not specified, two reads are required:
1348        /// One read to fetch the 8-byte parquet footer and
1349        /// another to fetch the metadata length encoded in the footer
1350        /// Default setting to 512 KiB, which should be sufficient for most parquet files,
1351        /// it can reduce one I/O operation per parquet file. If the metadata is larger than
1352        /// the hint, two reads will still be performed.
1353        pub metadata_size_hint: Option<usize>, default = Some(512 * 1024)
1354
1355        /// (reading) If true, filter expressions are be applied during the parquet decoding operation to
1356        /// reduce the number of rows decoded. This optimization is sometimes called "late materialization".
1357        pub pushdown_filters: bool, default = false
1358
1359        /// (reading) If true, filter expressions evaluated during the parquet decoding operation
1360        /// will be reordered heuristically to minimize the cost of evaluation. If false,
1361        /// the filters are applied in the same order as written in the query
1362        pub reorder_filters: bool, default = false
1363
1364        /// (reading) Force the use of RowSelections for filter results, when
1365        /// pushdown_filters is enabled. If false, the reader will automatically
1366        /// choose between a RowSelection and a Bitmap based on the number and
1367        /// pattern of selected rows.
1368        pub force_filter_selections: bool, default = false
1369
1370        /// (reading) If true, parquet reader will read columns of `Utf8/Utf8Large` with `Utf8View`,
1371        /// and `Binary/BinaryLarge` with `BinaryView`.
1372        ///
1373        /// The parquet reader is optimized for reading `Utf8View` and `BinaryView`,
1374        /// so such queries are significantly faster than reading `Utf8`/`Binary`
1375        /// and then casting to the view types.
1376        pub schema_force_view_types: bool, default = true
1377
1378        /// (reading) If true, parquet reader will read columns of
1379        /// `Binary/LargeBinary` with `Utf8`, and `BinaryView` with `Utf8View`.
1380        ///
1381        /// Parquet files generated by some legacy writers do not correctly set
1382        /// the UTF8 flag for strings, causing string columns to be loaded as
1383        /// BLOB instead.
1384        ///
1385        /// The parquet reader has special optimizations for `Utf8` validation,
1386        /// so reading such columns as strings is significantly faster than
1387        /// reading them as binary and then casting to string.
1388        pub binary_as_string: bool, default = false
1389
1390        /// (reading) If set, parquet reader will read columns of
1391        /// physical type int96 as originating from this resolution instead of
1392        /// nanosecond. Valid values are: ns, us, ms, and s. This is useful for
1393        /// reading data from systems like Spark which store microsecond
1394        /// resolution timestamps in an int96, allowing them to write values with
1395        /// a larger date range than 64-bit timestamps with nanosecond resolution.
1396        pub coerce_int96: Option<DFTimeUnit>, default = None
1397
1398        /// (reading) Optional timezone applied to INT96 columns when `coerce_int96`
1399        /// is set. When `Some`, INT96 columns coerce to
1400        /// `Timestamp(<coerce_int96>, Some(<tz>))` instead of the default
1401        /// `Timestamp(<coerce_int96>, None)`. Spark and other systems write INT96
1402        /// values as UTC-adjusted instants, so callers that need the resulting
1403        /// Arrow type to be timezone-aware (e.g. for Spark `TimestampType`
1404        /// semantics) should set this to `"UTC"`. No effect when `coerce_int96`
1405        /// is `None`, but the value is still validated when it is set.
1406        pub coerce_int96_tz: Option<ConfigTimeZone>, default = None
1407
1408        /// (reading) Use any available bloom filters when reading parquet files
1409        pub bloom_filter_on_read: bool, default = true
1410
1411        /// (reading) The maximum predicate cache size, in bytes. When
1412        /// `pushdown_filters` is enabled, sets the maximum memory used to cache
1413        /// the results of predicate evaluation between filter evaluation and
1414        /// output generation. Decreasing this value will reduce memory usage,
1415        /// but may increase IO and CPU usage. None means use the default
1416        /// parquet reader setting. 0 means no caching.
1417        pub max_predicate_cache_size: Option<usize>, default = None
1418
1419        /// Maximum number of input values in an `IN (...)` list eligible for
1420        /// min/max pruning. Lists above this cap, or a cap of 0, skip this
1421        /// rewrite; other predicates and Bloom-filter pruning remain available.
1422        ///
1423        /// Within the cap, nonempty lists of at most 20 values use the existing
1424        /// per-value rewrite. Larger literal lists use a compact representation
1425        /// when the column type is string, variable-length binary, integer,
1426        /// decimal, date, time, timestamp, or duration. This applies to both `IN`
1427        /// and `NOT IN`, including lists with NULL members. `NOT IN` with NULL and
1428        /// all-NULL `IN` lists cannot match any rows. Compact lists containing NULL
1429        /// do not use the fully-matched-row-group optimization. Floating-point and
1430        /// other lists retain the existing per-value rewrite, so raising the cap
1431        /// can make those predicates expensive to build and evaluate.
1432        ///
1433        /// Defaults to 20.
1434        pub max_in_list_size: usize, default = 20
1435
1436        /// (reading) If true, top-level string and binary Parquet columns with
1437        /// dictionary pages are inferred and scanned as
1438        /// `Dictionary<Int32, Utf8>` / `Dictionary<Int32, Binary>` instead of
1439        /// their plain value type.
1440        ///
1441        /// This applies only when DataFusion infers the table schema. Tables with
1442        /// a user-supplied schema are not promoted because the Parquet footer is
1443        /// not read at DDL time, so dictionary pages cannot be detected per column.
1444        /// See <https://github.com/apache/datafusion/issues/24112>
1445        pub enable_rle_to_dictionary: bool, default = false
1446
1447        /// (reading) Which byte range of a split file reads each row group.
1448        /// `start_offset` picks the range containing the row group's start.
1449        /// `midpoint` picks the range containing its midpoint, as Spark does,
1450        /// which spreads large row groups more evenly across ranges.
1451        pub row_group_range_assignment: RowGroupRangeAssignment, default = RowGroupRangeAssignment::StartOffset
1452
1453        // The following options affect writing to parquet files
1454        // and map to parquet::file::properties::WriterProperties
1455
1456        /// (writing) Sets best effort maximum size of data page in bytes
1457        pub data_pagesize_limit: usize, default = 1024 * 1024
1458
1459        /// (writing) Sets write_batch_size in rows
1460        pub write_batch_size: usize, default = 1024
1461
1462        /// (writing) Sets parquet writer version
1463        /// valid values are "1.0" and "2.0"
1464        pub writer_version: DFParquetWriterVersion, default = DFParquetWriterVersion::default()
1465
1466        /// (writing) Skip encoding the embedded arrow metadata in the KV_meta
1467        ///
1468        /// This is analogous to the `ArrowWriterOptions::with_skip_arrow_metadata`.
1469        /// Refer to <https://docs.rs/parquet/53.3.0/parquet/arrow/arrow_writer/struct.ArrowWriterOptions.html#method.with_skip_arrow_metadata>
1470        pub skip_arrow_metadata: bool, default = false
1471
1472        /// (writing) Sets default parquet compression codec.
1473        /// Valid values are: uncompressed, snappy, gzip(level),
1474        /// brotli(level), lz4, zstd(level), and lz4_raw.
1475        /// These values are not case sensitive. If NULL, uses
1476        /// default parquet writer setting
1477        ///
1478        /// Note that this default setting is not the same as
1479        /// the default parquet writer setting.
1480        pub compression: Option<DFParquetCompression>, default = Some(DFParquetCompression::Zstd(3))
1481
1482        /// (writing) Sets if dictionary encoding is enabled. If NULL, uses
1483        /// default parquet writer setting
1484        pub dictionary_enabled: Option<bool>, default = Some(true)
1485
1486        /// (writing) Sets best effort maximum dictionary page size, in bytes
1487        pub dictionary_page_size_limit: usize, default = 1024 * 1024
1488
1489        /// (writing) Sets if statistics are enabled for any column
1490        /// Valid values are: "none", "chunk", and "page"
1491        /// These values are not case sensitive. If NULL, uses
1492        /// default parquet writer setting
1493        pub statistics_enabled: Option<DFParquetStatistics>, default = Some(DFParquetStatistics::Page)
1494
1495        /// (writing) Target maximum number of rows in each row group (defaults to 1M
1496        /// rows). Writing larger row groups requires more memory to write, but
1497        /// can get better compression and be faster to read. When
1498        /// `max_row_group_bytes` is also set, the writer flushes a row group when
1499        /// either limit is reached, whichever comes first.
1500        pub max_row_group_size: usize, default =  1024 * 1024
1501
1502        /// (writing) Target maximum size of each row group in bytes. When set,
1503        /// the writer flushes whenever either this limit or `max_row_group_size`
1504        /// is reached, whichever comes first. Useful for bounding writer memory
1505        /// on wide schemas where a row-count limit can map to very different
1506        /// byte sizes. Matches the behavior of `parquet.block.size` in
1507        /// parquet-mr. If `None` (the default), only the row-count limit
1508        /// applies. Currently only honored when `allow_single_file_parallelism`
1509        /// is `false`; by default the parallel file writer ignores this limit.
1510        pub max_row_group_bytes: Option<MaxRowGroupBytes>, default = None
1511
1512        /// (writing) Sets "created by" property
1513        pub created_by: String, default = concat!("datafusion version ", env!("CARGO_PKG_VERSION")).into()
1514
1515        /// (writing) Sets column index truncate length
1516        pub column_index_truncate_length: Option<usize>, default = Some(64)
1517
1518        /// (writing) Sets statistics truncate length. If NULL, uses
1519        /// default parquet writer setting
1520        pub statistics_truncate_length: Option<usize>, default = Some(64)
1521
1522        /// (writing) Sets best effort maximum number of rows in data page
1523        pub data_page_row_count_limit: usize, default = 20_000
1524
1525        /// (writing)  Sets default encoding for any column.
1526        /// Valid values are: plain, plain_dictionary, rle,
1527        /// bit_packed, delta_binary_packed, delta_length_byte_array,
1528        /// delta_byte_array, rle_dictionary, byte_stream_split, and alp.
1529        /// These values are not case sensitive. If NULL, uses
1530        /// default parquet writer setting
1531        pub encoding: Option<DFParquetEncoding>, default = None
1532
1533        /// (writing) Write bloom filters for all columns when creating parquet files
1534        pub bloom_filter_on_write: bool, default = false
1535
1536        /// (writing) Sets bloom filter false positive probability. If NULL, uses
1537        /// default parquet writer setting
1538        pub bloom_filter_fpp: Option<f64>, default = None
1539
1540        /// (writing) Sets bloom filter number of distinct values. If NULL, uses
1541        /// default parquet writer setting
1542        pub bloom_filter_ndv: Option<u64>, default = None
1543
1544        /// (writing) Write the number of distinct values (NDV) for each column
1545        /// in row group statistics when creating parquet files. Enabling this
1546        /// improves NDV-based query optimizations at the cost of hashing every
1547        /// non-null value during write.
1548        pub write_row_group_number_distinct_values: bool, default = false
1549
1550        /// (writing) Controls whether DataFusion will attempt to speed up writing
1551        /// parquet files by serializing them in parallel. Each column
1552        /// in each row group in each output file are serialized in parallel
1553        /// leveraging a maximum possible core count of n_files\*n_row_groups\*n_columns.
1554        pub allow_single_file_parallelism: bool, default = true
1555
1556        /// (writing) By default parallel parquet writer is tuned for minimum
1557        /// memory usage in a streaming execution plan. You may see
1558        /// a performance benefit when writing large parquet files
1559        /// by increasing maximum_parallel_row_group_writers and
1560        /// maximum_buffered_record_batches_per_stream if your system
1561        /// has idle cores and can tolerate additional memory usage.
1562        /// Boosting these values is likely worthwhile when
1563        /// writing out already in-memory data, such as from a cached
1564        /// data frame.
1565        pub maximum_parallel_row_group_writers: usize, default = 1
1566
1567        /// (writing) By default parallel parquet writer is tuned for minimum
1568        /// memory usage in a streaming execution plan. You may see
1569        /// a performance benefit when writing large parquet files
1570        /// by increasing maximum_parallel_row_group_writers and
1571        /// maximum_buffered_record_batches_per_stream if your system
1572        /// has idle cores and can tolerate additional memory usage.
1573        /// Boosting these values is likely worthwhile when
1574        /// writing out already in-memory data, such as from a cached
1575        /// data frame.
1576        pub maximum_buffered_record_batches_per_stream: usize, default = 2
1577
1578        /// (writing) EXPERIMENTAL: Content-defined chunking (CDC) options when writing
1579        /// parquet files. Disabled by default; toggle with
1580        /// `content_defined_chunking.enabled = true|false`. The chunking parameters live
1581        /// under the same prefix (e.g. `content_defined_chunking.min_chunk_size`). When
1582        /// enabled, parallel writing is automatically disabled since the chunker state
1583        /// must persist across row groups. Mirrors
1584        /// `parquet::file::properties::WriterProperties::content_defined_chunking`.
1585        pub content_defined_chunking: ParquetCdcOptions, default = Default::default()
1586    }
1587}
1588
1589config_namespace! {
1590    /// Options for configuring Parquet Modular Encryption
1591    ///
1592    /// To use Parquet encryption, you must enable the `parquet_encryption` feature flag, as it is not activated by default.
1593    pub struct ParquetEncryptionOptions {
1594        /// Optional file decryption properties
1595        pub file_decryption: Option<ConfigFileDecryptionProperties>, default = None
1596
1597        /// Optional file encryption properties
1598        pub file_encryption: Option<ConfigFileEncryptionProperties>, default = None
1599
1600        /// Identifier for the encryption factory to use to create file encryption and decryption properties.
1601        /// Encryption factories can be registered in the runtime environment with
1602        /// `RuntimeEnv::register_parquet_encryption_factory`.
1603        pub factory_id: Option<String>, default = None
1604
1605        /// Any encryption factory specific options
1606        pub factory_options: EncryptionFactoryOptions, default = EncryptionFactoryOptions::default()
1607    }
1608}
1609
1610impl ParquetEncryptionOptions {
1611    /// Specify the encryption factory to use for Parquet modular encryption, along with its configuration
1612    pub fn configure_factory(
1613        &mut self,
1614        factory_id: &str,
1615        config: &impl ExtensionOptions,
1616    ) {
1617        self.factory_id = Some(factory_id.to_owned());
1618        self.factory_options.options.clear();
1619        for entry in config.entries() {
1620            if let Some(value) = entry.value {
1621                self.factory_options.options.insert(entry.key, value);
1622            }
1623        }
1624    }
1625}
1626
1627config_namespace! {
1628    /// Options related to query optimization
1629    ///
1630    /// See also: [`SessionConfig`]
1631    ///
1632    /// [`SessionConfig`]: https://docs.rs/datafusion/latest/datafusion/prelude/struct.SessionConfig.html
1633    pub struct OptimizerOptions {
1634        /// When set to true, the optimizer will push a limit operation into
1635        /// grouped aggregations which have no aggregate expressions, as a soft limit,
1636        /// emitting groups once the limit is reached, before all rows in the group are read.
1637        pub enable_distinct_aggregation_soft_limit: bool, default = true
1638
1639        /// When set to true, the physical plan optimizer will try to add round robin
1640        /// repartitioning to increase parallelism to leverage more CPU cores
1641        pub enable_round_robin_repartition: bool, default = true
1642
1643        /// When set to true, the optimizer will attempt to perform limit operations
1644        /// during aggregations, if possible
1645        pub enable_topk_aggregation: bool, default = true
1646
1647        /// When set to true, the optimizer will attempt to push limit operations
1648        /// past window functions, if possible
1649        pub enable_window_limits: bool, default = true
1650
1651        /// When set to true, the optimizer will replace
1652        /// Filter(rn<=K) → Window(ROW_NUMBER) → Sort patterns with a
1653        /// PartitionedTopKExec that maintains per-partition heaps, avoiding
1654        /// a full sort of the input.
1655        /// When the window partition key has low cardinality, enabling this optimization
1656        /// can improve performance. However, for high cardinality keys, it may
1657        /// cause regressions in both memory usage and runtime.
1658        pub enable_window_topn: bool, default = false
1659
1660        /// When set to true, the optimizer will push TopK (Sort with fetch)
1661        /// below hash repartition when the partition key is a prefix of the
1662        /// sort key, reducing data volume before the shuffle.
1663        pub enable_topk_repartition: bool, default = true
1664
1665        /// When set to true, the optimizer will attempt to push down TopK dynamic filters
1666        /// into the file scan phase.
1667        pub enable_topk_dynamic_filter_pushdown: bool, default = true
1668
1669        /// When set to true, uncorrelated scalar subqueries are
1670        /// left in the logical plan and executed by `ScalarSubqueryExec` during
1671        /// physical execution. When set to false, all scalar subqueries
1672        /// (including uncorrelated ones) are rewritten to left joins by the
1673        /// `ScalarSubqueryToJoin` optimizer rule.
1674        ///
1675        /// Note disabling this option is not recommended. It restores
1676        /// pre <https://github.com/apache/datafusion/pull/21240>
1677        /// behavior, which silently produces incorrect results for
1678        /// multi-row subqueries and does not support scalar subqueries in
1679        /// ORDER BY / JOIN ON / aggregate-function arguments. This option is
1680        /// intended as a temporary escape hatch for distributed execution
1681        /// frameworks and is planned to be removed in a future DataFusion
1682        /// release.
1683        pub enable_physical_uncorrelated_scalar_subquery: bool, default = true
1684
1685        /// When set to true, the optimizer will attempt to push down Join dynamic filters
1686        /// into the file scan phase.
1687        pub enable_join_dynamic_filter_pushdown: bool, default = true
1688
1689        /// When set to true, the optimizer will attempt to push down Aggregate dynamic filters
1690        /// into the file scan phase.
1691        pub enable_aggregate_dynamic_filter_pushdown: bool, default = true
1692
1693        /// When set to true attempts to push down dynamic filters generated by operators (TopK, Join & Aggregate) into the file scan phase.
1694        /// For example, for a query such as `SELECT * FROM t ORDER BY timestamp DESC LIMIT 10`, the optimizer
1695        /// will attempt to push down the current top 10 timestamps that the TopK operator references into the file scans.
1696        /// This means that if we already have 10 timestamps in the year 2025
1697        /// any files that only have timestamps in the year 2024 can be skipped / pruned at various stages in the scan.
1698        /// The config will suppress `enable_join_dynamic_filter_pushdown`, `enable_topk_dynamic_filter_pushdown` & `enable_aggregate_dynamic_filter_pushdown`
1699        /// So if you disable `enable_topk_dynamic_filter_pushdown`, then enable `enable_dynamic_filter_pushdown`, the `enable_topk_dynamic_filter_pushdown` will be overridden.
1700        pub enable_dynamic_filter_pushdown: bool, default = true
1701
1702        /// When set to true, the optimizer will insert filters before a join between
1703        /// a nullable and non-nullable column to filter out nulls on the nullable side. This
1704        /// filter can add additional overhead when the file format does not fully support
1705        /// predicate push down.
1706        pub filter_null_join_keys: bool, default = false
1707
1708        /// Should DataFusion repartition data using the aggregate keys to execute aggregates
1709        /// in parallel using the provided `target_partitions` level
1710        pub repartition_aggregations: bool, default = true
1711
1712        /// Minimum total file size in bytes for file-group byte-range
1713        /// splitting to fire. Files (or merged file groups) smaller than this
1714        /// stay as one partition. Lower values produce more, smaller
1715        /// partitions — better at filling `target_partitions` worth of cores
1716        /// when files are modestly sized, at the cost of slightly more
1717        /// per-partition open / metadata-load overhead.
1718        pub repartition_file_min_size: usize, default = 1024 * 1024
1719
1720        /// Should DataFusion repartition data using the join keys to execute joins in parallel
1721        /// using the provided `target_partitions` level
1722        pub repartition_joins: bool, default = true
1723
1724        /// Should DataFusion allow symmetric hash joins for unbounded data sources even when
1725        /// its inputs do not have any ordering or filtering If the flag is not enabled,
1726        /// the SymmetricHashJoin operator will be unable to prune its internal buffers,
1727        /// resulting in certain join types - such as Full, Left, LeftAnti, LeftSemi, Right,
1728        /// RightAnti, and RightSemi - being produced only at the end of the execution.
1729        /// This is not typical in stream processing. Additionally, without proper design for
1730        /// long runner execution, all types of joins may encounter out-of-memory errors.
1731        pub allow_symmetric_joins_without_pruning: bool, default = true
1732
1733        /// When set to `true`, datasource partitions will be repartitioned to achieve maximum parallelism.
1734        /// This applies to both in-memory partitions and FileSource's file groups (1 group is 1 partition).
1735        ///
1736        /// For FileSources, only Parquet and CSV formats are currently supported.
1737        ///
1738        /// If set to `true` for a FileSource, all files will be repartitioned evenly (i.e., a single large file
1739        /// might be partitioned into smaller chunks) for parallel scanning.
1740        /// If set to `false` for a FileSource, different files will be read in parallel, but repartitioning won't
1741        /// happen within a single file.
1742        ///
1743        /// If set to `true` for an in-memory source, all memtable's partitions will have their batches
1744        /// repartitioned evenly to the desired number of `target_partitions`. Repartitioning can change
1745        /// the total number of partitions and batches per partition, but does not slice the initial
1746        /// record tables provided to the MemTable on creation.
1747        pub repartition_file_scans: bool, default = true
1748
1749        /// Minimum number of distinct partition values required to group files by their
1750        /// Hive partition column values (enabling output partitioning declaration).
1751        ///
1752        /// How the option is used:
1753        ///     - preserve_file_partitions=0: Disable it.
1754        ///     - preserve_file_partitions=1: Always enable it.
1755        ///     - preserve_file_partitions=N, actual file partitions=M: Only enable when M >= N.
1756        ///     This threshold preserves I/O parallelism when file partitioning is below it.
1757        ///
1758        /// Note: This may reduce parallelism, rooting from the I/O level, if the number of distinct
1759        /// partitions is less than the target_partitions.
1760        pub preserve_file_partitions: usize, default = 0
1761
1762        /// Should DataFusion repartition data using the partitions keys to execute window
1763        /// functions in parallel using the provided `target_partitions` level
1764        pub repartition_windows: bool, default = true
1765
1766        /// Should DataFusion execute sorts in a per-partition fashion and merge
1767        /// afterwards instead of coalescing first and sorting globally.
1768        /// With this flag is enabled, plans in the form below
1769        ///
1770        /// ```text
1771        ///      "SortExec: [a@0 ASC]",
1772        ///      "  CoalescePartitionsExec",
1773        ///      "    RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1",
1774        /// ```
1775        /// would turn into the plan below which performs better in multithreaded environments
1776        ///
1777        /// ```text
1778        ///      "SortPreservingMergeExec: [a@0 ASC]",
1779        ///      "  SortExec: [a@0 ASC]",
1780        ///      "    RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1",
1781        /// ```
1782        pub repartition_sorts: bool, default = true
1783
1784        /// Partition count threshold for subset satisfaction optimization.
1785        ///
1786        /// When the current partition count is >= this threshold, DataFusion will
1787        /// skip repartitioning if the required partitioning expression is a subset
1788        /// of the current partition expression such as Hash(a) satisfies Hash(a, b).
1789        ///
1790        /// When the current partition count is < this threshold, DataFusion will
1791        /// repartition to increase parallelism even when subset satisfaction applies.
1792        ///
1793        /// Set to 0 to always repartition (disable subset satisfaction optimization).
1794        /// Set to a high value to always use subset satisfaction.
1795        ///
1796        /// Example (subset_repartition_threshold = 4):
1797        /// ```text
1798        ///     Hash([a]) satisfies Hash([a, b]) because (Hash([a, b]) is subset of Hash([a])
1799        ///
1800        ///     If current partitions (3) < threshold (4), repartition:
1801        ///     AggregateExec: mode=FinalPartitioned, gby=[a, b], aggr=[SUM(x)]
1802        ///       RepartitionExec: partitioning=Hash([a, b], 8), input_partitions=3
1803        ///         AggregateExec: mode=Partial, gby=[a, b], aggr=[SUM(x)]
1804        ///           DataSourceExec: file_groups={...}, output_partitioning=Hash([a], 3)
1805        ///
1806        ///     If current partitions (8) >= threshold (4), use subset satisfaction:
1807        ///     AggregateExec: mode=SinglePartitioned, gby=[a, b], aggr=[SUM(x)]
1808        ///       DataSourceExec: file_groups={...}, output_partitioning=Hash([a], 8)
1809        /// ```
1810        pub subset_repartition_threshold: usize, default = 4
1811
1812        /// When true, DataFusion will opportunistically remove sorts when the data is already sorted,
1813        /// (i.e. setting `preserve_order` to true on `RepartitionExec`  and
1814        /// using `SortPreservingMergeExec`)
1815        ///
1816        /// When false, DataFusion will maximize plan parallelism using
1817        /// `RepartitionExec` even if this requires subsequently resorting data using a `SortExec`.
1818        pub prefer_existing_sort: bool, default = false
1819
1820        /// When set to true, the logical plan optimizer will produce warning
1821        /// messages if any optimization rules produce errors and then proceed to the next
1822        /// rule. When set to false, any rules that produce errors will cause the query to fail
1823        pub skip_failed_rules: bool, default = false
1824
1825        /// The logical optimizer applies rules in order for up to `max_passes` passes,
1826        /// stopping early if a pass leaves the plan unchanged or repeats an earlier plan.
1827        /// The physical optimizer always runs in one pass.
1828        pub max_passes: usize, default = 3
1829
1830        /// When set to true, the physical plan optimizer will run a top down
1831        /// process to reorder the join keys
1832        pub top_down_join_key_reordering: bool, default = true
1833
1834        /// When set to true, the physical plan optimizer may swap join inputs
1835        /// based on statistics. When set to false, statistics-driven join
1836        /// input reordering is disabled and the original join order in the
1837        /// query is used.
1838        pub join_reordering: bool, default = true
1839
1840        /// (Deprecated) Ignored: the physical plan optimizer always consults the
1841        /// session's pluggable `StatisticsRegistry` (register providers on the
1842        /// `SessionState`; with none it is a no-op).
1843        pub use_statistics_registry: bool, warn = "`use_statistics_registry` is deprecated and ignored; the StatisticsRegistry is always consulted, register providers on the SessionState", default = false
1844
1845        /// When set to true, the physical plan optimizer will prefer HashJoin over SortMergeJoin.
1846        /// HashJoin can work more efficiently than SortMergeJoin but consumes more memory
1847        pub prefer_hash_join: bool, default = true
1848
1849        /// When set to true, piecewise merge join is enabled. PiecewiseMergeJoin is currently
1850        /// experimental. Physical planner will opt for PiecewiseMergeJoin when there is only
1851        /// one range filter.
1852        pub enable_piecewise_merge_join: bool, default = false
1853
1854        /// The maximum estimated size in bytes for one input side of a HashJoin
1855        /// will be collected into a single partition
1856        pub hash_join_single_partition_threshold: usize, default = 4 * 1024 * 1024
1857
1858        /// The maximum estimated size in rows for one input side of a HashJoin
1859        /// will be collected into a single partition
1860        pub hash_join_single_partition_threshold_rows: usize, default = 1024 * 128
1861
1862        /// Maximum size in bytes for the build side of a hash join to be pushed down as an InList expression for dynamic filtering.
1863        /// Build sides larger than this will use hash table lookups instead.
1864        /// Set to 0 to always use hash table lookups.
1865        ///
1866        /// InList pushdown can be more efficient for small build sides because it can result in better
1867        /// statistics pruning as well as use any bloom filters present on the scan side.
1868        /// InList expressions are also more transparent and easier to serialize over the network in distributed uses of DataFusion.
1869        /// On the other hand InList pushdown requires making a copy of the data and thus adds some overhead to the build side and uses more memory.
1870        ///
1871        /// This setting is per-partition, so we may end up using `hash_join_inlist_pushdown_max_size` * `target_partitions` memory.
1872        ///
1873        /// The default is 128kB per partition.
1874        /// This should allow point lookup joins (e.g. joining on a unique primary key) to use InList pushdown in most cases
1875        /// but avoids excessive memory usage or overhead for larger joins.
1876        pub hash_join_inlist_pushdown_max_size: usize, default = 128 * 1024
1877
1878        /// Maximum number of distinct values (rows) in the build side of a hash join to be pushed down as an InList expression for dynamic filtering.
1879        /// Build sides with more rows than this will use hash table lookups instead.
1880        /// Set to 0 to always use hash table lookups.
1881        ///
1882        /// This provides an additional limit beyond `hash_join_inlist_pushdown_max_size` to prevent
1883        /// very large IN lists that might not provide much benefit over hash table lookups.
1884        ///
1885        /// This uses the deduplicated row count once the build side has been evaluated.
1886        ///
1887        /// The default is 150 values per partition.
1888        /// This is inspired by Trino's `max-filter-keys-per-column` setting.
1889        /// See: <https://trino.io/docs/current/admin/dynamic-filtering.html#dynamic-filter-collection-thresholds>
1890        pub hash_join_inlist_pushdown_max_distinct_values: usize, default = 150
1891
1892        /// The default filter selectivity used by Filter Statistics
1893        /// when an exact selectivity cannot be determined. Valid values are
1894        /// between 0 (no selectivity) and 100 (all rows are selected).
1895        pub default_filter_selectivity: ConfigFilterSelectivity, default = filter_selectivity_default(20)
1896
1897        /// When set to true, the optimizer will not attempt to convert Union to Interleave
1898        pub prefer_existing_union: bool, default = false
1899
1900        /// When set to true, if the returned type is a view type
1901        /// then the output will be coerced to a non-view.
1902        /// Coerces `Utf8View` to `LargeUtf8`, and `BinaryView` to `LargeBinary`.
1903        pub expand_views_at_output: bool, default = false
1904
1905        /// Enable sort pushdown optimization.
1906        /// When enabled, attempts to push sort requirements down to data sources
1907        /// that can natively handle them (e.g., by reversing file/row group read order).
1908        ///
1909        /// Returns **inexact ordering**: Sort operator is kept for correctness,
1910        /// but optimized input enables early termination for TopK queries (ORDER BY ... LIMIT N),
1911        /// providing significant speedup.
1912        ///
1913        /// Memory: No additional overhead (only changes read order).
1914        ///
1915        /// Future: Will add option to detect perfectly sorted data and eliminate Sort completely.
1916        ///
1917        /// Default: true
1918        pub enable_sort_pushdown: bool, default = true
1919
1920        /// When set to true, the optimizer will extract leaf expressions
1921        /// (such as `get_field`) from filter/sort/join nodes into projections
1922        /// closer to the leaf table scans, and push those projections down
1923        /// towards the leaf nodes.
1924        pub enable_leaf_expression_pushdown: bool, default = true
1925
1926        /// When set to true, the logical optimizer will rewrite `UNION DISTINCT` branches that
1927        /// read from the same source and differ only by filter predicates into a single branch
1928        /// with a combined filter. This optimization is conservative and only applies when the
1929        /// branches share the same source and compatible wrapper nodes such as identical
1930        /// projections or aliases.
1931        pub enable_unions_to_filter: bool, default = false
1932    }
1933}
1934
1935config_namespace! {
1936    /// Options controlling explain output
1937    ///
1938    /// See also: [`SessionConfig`]
1939    ///
1940    /// [`SessionConfig`]: https://docs.rs/datafusion/latest/datafusion/prelude/struct.SessionConfig.html
1941    pub struct ExplainOptions {
1942        /// When set to true, the explain statement will only print logical plans
1943        pub logical_plan_only: bool, default = false
1944
1945        /// When set to true, the explain statement will only print physical plans
1946        pub physical_plan_only: bool, default = false
1947
1948        /// When set to true, the explain statement will print operator statistics
1949        /// for physical plans
1950        pub show_statistics: bool, default = false
1951
1952        /// When set to true, the explain statement will print the partition sizes
1953        pub show_sizes: bool, default = true
1954
1955        /// When set to true, the explain statement will print schema information
1956        pub show_schema: bool, default = false
1957
1958        /// Display format of explain. Default is "indent".
1959        /// When set to "tree", it will print the plan in a tree-rendered format.
1960        pub format: ExplainFormat, default = ExplainFormat::Indent
1961
1962        /// (format=tree only) Maximum total width of the rendered tree.
1963        /// When set to 0, the tree will have no width limit.
1964        pub tree_maximum_render_width: usize, default = 240
1965
1966        /// Verbosity level for "EXPLAIN ANALYZE". Default is "dev"
1967        /// "summary" shows common metrics for high-level insights.
1968        /// "dev" provides deep operator-level introspection for developers.
1969        pub analyze_level: MetricType, default = MetricType::Dev
1970
1971        /// Which metric categories to include in "EXPLAIN ANALYZE" output.
1972        /// Comma-separated list of: "rows", "bytes", "timing", "uncategorized".
1973        /// Use "none" to show plan structure only, or "all" (default) to show everything.
1974        /// Metrics without a declared category are treated as "uncategorized".
1975        pub analyze_categories: ExplainAnalyzeCategories, default = ExplainAnalyzeCategories::All
1976    }
1977}
1978
1979impl ExecutionOptions {
1980    /// Returns the correct parallelism based on the provided `value`.
1981    /// If `value` is `"0"`, returns the default available parallelism, computed with
1982    /// `get_available_parallelism`. Otherwise, returns `value`.
1983    fn normalized_parallelism(value: &str) -> String {
1984        if value.parse::<usize>() == Ok(0) {
1985            get_available_parallelism().to_string()
1986        } else {
1987            value.to_owned()
1988        }
1989    }
1990}
1991
1992/// Format used to display `Duration` values in query output. Mirrors
1993/// [`arrow::util::display::DurationFormat`].
1994///
1995/// See [`FormatOptions::duration_format`].
1996#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1997pub enum ConfigDurationFormat {
1998    /// Format durations in a human readable form, e.g. `1h2m3s450ms`.
1999    #[default]
2000    Pretty,
2001    /// Format durations as an ISO 8601 duration string, e.g. `PT1H2M3.45S`.
2002    Iso8601,
2003}
2004
2005impl FromStr for ConfigDurationFormat {
2006    type Err = DataFusionError;
2007
2008    fn from_str(s: &str) -> Result<Self, Self::Err> {
2009        match s.to_ascii_lowercase().as_str() {
2010            "pretty" => Ok(Self::Pretty),
2011            "iso8601" => Ok(Self::Iso8601),
2012            _ => _config_err!(
2013                "Invalid duration format: {s}. Valid values are pretty or iso8601"
2014            ),
2015        }
2016    }
2017}
2018
2019impl ConfigField for ConfigDurationFormat {
2020    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
2021        v.some(key, self, description)
2022    }
2023
2024    fn set(&mut self, _: &str, value: &str) -> Result<()> {
2025        *self = ConfigDurationFormat::from_str(value)?;
2026        Ok(())
2027    }
2028}
2029
2030impl Display for ConfigDurationFormat {
2031    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2032        let str = match self {
2033            Self::Pretty => "pretty",
2034            Self::Iso8601 => "iso8601",
2035        };
2036        write!(f, "{str}")
2037    }
2038}
2039
2040impl From<ConfigDurationFormat> for arrow::util::display::DurationFormat {
2041    fn from(value: ConfigDurationFormat) -> Self {
2042        match value {
2043            ConfigDurationFormat::Pretty => arrow::util::display::DurationFormat::Pretty,
2044            ConfigDurationFormat::Iso8601 => {
2045                arrow::util::display::DurationFormat::ISO8601
2046            }
2047        }
2048    }
2049}
2050
2051/// A time zone that is known to parse as an Arrow
2052/// [`Tz`](arrow::array::timezone::Tz), used for
2053/// [`ExecutionOptions::time_zone`].
2054///
2055/// The value is kept as it was written, so `+08` stays `+08` rather than
2056/// being normalized to `+08:00`.
2057#[derive(Debug, Clone, PartialEq, Eq)]
2058pub struct ConfigTimeZone(String);
2059
2060impl ConfigTimeZone {
2061    /// Returns the time zone as it was written.
2062    pub fn as_str(&self) -> &str {
2063        &self.0
2064    }
2065}
2066
2067impl FromStr for ConfigTimeZone {
2068    type Err = DataFusionError;
2069
2070    fn from_str(s: &str) -> Result<Self, Self::Err> {
2071        match s.parse::<arrow::array::timezone::Tz>() {
2072            Ok(_) => Ok(Self(s.to_string())),
2073            Err(_) => _config_err!(
2074                "Invalid time zone: {s}. Valid values are UTC offsets such as +08:00 or IANA time zone names such as Asia/Taipei"
2075            ),
2076        }
2077    }
2078}
2079
2080impl Display for ConfigTimeZone {
2081    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2082        f.write_str(&self.0)
2083    }
2084}
2085
2086/// `ConfigField` for `Option<ConfigTimeZone>` parses before assigning so an
2087/// invalid value leaves the current setting unchanged.
2088impl ConfigField for Option<ConfigTimeZone> {
2089    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
2090        match self {
2091            Some(time_zone) => v.some(key, time_zone, description),
2092            None => v.none(key, description),
2093        }
2094    }
2095
2096    fn set(&mut self, key: &str, value: &str) -> Result<()> {
2097        if !key.is_empty() {
2098            return _config_err!(
2099                "Config field is a scalar Option<ConfigTimeZone> and does not have nested field \"{}\"",
2100                key
2101            );
2102        }
2103
2104        *self = Some(ConfigTimeZone::from_str(value)?);
2105        Ok(())
2106    }
2107
2108    fn reset(&mut self, key: &str) -> Result<()> {
2109        if key.is_empty() {
2110            *self = None;
2111            Ok(())
2112        } else {
2113            _config_err!(
2114                "Config field is a scalar Option<ConfigTimeZone> and does not have nested field \"{}\"",
2115                key
2116            )
2117        }
2118    }
2119}
2120
2121config_namespace! {
2122    /// Options controlling the format of output when printing record batches
2123    /// Copies [`arrow::util::display::FormatOptions`]
2124    pub struct FormatOptions {
2125        /// If set to `true` any formatting errors will be written to the output
2126        /// instead of being converted into a [`std::fmt::Error`]
2127        pub safe: bool, default = true
2128        /// Format string for nulls
2129        pub null: String, default = "".into()
2130        /// Date format for date arrays
2131        pub date_format: Option<String>, default = Some("%Y-%m-%d".to_string())
2132        /// Format for DateTime arrays
2133        pub datetime_format: Option<String>, default = Some("%Y-%m-%dT%H:%M:%S%.f".to_string())
2134        /// Timestamp format for timestamp arrays
2135        pub timestamp_format: Option<String>, default = Some("%Y-%m-%dT%H:%M:%S%.f".to_string())
2136        /// Timestamp format for timestamp with timezone arrays. When `None`, ISO 8601 format is used.
2137        pub timestamp_tz_format: Option<String>, default = None
2138        /// Time format for time arrays
2139        pub time_format: Option<String>, default = Some("%H:%M:%S%.f".to_string())
2140        /// Duration format. Can be either `"pretty"` or `"ISO8601"`
2141        pub duration_format: ConfigDurationFormat, default = ConfigDurationFormat::Pretty
2142        /// Show types in visual representation batches
2143        pub types_info: bool, default = false
2144    }
2145}
2146
2147impl<'a> TryFrom<&'a FormatOptions> for arrow::util::display::FormatOptions<'a> {
2148    type Error = DataFusionError;
2149    fn try_from(options: &'a FormatOptions) -> Result<Self> {
2150        for (name, format) in [
2151            ("date_format", options.date_format.as_deref()),
2152            ("datetime_format", options.datetime_format.as_deref()),
2153            ("timestamp_format", options.timestamp_format.as_deref()),
2154            (
2155                "timestamp_tz_format",
2156                options.timestamp_tz_format.as_deref(),
2157            ),
2158            ("time_format", options.time_format.as_deref()),
2159        ] {
2160            if let Some(format) = format {
2161                let items = chrono::format::StrftimeItems::new(format).parse().map_err(
2162                    |error| {
2163                        DataFusionError::Configuration(format!(
2164                            "Invalid datafusion.format.{name}: {error}"
2165                        ))
2166                    },
2167                )?;
2168
2169                // Parsing validates directives, but some directives require fields
2170                // that are absent from a particular temporal type (for example,
2171                // `%H` for a date). Chrono reports those errors while formatting.
2172                let mut rendered = String::new();
2173                let result = match name {
2174                    "date_format" => chrono::NaiveDate::from_ymd_opt(2001, 2, 3)
2175                        .expect("valid sample date")
2176                        .format_with_items(items.iter())
2177                        .write_to(&mut rendered),
2178                    "datetime_format" | "timestamp_format" => {
2179                        chrono::NaiveDate::from_ymd_opt(2001, 2, 3)
2180                            .expect("valid sample date")
2181                            .and_hms_opt(4, 5, 6)
2182                            .expect("valid sample time")
2183                            .format_with_items(items.iter())
2184                            .write_to(&mut rendered)
2185                    }
2186                    "timestamp_tz_format" => {
2187                        chrono::DateTime::from_timestamp(981_173_106, 0)
2188                            .expect("valid sample timestamp")
2189                            .format_with_items(items.iter())
2190                            .write_to(&mut rendered)
2191                    }
2192                    "time_format" => chrono::NaiveTime::from_hms_opt(4, 5, 6)
2193                        .expect("valid sample time")
2194                        .format_with_items(items.iter())
2195                        .write_to(&mut rendered),
2196                    _ => unreachable!("all temporal format names are handled above"),
2197                };
2198                if result.is_err() {
2199                    return Err(DataFusionError::Configuration(format!(
2200                        "Invalid datafusion.format.{name}: format is incompatible with its temporal type"
2201                    )));
2202                }
2203            }
2204        }
2205
2206        Ok(Self::new()
2207            .with_display_error(options.safe)
2208            .with_null(&options.null)
2209            .with_date_format(options.date_format.as_deref())
2210            .with_datetime_format(options.datetime_format.as_deref())
2211            .with_timestamp_format(options.timestamp_format.as_deref())
2212            .with_timestamp_tz_format(options.timestamp_tz_format.as_deref())
2213            .with_time_format(options.time_format.as_deref())
2214            .with_duration_format(options.duration_format.into())
2215            .with_types_info(options.types_info))
2216    }
2217}
2218
2219config_namespace! {
2220    /// Options controlling DataFusion's Spark-compatibility layer (functions
2221    /// under `datafusion/spark`). Keys here mirror their `spark.sql.*`
2222    /// equivalents in Apache Spark.
2223    pub struct SparkOptions {
2224        /// Policy for handling duplicate keys in Spark-compatible map-construction
2225        /// functions (`map_from_arrays`, `map_from_entries`, `str_to_map`).
2226        ///
2227        /// Mirrors Spark's
2228        /// [`spark.sql.mapKeyDedupPolicy`](https://github.com/apache/spark/blob/cf3a34e19dfcf70e2d679217ff1ba21302212472/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala#L4961):
2229        /// - `EXCEPTION` (default): raise `[DUPLICATED_MAP_KEY]` at runtime on any duplicate key.
2230        /// - `LAST_WIN`: keep the last occurrence of each duplicate key.
2231        ///
2232        /// Values are case-insensitive.
2233        pub map_key_dedup_policy: MapKeyDedupPolicy, default = MapKeyDedupPolicy::Exception
2234    }
2235}
2236
2237/// A key value pair, with a corresponding description
2238#[derive(Debug, Clone, Hash, PartialEq, Eq)]
2239pub struct ConfigEntry {
2240    /// A unique string to identify this config value
2241    pub key: String,
2242
2243    /// The value if any
2244    pub value: Option<String>,
2245
2246    /// A description of this configuration entry
2247    pub description: &'static str,
2248}
2249
2250/// Configuration options struct, able to store both built-in configuration and custom options
2251#[derive(Debug, Clone, Default)]
2252#[non_exhaustive]
2253pub struct ConfigOptions {
2254    /// Catalog options
2255    pub catalog: CatalogOptions,
2256    /// Execution options
2257    pub execution: ExecutionOptions,
2258    /// Optimizer options
2259    pub optimizer: OptimizerOptions,
2260    /// SQL parser options
2261    pub sql_parser: SqlParserOptions,
2262    /// Explain options
2263    pub explain: ExplainOptions,
2264    /// Optional extensions registered using [`Extensions::insert`]
2265    pub extensions: Extensions,
2266    /// Formatting options when printing batches
2267    pub format: FormatOptions,
2268    /// Spark-compatibility options (functions under `datafusion/spark`)
2269    pub spark: SparkOptions,
2270}
2271
2272impl ConfigField for ConfigOptions {
2273    fn visit<V: Visit>(&self, v: &mut V, _key_prefix: &str, _description: &'static str) {
2274        self.catalog.visit(v, "datafusion.catalog", "");
2275        self.execution.visit(v, "datafusion.execution", "");
2276        self.optimizer.visit(v, "datafusion.optimizer", "");
2277        self.explain.visit(v, "datafusion.explain", "");
2278        self.sql_parser.visit(v, "datafusion.sql_parser", "");
2279        self.format.visit(v, "datafusion.format", "");
2280        self.spark.visit(v, "datafusion.spark", "");
2281    }
2282
2283    fn set(&mut self, key: &str, value: &str) -> Result<()> {
2284        // Extensions are handled in the public `ConfigOptions::set`
2285        let (key, rem) = key.split_once('.').unwrap_or((key, ""));
2286        match key {
2287            "catalog" => self.catalog.set(rem, value),
2288            "execution" => self.execution.set(rem, value),
2289            "optimizer" => self.optimizer.set(rem, value),
2290            "explain" => self.explain.set(rem, value),
2291            "sql_parser" => self.sql_parser.set(rem, value),
2292            "format" => self.format.set(rem, value),
2293            "spark" => self.spark.set(rem, value),
2294            _ => _config_err!("Config value \"{key}\" not found on ConfigOptions"),
2295        }
2296    }
2297
2298    /// Reset a configuration option back to its default value
2299    fn reset(&mut self, key: &str) -> Result<()> {
2300        let Some((prefix, rest)) = key.split_once('.') else {
2301            return _config_err!("could not find config namespace for key \"{key}\"");
2302        };
2303
2304        if prefix != "datafusion" {
2305            return _config_err!("Could not find config namespace \"{prefix}\"");
2306        }
2307
2308        let (section, rem) = rest.split_once('.').unwrap_or((rest, ""));
2309        if rem.is_empty() {
2310            return _config_err!("could not find config field for key \"{key}\"");
2311        }
2312
2313        match section {
2314            "catalog" => self.catalog.reset(rem),
2315            "execution" => self.execution.reset(rem),
2316            "optimizer" => {
2317                if rem == "enable_dynamic_filter_pushdown" {
2318                    let defaults = OptimizerOptions::default();
2319                    self.optimizer.enable_dynamic_filter_pushdown =
2320                        defaults.enable_dynamic_filter_pushdown;
2321                    self.optimizer.enable_topk_dynamic_filter_pushdown =
2322                        defaults.enable_topk_dynamic_filter_pushdown;
2323                    self.optimizer.enable_join_dynamic_filter_pushdown =
2324                        defaults.enable_join_dynamic_filter_pushdown;
2325                    Ok(())
2326                } else {
2327                    self.optimizer.reset(rem)
2328                }
2329            }
2330            "explain" => self.explain.reset(rem),
2331            "sql_parser" => self.sql_parser.reset(rem),
2332            "format" => self.format.reset(rem),
2333            "spark" => self.spark.reset(rem),
2334            other => _config_err!("Config value \"{other}\" not found on ConfigOptions"),
2335        }
2336    }
2337}
2338
2339/// This namespace is reserved for interacting with Foreign Function Interface
2340/// (FFI) based configuration extensions.
2341pub const DATAFUSION_FFI_CONFIG_NAMESPACE: &str = "datafusion_ffi";
2342
2343impl ConfigOptions {
2344    /// Creates a new [`ConfigOptions`] with default values
2345    pub fn new() -> Self {
2346        Self::default()
2347    }
2348
2349    /// Set extensions to provided value
2350    pub fn with_extensions(mut self, extensions: Extensions) -> Self {
2351        self.extensions = extensions;
2352        self
2353    }
2354
2355    /// Set a configuration option
2356    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
2357        let Some((mut prefix, mut inner_key)) = key.split_once('.') else {
2358            return _config_err!("could not find config namespace for key \"{key}\"");
2359        };
2360
2361        if prefix == "datafusion" {
2362            if inner_key == "optimizer.enable_dynamic_filter_pushdown" {
2363                let bool_value = value.parse::<bool>().map_err(|e| {
2364                    DataFusionError::Configuration(format!(
2365                        "Failed to parse '{value}' as bool: {e}",
2366                    ))
2367                })?;
2368
2369                {
2370                    self.optimizer.enable_dynamic_filter_pushdown = bool_value;
2371                    self.optimizer.enable_topk_dynamic_filter_pushdown = bool_value;
2372                    self.optimizer.enable_join_dynamic_filter_pushdown = bool_value;
2373                    self.optimizer.enable_aggregate_dynamic_filter_pushdown = bool_value;
2374                }
2375                return Ok(());
2376            }
2377            return ConfigField::set(self, inner_key, value)
2378                .map_err(|e| e.context(format!("Error setting config {key}")));
2379        }
2380
2381        if !self.extensions.0.contains_key(prefix)
2382            && self
2383                .extensions
2384                .0
2385                .contains_key(DATAFUSION_FFI_CONFIG_NAMESPACE)
2386        {
2387            inner_key = key;
2388            prefix = DATAFUSION_FFI_CONFIG_NAMESPACE;
2389        }
2390
2391        let Some(e) = self.extensions.0.get_mut(prefix) else {
2392            return _config_err!("Could not find config namespace \"{prefix}\"");
2393        };
2394        e.0.set(inner_key, value)
2395    }
2396
2397    /// Create new [`ConfigOptions`], taking values from environment variables
2398    /// where possible.
2399    ///
2400    /// For example, to configure `datafusion.execution.batch_size`
2401    /// ([`ExecutionOptions::batch_size`]) you would set the
2402    /// `DATAFUSION_EXECUTION_BATCH_SIZE` environment variable.
2403    ///
2404    /// The name of the environment variable is the option's key, transformed to
2405    /// uppercase and with periods replaced with underscores.
2406    ///
2407    /// Values are parsed according to the [same rules used in casts from
2408    /// Utf8](https://docs.rs/arrow/latest/arrow/compute/kernels/cast/fn.cast.html).
2409    ///
2410    /// If the value in the environment variable cannot be cast to the type of
2411    /// the configuration option, the default value will be used instead and a
2412    /// warning emitted. Environment variables are read when this method is
2413    /// called, and are not re-read later.
2414    pub fn from_env() -> Result<Self> {
2415        struct Visitor(Vec<String>);
2416
2417        impl Visit for Visitor {
2418            fn some<V: Display>(&mut self, key: &str, _: V, _: &'static str) {
2419                self.0.push(key.to_string())
2420            }
2421
2422            fn none(&mut self, key: &str, _: &'static str) {
2423                self.0.push(key.to_string())
2424            }
2425        }
2426
2427        // Extract the names of all fields and then look up the corresponding
2428        // environment variables. This isn't hugely efficient but avoids
2429        // ambiguity between `a.b` and `a_b` which would both correspond
2430        // to an environment variable of `A_B`
2431
2432        let mut keys = Visitor(vec![]);
2433        let mut ret = Self::default();
2434        ret.visit(&mut keys, "datafusion", "");
2435
2436        for key in keys.0 {
2437            let env = key.to_uppercase().replace('.', "_");
2438            if let Some(var) = std::env::var_os(env) {
2439                let value = var.to_string_lossy();
2440                log::info!("Set {key} to {value} from the environment variable");
2441                ret.set(&key, value.as_ref())?;
2442            }
2443        }
2444
2445        Ok(ret)
2446    }
2447
2448    /// Create new ConfigOptions struct, taking values from a string hash map.
2449    ///
2450    /// Only the built-in configurations will be extracted from the hash map
2451    /// and other key value pairs will be ignored.
2452    pub fn from_string_hash_map(settings: &HashMap<String, String>) -> Result<Self> {
2453        struct Visitor(Vec<String>);
2454
2455        impl Visit for Visitor {
2456            fn some<V: Display>(&mut self, key: &str, _: V, _: &'static str) {
2457                self.0.push(key.to_string())
2458            }
2459
2460            fn none(&mut self, key: &str, _: &'static str) {
2461                self.0.push(key.to_string())
2462            }
2463        }
2464
2465        let mut keys = Visitor(vec![]);
2466        let mut ret = Self::default();
2467        ret.visit(&mut keys, "datafusion", "");
2468
2469        for key in keys.0 {
2470            if let Some(var) = settings.get(&key) {
2471                ret.set(&key, var)?;
2472            }
2473        }
2474
2475        Ok(ret)
2476    }
2477
2478    /// Returns the [`ConfigEntry`] stored within this [`ConfigOptions`]
2479    pub fn entries(&self) -> Vec<ConfigEntry> {
2480        struct Visitor(Vec<ConfigEntry>);
2481
2482        impl Visit for Visitor {
2483            fn some<V: Display>(
2484                &mut self,
2485                key: &str,
2486                value: V,
2487                description: &'static str,
2488            ) {
2489                self.0.push(ConfigEntry {
2490                    key: key.to_string(),
2491                    value: Some(value.to_string()),
2492                    description,
2493                })
2494            }
2495
2496            fn none(&mut self, key: &str, description: &'static str) {
2497                self.0.push(ConfigEntry {
2498                    key: key.to_string(),
2499                    value: None,
2500                    description,
2501                })
2502            }
2503        }
2504
2505        let mut v = Visitor(vec![]);
2506        self.visit(&mut v, "datafusion", "");
2507
2508        v.0.extend(self.extensions.0.values().flat_map(|e| e.0.entries()));
2509        v.0
2510    }
2511
2512    /// Generate documentation that can be included in the user guide
2513    pub fn generate_config_markdown() -> String {
2514        use std::fmt::Write as _;
2515
2516        let mut s = Self::default();
2517
2518        // Normalize for display
2519        s.execution.target_partitions = 0;
2520        s.execution.planning_concurrency = 0;
2521
2522        let mut docs = "| key | default | description |\n".to_string();
2523        docs += "|-----|---------|-------------|\n";
2524        let mut entries = s.entries();
2525        entries.sort_unstable_by(|a, b| a.key.cmp(&b.key));
2526
2527        for entry in s.entries() {
2528            let _ = writeln!(
2529                &mut docs,
2530                "| {} | {} | {} |",
2531                entry.key,
2532                display_default(entry.value.as_deref()),
2533                entry.description
2534            );
2535        }
2536        docs
2537    }
2538}
2539
2540/// Renders a default value for the generated documentation table.
2541///
2542/// Values containing `_` or `*` are shown as code, since markdown would otherwise read them
2543/// as formatting: a default of `__HIVE_DEFAULT_PARTITION__` renders as bold text.
2544fn display_default(value: Option<&str>) -> Cow<'_, str> {
2545    match value {
2546        None => Cow::Borrowed("NULL"),
2547        Some(value) if value.contains(['_', '*']) => Cow::Owned(format!("`{value}`")),
2548        Some(value) => Cow::Borrowed(value),
2549    }
2550}
2551
2552/// [`ConfigExtension`] provides a mechanism to store third-party configuration
2553/// within DataFusion [`ConfigOptions`]
2554///
2555/// This mechanism can be used to pass configuration to user defined functions
2556/// or optimizer passes
2557///
2558/// # Example
2559/// ```
2560/// use datafusion_common::{
2561///     config::ConfigExtension, config::ConfigOptions, extensions_options,
2562/// };
2563/// // Define a new configuration struct using the `extensions_options` macro
2564/// extensions_options! {
2565///    /// My own config options.
2566///    pub struct MyConfig {
2567///        /// Should "foo" be replaced by "bar"?
2568///        pub foo_to_bar: bool, default = true
2569///
2570///        /// How many "baz" should be created?
2571///        pub baz_count: usize, default = 1337
2572///    }
2573/// }
2574///
2575/// impl ConfigExtension for MyConfig {
2576///     const PREFIX: &'static str = "my_config";
2577/// }
2578///
2579/// // set up config struct and register extension
2580/// let mut config = ConfigOptions::default();
2581/// config.extensions.insert(MyConfig::default());
2582///
2583/// // overwrite config default
2584/// config.set("my_config.baz_count", "42").unwrap();
2585///
2586/// // check config state
2587/// let my_config = config.extensions.get::<MyConfig>().unwrap();
2588/// assert!(my_config.foo_to_bar,);
2589/// assert_eq!(my_config.baz_count, 42,);
2590/// ```
2591///
2592/// # Note:
2593/// Unfortunately associated constants are not currently object-safe, and so this
2594/// extends the object-safe [`ExtensionOptions`]
2595pub trait ConfigExtension: ExtensionOptions {
2596    /// Configuration namespace prefix to use
2597    ///
2598    /// All values under this will be prefixed with `$PREFIX + "."`
2599    const PREFIX: &'static str;
2600}
2601
2602/// An object-safe API for storing arbitrary configuration.
2603///
2604/// See [`ConfigExtension`] for user defined configuration
2605pub trait ExtensionOptions: Send + Sync + fmt::Debug + 'static {
2606    /// Return `self` as [`Any`]
2607    ///
2608    /// This is needed until trait upcasting is stabilized
2609    fn as_any(&self) -> &dyn Any;
2610
2611    /// Return `self` as [`Any`]
2612    ///
2613    /// This is needed until trait upcasting is stabilized
2614    fn as_any_mut(&mut self) -> &mut dyn Any;
2615
2616    /// Return a deep clone of this [`ExtensionOptions`]
2617    ///
2618    /// It is important this does not share mutable state to avoid consistency issues
2619    /// with configuration changing whilst queries are executing
2620    fn cloned(&self) -> Box<dyn ExtensionOptions>;
2621
2622    /// Set the given `key`, `value` pair
2623    fn set(&mut self, key: &str, value: &str) -> Result<()>;
2624
2625    /// Returns the [`ConfigEntry`] stored in this [`ExtensionOptions`]
2626    fn entries(&self) -> Vec<ConfigEntry>;
2627}
2628
2629/// A type-safe container for [`ConfigExtension`]
2630#[derive(Debug, Default, Clone)]
2631pub struct Extensions(BTreeMap<&'static str, ExtensionBox>);
2632
2633impl Extensions {
2634    /// Create a new, empty [`Extensions`]
2635    pub fn new() -> Self {
2636        Self(BTreeMap::new())
2637    }
2638
2639    /// Registers a [`ConfigExtension`] with this [`ConfigOptions`]
2640    pub fn insert<T: ConfigExtension>(&mut self, extension: T) {
2641        assert_ne!(T::PREFIX, "datafusion");
2642        let e = ExtensionBox(Box::new(extension));
2643        self.0.insert(T::PREFIX, e);
2644    }
2645
2646    /// Retrieves the extension of the given type if any
2647    pub fn get<T: ConfigExtension>(&self) -> Option<&T> {
2648        self.0.get(T::PREFIX)?.0.as_any().downcast_ref()
2649    }
2650
2651    /// Retrieves the extension of the given type if any
2652    pub fn get_mut<T: ConfigExtension>(&mut self) -> Option<&mut T> {
2653        let e = self.0.get_mut(T::PREFIX)?;
2654        e.0.as_any_mut().downcast_mut()
2655    }
2656
2657    /// Iterates all the config extension entries yielding their prefix and their
2658    /// [ExtensionOptions] implementation.
2659    pub fn iter(
2660        &self,
2661    ) -> impl Iterator<Item = (&'static str, &Box<dyn ExtensionOptions>)> {
2662        self.0.iter().map(|(k, v)| (*k, &v.0))
2663    }
2664}
2665
2666#[derive(Debug)]
2667struct ExtensionBox(Box<dyn ExtensionOptions>);
2668
2669impl Clone for ExtensionBox {
2670    fn clone(&self) -> Self {
2671        Self(self.0.cloned())
2672    }
2673}
2674
2675/// A trait implemented by `config_namespace` and for field types that provides
2676/// the ability to walk and mutate the configuration tree
2677pub trait ConfigField {
2678    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str);
2679
2680    fn set(&mut self, key: &str, value: &str) -> Result<()>;
2681
2682    fn reset(&mut self, key: &str) -> Result<()> {
2683        _config_err!("Reset is not supported for this config field, key: {}", key)
2684    }
2685}
2686
2687impl<F: ConfigField + Default> ConfigField for Option<F> {
2688    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
2689        match self {
2690            Some(s) => s.visit(v, key, description),
2691            None => v.none(key, description),
2692        }
2693    }
2694
2695    fn set(&mut self, key: &str, value: &str) -> Result<()> {
2696        self.get_or_insert_with(Default::default).set(key, value)
2697    }
2698
2699    fn reset(&mut self, key: &str) -> Result<()> {
2700        if key.is_empty() {
2701            *self = Default::default();
2702            Ok(())
2703        } else {
2704            self.get_or_insert_with(Default::default).reset(key)
2705        }
2706    }
2707}
2708
2709/// Default transformation to parse a [`ConfigField`] for a string.
2710///
2711/// This uses [`FromStr`] to parse the data.
2712pub fn default_config_transform<T>(input: &str) -> Result<T>
2713where
2714    T: FromStr,
2715    <T as FromStr>::Err: Sync + Send + Error + 'static,
2716{
2717    input.parse().map_err(|e| {
2718        DataFusionError::Context(
2719            format!(
2720                "Error parsing '{}' as {}",
2721                input,
2722                std::any::type_name::<T>()
2723            ),
2724            Box::new(DataFusionError::External(Box::new(e))),
2725        )
2726    })
2727}
2728
2729/// Macro that generates [`ConfigField`] for a given type.
2730///
2731/// # Usage
2732/// This always requires [`Display`] to be implemented for the given type.
2733///
2734/// There are two ways to invoke this macro. The first one uses
2735/// [`default_config_transform`]/[`FromStr`] to parse the data:
2736///
2737/// ```ignore
2738/// config_field(MyType);
2739/// ```
2740///
2741/// Note that the parsing error MUST implement [`std::error::Error`]!
2742///
2743/// Or you can specify how you want to parse an [`str`] into the type:
2744///
2745/// ```ignore
2746/// fn parse_it(s: &str) -> Result<MyType> {
2747///     ...
2748/// }
2749///
2750/// config_field(
2751///     MyType,
2752///     value => parse_it(value)
2753/// );
2754/// ```
2755#[macro_export]
2756macro_rules! config_field {
2757    ($t:ty) => {
2758        config_field!($t, value => $crate::config::default_config_transform(value)?);
2759    };
2760
2761    ($t:ty, $arg:ident => $transform:expr) => {
2762        impl $crate::config::ConfigField for $t {
2763            fn visit<V: $crate::config::Visit>(&self, v: &mut V, key: &str, description: &'static str) {
2764                v.some(key, self, description)
2765            }
2766
2767            fn set(&mut self, _: &str, $arg: &str) -> $crate::error::Result<()> {
2768                *self = $transform;
2769                Ok(())
2770            }
2771
2772            fn reset(&mut self, key: &str) -> $crate::error::Result<()> {
2773                if key.is_empty() {
2774                    *self = <$t as Default>::default();
2775                    Ok(())
2776                } else {
2777                    $crate::error::_config_err!(
2778                        "Config field is a scalar {} and does not have nested field \"{}\"",
2779                        stringify!($t),
2780                        key
2781                    )
2782                }
2783            }
2784        }
2785    };
2786}
2787
2788config_field!(String);
2789config_field!(bool, value => default_config_transform(value.to_lowercase().as_str())?);
2790config_field!(usize);
2791config_field!(f64);
2792config_field!(u64);
2793config_field!(u32);
2794config_field!(i32);
2795
2796impl ConfigField for u8 {
2797    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
2798        v.some(key, self, description)
2799    }
2800
2801    fn set(&mut self, key: &str, value: &str) -> Result<()> {
2802        if value.is_empty() {
2803            return Err(DataFusionError::Configuration(format!(
2804                "Input string for {key} key is empty"
2805            )));
2806        }
2807        // Check if the string is a valid number
2808        if let Ok(num) = value.parse::<u8>() {
2809            // TODO: Let's decide how we treat the numerical strings.
2810            *self = num;
2811        } else {
2812            let bytes = value.as_bytes();
2813            // Check if the first character is ASCII (single byte)
2814            if bytes.len() > 1 || !value.chars().next().unwrap().is_ascii() {
2815                return Err(DataFusionError::Configuration(format!(
2816                    "Error parsing {value} as u8. Non-ASCII string provided"
2817                )));
2818            }
2819            *self = bytes[0];
2820        }
2821        Ok(())
2822    }
2823}
2824
2825impl ConfigField for CompressionTypeVariant {
2826    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
2827        v.some(key, self, description)
2828    }
2829
2830    fn set(&mut self, _: &str, value: &str) -> Result<()> {
2831        *self = CompressionTypeVariant::from_str(value)?;
2832        Ok(())
2833    }
2834}
2835
2836impl ConfigField for CsvQuoteStyle {
2837    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
2838        v.some(key, self, description)
2839    }
2840
2841    fn set(&mut self, _: &str, value: &str) -> Result<()> {
2842        *self = CsvQuoteStyle::from_str(value)?;
2843        Ok(())
2844    }
2845}
2846
2847/// An implementation trait used to recursively walk configuration
2848pub trait Visit {
2849    fn some<V: Display>(&mut self, key: &str, value: V, description: &'static str);
2850
2851    fn none(&mut self, key: &str, description: &'static str);
2852}
2853
2854/// Convenience macro to create [`ExtensionsOptions`].
2855///
2856/// The created structure implements the following traits:
2857///
2858/// - [`Clone`]
2859/// - [`Debug`]
2860/// - [`Default`]
2861/// - [`ExtensionOptions`]
2862///
2863/// # Usage
2864/// The syntax is:
2865///
2866/// ```text
2867/// extensions_options! {
2868///      /// Struct docs (optional).
2869///     [<vis>] struct <StructName> {
2870///         /// Field docs (optional)
2871///         [<vis>] <field_name>: <field_type>, default = <default_value>
2872///
2873///         ... more fields
2874///     }
2875/// }
2876/// ```
2877///
2878/// The placeholders are:
2879/// - `[<vis>]`: Optional visibility modifier like `pub` or `pub(crate)`.
2880/// - `<StructName>`: Struct name like `MyStruct`.
2881/// - `<field_name>`: Field name like `my_field`.
2882/// - `<field_type>`: Field type like `u8`.
2883/// - `<default_value>`: Default value matching the field type like `42`.
2884///
2885/// # Example
2886/// See also a full example on the [`ConfigExtension`] documentation
2887///
2888/// ```
2889/// use datafusion_common::extensions_options;
2890///
2891/// extensions_options! {
2892///     /// My own config options.
2893///     pub struct MyConfig {
2894///         /// Should "foo" be replaced by "bar"?
2895///         pub foo_to_bar: bool, default = true
2896///
2897///         /// How many "baz" should be created?
2898///         pub baz_count: usize, default = 1337
2899///     }
2900/// }
2901/// ```
2902///
2903///
2904/// [`Debug`]: std::fmt::Debug
2905/// [`ExtensionsOptions`]: crate::config::ExtensionOptions
2906#[macro_export]
2907macro_rules! extensions_options {
2908    (
2909     $(#[doc = $struct_d:tt])*
2910     $vis:vis struct $struct_name:ident {
2911        $(
2912        $(#[doc = $d:tt])*
2913        $field_vis:vis $field_name:ident : $field_type:ty, default = $default:expr
2914        )*$(,)*
2915    }
2916    ) => {
2917        $(#[doc = $struct_d])*
2918        #[derive(Debug, Clone)]
2919        #[non_exhaustive]
2920        $vis struct $struct_name{
2921            $(
2922            $(#[doc = $d])*
2923            $field_vis $field_name : $field_type,
2924            )*
2925        }
2926
2927        impl Default for $struct_name {
2928            fn default() -> Self {
2929                Self {
2930                    $($field_name: $default),*
2931                }
2932            }
2933        }
2934
2935        impl $crate::config::ExtensionOptions for $struct_name {
2936            fn as_any(&self) -> &dyn ::std::any::Any {
2937                self
2938            }
2939
2940            fn as_any_mut(&mut self) -> &mut dyn ::std::any::Any {
2941                self
2942            }
2943
2944            fn cloned(&self) -> Box<dyn $crate::config::ExtensionOptions> {
2945                Box::new(self.clone())
2946            }
2947
2948            fn set(&mut self, key: &str, value: &str) -> $crate::error::Result<()> {
2949                $crate::config::ConfigField::set(self, key, value)
2950            }
2951
2952            fn entries(&self) -> Vec<$crate::config::ConfigEntry> {
2953                struct Visitor(Vec<$crate::config::ConfigEntry>);
2954
2955                impl $crate::config::Visit for Visitor {
2956                    fn some<V: std::fmt::Display>(
2957                        &mut self,
2958                        key: &str,
2959                        value: V,
2960                        description: &'static str,
2961                    ) {
2962                        self.0.push($crate::config::ConfigEntry {
2963                            key: key.to_string(),
2964                            value: Some(value.to_string()),
2965                            description,
2966                        })
2967                    }
2968
2969                    fn none(&mut self, key: &str, description: &'static str) {
2970                        self.0.push($crate::config::ConfigEntry {
2971                            key: key.to_string(),
2972                            value: None,
2973                            description,
2974                        })
2975                    }
2976                }
2977
2978                let mut v = Visitor(vec![]);
2979                // The prefix is not used for extensions.
2980                // The description is generated in ConfigField::visit.
2981                // We can just pass empty strings here.
2982                $crate::config::ConfigField::visit(self, &mut v, "", "");
2983                v.0
2984            }
2985        }
2986
2987        impl $crate::config::ConfigField for $struct_name {
2988            fn set(&mut self, key: &str, value: &str) -> $crate::error::Result<()> {
2989                let (key, rem) = key.split_once('.').unwrap_or((key, ""));
2990                match key {
2991                    $(
2992                        stringify!($field_name) => {
2993                            // Safely apply deprecated attribute if present
2994                            // $(#[allow(deprecated)])?
2995                            {
2996                                            self.$field_name.set(rem, value.as_ref())
2997                            }
2998                        },
2999                    )*
3000                    _ => return $crate::error::_config_err!(
3001                        "Config value \"{}\" not found on {}", key, stringify!($struct_name)
3002                    )
3003                }
3004            }
3005
3006            fn visit<V: $crate::config::Visit>(&self, v: &mut V, _key_prefix: &str, _description: &'static str) {
3007                $(
3008                    let key = stringify!($field_name).to_string();
3009                    let desc = concat!($($d),*).trim();
3010                    self.$field_name.visit(v, key.as_str(), desc);
3011                )*
3012            }
3013        }
3014    }
3015}
3016
3017/// These file types have special built in behavior for configuration.
3018/// Use TableOptions::Extensions for configuring other file types.
3019#[derive(Debug, Clone)]
3020pub enum ConfigFileType {
3021    CSV,
3022    #[cfg(feature = "parquet")]
3023    PARQUET,
3024    JSON,
3025    ARROW,
3026}
3027
3028/// Represents the configuration options available for handling different table formats within a data processing application.
3029/// This struct encompasses options for various file formats including CSV, Parquet, and JSON, allowing for flexible configuration
3030/// of parsing and writing behaviors specific to each format. Additionally, it supports extending functionality through custom extensions.
3031#[derive(Debug, Clone, Default)]
3032pub struct TableOptions {
3033    /// Configuration options for CSV file handling. This includes settings like the delimiter,
3034    /// quote character, and whether the first row is considered as headers.
3035    pub csv: CsvOptions,
3036
3037    /// Configuration options for Parquet file handling. This includes settings for compression,
3038    /// encoding, and other Parquet-specific file characteristics.
3039    pub parquet: TableParquetOptions,
3040
3041    /// Configuration options for JSON file handling.
3042    pub json: JsonOptions,
3043
3044    /// Configuration options for Arrow IPC file handling. This includes settings for the
3045    /// compression codec used for record batches written to disk.
3046    pub arrow: ArrowOptions,
3047
3048    /// The current file format that the table operations should assume. This option allows
3049    /// for dynamic switching between the supported file types (e.g., CSV, Parquet, JSON).
3050    pub current_format: Option<ConfigFileType>,
3051
3052    /// Optional extensions that can be used to extend or customize the behavior of the table
3053    /// options. Extensions can be registered using `Extensions::insert` and might include
3054    /// custom file handling logic, additional configuration parameters, or other enhancements.
3055    pub extensions: Extensions,
3056}
3057
3058impl ConfigField for TableOptions {
3059    /// Visits configuration settings for the current file format, or all formats if none is selected.
3060    ///
3061    /// This method adapts the behavior based on whether a file format is currently selected in `current_format`.
3062    /// If a format is selected, it visits only the settings relevant to that format. Otherwise,
3063    /// it visits all available format settings.
3064    fn visit<V: Visit>(&self, v: &mut V, _key_prefix: &str, _description: &'static str) {
3065        if let Some(file_type) = &self.current_format {
3066            match file_type {
3067                #[cfg(feature = "parquet")]
3068                ConfigFileType::PARQUET => self.parquet.visit(v, "format", ""),
3069                ConfigFileType::CSV => self.csv.visit(v, "format", ""),
3070                ConfigFileType::JSON => self.json.visit(v, "format", ""),
3071                ConfigFileType::ARROW => self.arrow.visit(v, "format", ""),
3072            }
3073        } else {
3074            self.csv.visit(v, "csv", "");
3075            self.parquet.visit(v, "parquet", "");
3076            self.json.visit(v, "json", "");
3077            self.arrow.visit(v, "arrow", "");
3078        }
3079    }
3080
3081    /// Sets a configuration value for a specific key within `TableOptions`.
3082    ///
3083    /// This method delegates setting configuration values to the specific file format configurations,
3084    /// based on the current format selected. If no format is selected, it returns an error.
3085    ///
3086    /// # Parameters
3087    ///
3088    /// * `key`: The configuration key specifying which setting to adjust, prefixed with the format (e.g., "format.delimiter")
3089    ///   for CSV format.
3090    /// * `value`: The value to set for the specified configuration key.
3091    ///
3092    /// # Returns
3093    ///
3094    /// A result indicating success or an error if the key is not recognized, if a format is not specified,
3095    /// or if setting the configuration value fails for the specific format.
3096    fn set(&mut self, key: &str, value: &str) -> Result<()> {
3097        // Extensions are handled in the public `ConfigOptions::set`
3098        let (key, rem) = key.split_once('.').unwrap_or((key, ""));
3099        match key {
3100            "format" => {
3101                let Some(format) = &self.current_format else {
3102                    return _config_err!("Specify a format for TableOptions");
3103                };
3104                match format {
3105                    #[cfg(feature = "parquet")]
3106                    ConfigFileType::PARQUET => self.parquet.set(rem, value),
3107                    ConfigFileType::CSV => self.csv.set(rem, value),
3108                    ConfigFileType::JSON => self.json.set(rem, value),
3109                    ConfigFileType::ARROW => self.arrow.set(rem, value),
3110                }
3111            }
3112            _ => _config_err!("Config value \"{key}\" not found on TableOptions"),
3113        }
3114    }
3115}
3116
3117impl TableOptions {
3118    /// Constructs a new instance of `TableOptions` with default settings.
3119    ///
3120    /// # Returns
3121    ///
3122    /// A new `TableOptions` instance with default configuration values.
3123    pub fn new() -> Self {
3124        Self::default()
3125    }
3126
3127    /// Creates a new `TableOptions` instance initialized with settings from a given session config.
3128    ///
3129    /// # Parameters
3130    ///
3131    /// * `config`: A reference to the session `ConfigOptions` from which to derive initial settings.
3132    ///
3133    /// # Returns
3134    ///
3135    /// A new `TableOptions` instance with settings applied from the session config.
3136    pub fn default_from_session_config(config: &ConfigOptions) -> Self {
3137        let initial = TableOptions::default();
3138        initial.combine_with_session_config(config)
3139    }
3140
3141    /// Updates the current `TableOptions` with settings from a given session config.
3142    ///
3143    /// # Parameters
3144    ///
3145    /// * `config`: A reference to the session `ConfigOptions` whose settings are to be applied.
3146    ///
3147    /// # Returns
3148    ///
3149    /// A new `TableOptions` instance with updated settings from the session config.
3150    #[must_use = "this method returns a new instance"]
3151    pub fn combine_with_session_config(&self, config: &ConfigOptions) -> Self {
3152        let mut clone = self.clone();
3153        clone.parquet.global = config.execution.parquet.clone();
3154        clone
3155    }
3156
3157    /// Sets the file format for the table.
3158    ///
3159    /// # Parameters
3160    ///
3161    /// * `format`: The file format to use (e.g., CSV, Parquet).
3162    pub fn set_config_format(&mut self, format: ConfigFileType) {
3163        self.current_format = Some(format);
3164    }
3165
3166    /// Sets the extensions for this `TableOptions` instance.
3167    ///
3168    /// # Parameters
3169    ///
3170    /// * `extensions`: The `Extensions` instance to set.
3171    ///
3172    /// # Returns
3173    ///
3174    /// A new `TableOptions` instance with the specified extensions applied.
3175    pub fn with_extensions(mut self, extensions: Extensions) -> Self {
3176        self.extensions = extensions;
3177        self
3178    }
3179
3180    /// Sets a specific configuration option.
3181    ///
3182    /// # Parameters
3183    ///
3184    /// * `key`: The configuration key (e.g., "format.delimiter").
3185    /// * `value`: The value to set for the specified key.
3186    ///
3187    /// # Returns
3188    ///
3189    /// A result indicating success or failure in setting the configuration option.
3190    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
3191        let Some((mut prefix, _)) = key.split_once('.') else {
3192            return _config_err!("could not find config namespace for key \"{key}\"");
3193        };
3194
3195        if prefix == "format" {
3196            return ConfigField::set(self, key, value);
3197        }
3198
3199        if prefix == "execution" {
3200            return Ok(());
3201        }
3202
3203        if !self.extensions.0.contains_key(prefix)
3204            && self
3205                .extensions
3206                .0
3207                .contains_key(DATAFUSION_FFI_CONFIG_NAMESPACE)
3208        {
3209            prefix = DATAFUSION_FFI_CONFIG_NAMESPACE;
3210        }
3211
3212        let Some(e) = self.extensions.0.get_mut(prefix) else {
3213            return _config_err!("Could not find config namespace \"{prefix}\"");
3214        };
3215        e.0.set(key, value)
3216    }
3217
3218    /// Initializes a new `TableOptions` from a hash map of string settings.
3219    ///
3220    /// # Parameters
3221    ///
3222    /// * `settings`: A hash map where each key-value pair represents a configuration setting.
3223    ///
3224    /// # Returns
3225    ///
3226    /// A result containing the new `TableOptions` instance or an error if any setting could not be applied.
3227    pub fn from_string_hash_map(settings: &HashMap<String, String>) -> Result<Self> {
3228        let mut ret = Self::default();
3229        for (k, v) in settings {
3230            ret.set(k, v)?;
3231        }
3232
3233        Ok(ret)
3234    }
3235
3236    /// Modifies the current `TableOptions` instance with settings from a hash map.
3237    ///
3238    /// # Parameters
3239    ///
3240    /// * `settings`: A hash map where each key-value pair represents a configuration setting.
3241    ///
3242    /// # Returns
3243    ///
3244    /// A result indicating success or failure in applying the settings.
3245    pub fn alter_with_string_hash_map(
3246        &mut self,
3247        settings: &HashMap<String, String>,
3248    ) -> Result<()> {
3249        for (k, v) in settings {
3250            self.set(k, v)?;
3251        }
3252        Ok(())
3253    }
3254
3255    /// Retrieves all configuration entries from this `TableOptions`.
3256    ///
3257    /// # Returns
3258    ///
3259    /// A vector of `ConfigEntry` instances, representing all the configuration options within this `TableOptions`.
3260    pub fn entries(&self) -> Vec<ConfigEntry> {
3261        struct Visitor(Vec<ConfigEntry>);
3262
3263        impl Visit for Visitor {
3264            fn some<V: Display>(
3265                &mut self,
3266                key: &str,
3267                value: V,
3268                description: &'static str,
3269            ) {
3270                self.0.push(ConfigEntry {
3271                    key: key.to_string(),
3272                    value: Some(value.to_string()),
3273                    description,
3274                })
3275            }
3276
3277            fn none(&mut self, key: &str, description: &'static str) {
3278                self.0.push(ConfigEntry {
3279                    key: key.to_string(),
3280                    value: None,
3281                    description,
3282                })
3283            }
3284        }
3285
3286        let mut v = Visitor(vec![]);
3287        self.visit(&mut v, "format", "");
3288
3289        v.0.extend(self.extensions.0.values().flat_map(|e| e.0.entries()));
3290        v.0
3291    }
3292}
3293
3294/// Options that control how Parquet files are read, including global options
3295/// that apply to all columns and optional column-specific overrides
3296///
3297/// Closely tied to `ParquetWriterOptions` (see `crate::file_options::parquet_writer::ParquetWriterOptions` when the "parquet" feature is enabled).
3298/// Properties not included in [`TableParquetOptions`] may not be configurable at the external API
3299/// (e.g. sorting_columns).
3300#[derive(Clone, Default, Debug, PartialEq)]
3301pub struct TableParquetOptions {
3302    /// Global Parquet options that propagates to all columns.
3303    pub global: ParquetOptions,
3304    /// Column specific options. Default usage is parquet.XX::column.
3305    pub column_specific_options: HashMap<String, ParquetColumnOptions>,
3306    /// Additional file-level metadata to include. Inserted into the key_value_metadata
3307    /// for the written [`FileMetaData`](https://docs.rs/parquet/latest/parquet/file/metadata/struct.FileMetaData.html).
3308    ///
3309    /// Multiple entries are permitted
3310    /// ```sql
3311    /// OPTIONS (
3312    ///    'format.metadata::key1' '',
3313    ///    'format.metadata::key2' 'value',
3314    ///    'format.metadata::key3' 'value has spaces',
3315    ///    'format.metadata::key4' 'value has special chars :: :',
3316    ///    'format.metadata::key_dupe' 'original will be overwritten',
3317    ///    'format.metadata::key_dupe' 'final'
3318    /// )
3319    /// ```
3320    pub key_value_metadata: HashMap<String, Option<String>>,
3321    /// Options for configuring Parquet modular encryption
3322    ///
3323    /// To use Parquet encryption, you must enable the `parquet_encryption` feature flag, as it is not activated by default.
3324    /// See ConfigFileEncryptionProperties and ConfigFileDecryptionProperties in datafusion/common/src/config.rs
3325    /// These can be set via 'format.crypto', for example:
3326    /// ```sql
3327    /// OPTIONS (
3328    ///    'format.crypto.file_encryption.encrypt_footer' 'true',
3329    ///    'format.crypto.file_encryption.footer_key_as_hex' '30313233343536373839303132333435',  -- b"0123456789012345" */
3330    ///    'format.crypto.file_encryption.column_key_as_hex::double_field' '31323334353637383930313233343530', -- b"1234567890123450"
3331    ///    'format.crypto.file_encryption.column_key_as_hex::float_field' '31323334353637383930313233343531', -- b"1234567890123451"
3332    ///     -- Same for decryption
3333    ///    'format.crypto.file_decryption.footer_key_as_hex' '30313233343536373839303132333435', -- b"0123456789012345"
3334    ///    'format.crypto.file_decryption.column_key_as_hex::double_field' '31323334353637383930313233343530', -- b"1234567890123450"
3335    ///    'format.crypto.file_decryption.column_key_as_hex::float_field' '31323334353637383930313233343531', -- b"1234567890123451"
3336    /// )
3337    /// ```
3338    /// See datafusion-cli/tests/sql/encrypted_parquet.sql for a more complete example.
3339    /// Note that keys must be provided as in hex format since these are binary strings.
3340    pub crypto: ParquetEncryptionOptions,
3341}
3342
3343impl TableParquetOptions {
3344    /// Return new default TableParquetOptions
3345    pub fn new() -> Self {
3346        Self::default()
3347    }
3348
3349    /// Set whether the encoding of the arrow metadata should occur
3350    /// during the writing of parquet.
3351    ///
3352    /// Default is to encode the arrow schema in the file kv_metadata.
3353    pub fn with_skip_arrow_metadata(self, skip: bool) -> Self {
3354        Self {
3355            global: ParquetOptions {
3356                skip_arrow_metadata: skip,
3357                ..self.global
3358            },
3359            ..self
3360        }
3361    }
3362
3363    /// Retrieves all configuration entries from this `TableParquetOptions`.
3364    ///
3365    /// # Returns
3366    ///
3367    /// A vector of `ConfigEntry` instances, representing all the configuration options within this
3368    pub fn entries(self: &TableParquetOptions) -> Vec<ConfigEntry> {
3369        struct Visitor(Vec<ConfigEntry>);
3370
3371        impl Visit for Visitor {
3372            fn some<V: Display>(
3373                &mut self,
3374                key: &str,
3375                value: V,
3376                description: &'static str,
3377            ) {
3378                self.0.push(ConfigEntry {
3379                    key: key[1..].to_string(),
3380                    value: Some(value.to_string()),
3381                    description,
3382                })
3383            }
3384
3385            fn none(&mut self, key: &str, description: &'static str) {
3386                self.0.push(ConfigEntry {
3387                    key: key[1..].to_string(),
3388                    value: None,
3389                    description,
3390                })
3391            }
3392        }
3393
3394        let mut v = Visitor(vec![]);
3395        self.visit(&mut v, "", "");
3396
3397        v.0
3398    }
3399}
3400
3401impl ConfigField for TableParquetOptions {
3402    fn visit<V: Visit>(&self, v: &mut V, key_prefix: &str, description: &'static str) {
3403        self.global.visit(v, key_prefix, description);
3404        self.column_specific_options
3405            .visit(v, key_prefix, description);
3406        self.crypto
3407            .visit(v, &format!("{key_prefix}.crypto"), description);
3408    }
3409
3410    fn set(&mut self, key: &str, value: &str) -> Result<()> {
3411        // Determine if the key is a global, metadata, or column-specific setting
3412        if key.starts_with("metadata::") {
3413            let k = match key.split("::").collect::<Vec<_>>()[..] {
3414                [_meta] | [_meta, ""] => {
3415                    return _config_err!(
3416                        "Invalid metadata key provided, missing key in metadata::<key>"
3417                    );
3418                }
3419                [_meta, k] => k.into(),
3420                _ => {
3421                    return _config_err!(
3422                        "Invalid metadata key provided, found too many '::' in \"{key}\""
3423                    );
3424                }
3425            };
3426            self.key_value_metadata.insert(k, Some(value.into()));
3427            Ok(())
3428        } else if let Some(crypto_feature) = key.strip_prefix("crypto.") {
3429            self.crypto.set(crypto_feature, value)
3430        } else if key.contains("::") {
3431            self.column_specific_options.set(key, value)
3432        } else {
3433            self.global.set(key, value)
3434        }
3435    }
3436}
3437
3438macro_rules! config_namespace_with_hashmap {
3439    (
3440     $(#[doc = $struct_d:tt])*
3441     $(#[deprecated($($struct_depr:tt)*)])?  // Optional struct-level deprecated attribute
3442     $vis:vis struct $struct_name:ident {
3443        $(
3444        $(#[doc = $d:tt])*
3445        $(#[deprecated($($field_depr:tt)*)])? // Optional field-level deprecated attribute
3446        $field_vis:vis $field_name:ident : $field_type:ty, $(transform = $transform:expr,)? default = $default:expr
3447        )*$(,)*
3448    }
3449    ) => {
3450
3451        $(#[doc = $struct_d])*
3452        $(#[deprecated($($struct_depr)*)])?  // Apply struct deprecation
3453        #[derive(Debug, Clone, PartialEq)]
3454        $vis struct $struct_name{
3455            $(
3456            $(#[doc = $d])*
3457            $(#[deprecated($($field_depr)*)])? // Apply field deprecation
3458            $field_vis $field_name : $field_type,
3459            )*
3460        }
3461
3462        impl ConfigField for $struct_name {
3463            fn set(&mut self, key: &str, value: &str) -> Result<()> {
3464                let (key, rem) = key.split_once('.').unwrap_or((key, ""));
3465                match key {
3466                    $(
3467                       stringify!($field_name) => {
3468                           // Handle deprecated fields
3469                           $(let value = $transform(value);)?
3470                           self.$field_name.set(rem, value.as_ref())
3471                       },
3472                    )*
3473                    _ => _config_err!(
3474                        "Config value \"{}\" not found on {}", key, stringify!($struct_name)
3475                    )
3476                }
3477            }
3478
3479            fn visit<V: Visit>(&self, v: &mut V, key_prefix: &str, _description: &'static str) {
3480                $(
3481                let key = format!(concat!("{}.", stringify!($field_name)), key_prefix);
3482                let desc = concat!($($d),*).trim();
3483                // Handle deprecated fields
3484                self.$field_name.visit(v, key.as_str(), desc);
3485                )*
3486            }
3487        }
3488
3489        impl Default for $struct_name {
3490            fn default() -> Self {
3491                Self {
3492                    $($field_name: $default),*
3493                }
3494            }
3495        }
3496
3497        impl ConfigField for HashMap<String,$struct_name> {
3498            fn set(&mut self, key: &str, value: &str) -> Result<()> {
3499                let parts: Vec<&str> = key.splitn(2, "::").collect();
3500                match parts.as_slice() {
3501                    [inner_key, hashmap_key] => {
3502                        // Get or create the struct for the specified key
3503                        let inner_value = self
3504                            .entry((*hashmap_key).to_owned())
3505                            .or_insert_with($struct_name::default);
3506
3507                        inner_value.set(inner_key, value)
3508                    }
3509                    _ => _config_err!("Unrecognized key '{key}'."),
3510                }
3511            }
3512
3513            fn visit<V: Visit>(&self, v: &mut V, key_prefix: &str, _description: &'static str) {
3514                for (column_name, col_options) in self {
3515                    $(
3516                    let key = format!("{}.{field}::{}", key_prefix, column_name, field = stringify!($field_name));
3517                    let desc = concat!($($d),*).trim();
3518                    col_options.$field_name.visit(v, key.as_str(), desc);
3519                    )*
3520                }
3521            }
3522        }
3523    }
3524}
3525
3526config_namespace_with_hashmap! {
3527    /// Options controlling parquet format for individual columns.
3528    ///
3529    /// See [`ParquetOptions`] for more details
3530    pub struct ParquetColumnOptions {
3531        /// Sets if bloom filter is enabled for the column path.
3532        pub bloom_filter_enabled: Option<bool>, default = None
3533
3534        /// Sets encoding for the column path.
3535        /// Valid values are: plain, plain_dictionary, rle,
3536        /// bit_packed, delta_binary_packed, delta_length_byte_array,
3537        /// delta_byte_array, rle_dictionary, byte_stream_split, and alp.
3538        /// These values are not case-sensitive. If NULL, uses
3539        /// default parquet options
3540        pub encoding: Option<String>, default = None
3541
3542        /// Sets if dictionary encoding is enabled for the column path. If NULL, uses
3543        /// default parquet options
3544        pub dictionary_enabled: Option<bool>, default = None
3545
3546        /// Sets default parquet compression codec for the column path.
3547        /// Valid values are: uncompressed, snappy, gzip(level),
3548        /// brotli(level), lz4, zstd(level), and lz4_raw.
3549        /// These values are not case-sensitive. If NULL, uses
3550        /// default parquet options
3551        pub compression: Option<String>, transform = str::to_lowercase, default = None
3552
3553        /// Sets if statistics are enabled for the column
3554        /// Valid values are: "none", "chunk", and "page"
3555        /// These values are not case sensitive. If NULL, uses
3556        /// default parquet options
3557        pub statistics_enabled: Option<String>, default = None
3558
3559        /// Sets bloom filter false positive probability for the column path. If NULL, uses
3560        /// default parquet options
3561        pub bloom_filter_fpp: Option<f64>, default = None
3562
3563        /// Sets bloom filter number of distinct values. If NULL, uses
3564        /// default parquet options
3565        pub bloom_filter_ndv: Option<u64>, default = None
3566    }
3567}
3568
3569#[derive(Clone, Debug, PartialEq)]
3570pub struct ConfigFileEncryptionProperties {
3571    /// Should the parquet footer be encrypted
3572    /// default is true
3573    pub encrypt_footer: bool,
3574    /// Key to use for the parquet footer encoded in hex format
3575    pub footer_key_as_hex: String,
3576    /// Metadata information for footer key
3577    pub footer_key_metadata_as_hex: String,
3578    /// HashMap of column names --> (key in hex format, metadata)
3579    pub column_encryption_properties: HashMap<String, ColumnEncryptionProperties>,
3580    /// AAD prefix string uniquely identifies the file and prevents file swapping
3581    pub aad_prefix_as_hex: String,
3582    /// If true, store the AAD prefix in the file
3583    /// default is false
3584    pub store_aad_prefix: bool,
3585}
3586
3587// Setup to match EncryptionPropertiesBuilder::new()
3588impl Default for ConfigFileEncryptionProperties {
3589    fn default() -> Self {
3590        ConfigFileEncryptionProperties {
3591            encrypt_footer: true,
3592            footer_key_as_hex: String::new(),
3593            footer_key_metadata_as_hex: String::new(),
3594            column_encryption_properties: Default::default(),
3595            aad_prefix_as_hex: String::new(),
3596            store_aad_prefix: false,
3597        }
3598    }
3599}
3600
3601config_namespace_with_hashmap! {
3602    pub struct ColumnEncryptionProperties {
3603        /// Per column encryption key
3604        pub column_key_as_hex: String, default = "".to_string()
3605        /// Per column encryption key metadata
3606        pub column_metadata_as_hex: Option<String>, default = None
3607    }
3608}
3609
3610impl ConfigField for ConfigFileEncryptionProperties {
3611    fn visit<V: Visit>(&self, v: &mut V, key_prefix: &str, _description: &'static str) {
3612        let key = format!("{key_prefix}.encrypt_footer");
3613        let desc = "Encrypt the footer";
3614        self.encrypt_footer.visit(v, key.as_str(), desc);
3615
3616        let key = format!("{key_prefix}.footer_key_as_hex");
3617        let desc = "Key to use for the parquet footer";
3618        self.footer_key_as_hex.visit(v, key.as_str(), desc);
3619
3620        let key = format!("{key_prefix}.footer_key_metadata_as_hex");
3621        let desc = "Metadata to use for the parquet footer";
3622        self.footer_key_metadata_as_hex.visit(v, key.as_str(), desc);
3623
3624        self.column_encryption_properties.visit(v, key_prefix, desc);
3625
3626        let key = format!("{key_prefix}.aad_prefix_as_hex");
3627        let desc = "AAD prefix to use";
3628        self.aad_prefix_as_hex.visit(v, key.as_str(), desc);
3629
3630        let key = format!("{key_prefix}.store_aad_prefix");
3631        let desc = "If true, store the AAD prefix";
3632        self.store_aad_prefix.visit(v, key.as_str(), desc);
3633
3634        self.aad_prefix_as_hex.visit(v, key.as_str(), desc);
3635    }
3636
3637    fn set(&mut self, key: &str, value: &str) -> Result<()> {
3638        // Any hex encoded values must be pre-encoded using
3639        // hex::encode() before calling set.
3640
3641        if key.contains("::") {
3642            // Handle any column specific properties
3643            return self.column_encryption_properties.set(key, value);
3644        }
3645
3646        let (key, rem) = key.split_once('.').unwrap_or((key, ""));
3647        match key {
3648            "encrypt_footer" => self.encrypt_footer.set(rem, value.as_ref()),
3649            "footer_key_as_hex" => self.footer_key_as_hex.set(rem, value.as_ref()),
3650            "footer_key_metadata_as_hex" => {
3651                self.footer_key_metadata_as_hex.set(rem, value.as_ref())
3652            }
3653            "aad_prefix_as_hex" => self.aad_prefix_as_hex.set(rem, value.as_ref()),
3654            "store_aad_prefix" => self.store_aad_prefix.set(rem, value.as_ref()),
3655            _ => _config_err!(
3656                "Config value \"{}\" not found on ConfigFileEncryptionProperties",
3657                key
3658            ),
3659        }
3660    }
3661}
3662
3663#[cfg(feature = "parquet_encryption")]
3664impl TryFrom<ConfigFileEncryptionProperties> for FileEncryptionProperties {
3665    type Error = DataFusionError;
3666
3667    fn try_from(val: ConfigFileEncryptionProperties) -> Result<Self> {
3668        let mut fep = FileEncryptionProperties::builder(
3669            hex::decode(val.footer_key_as_hex)
3670            .map_err(|e| {
3671                DataFusionError::Configuration(format!("Unable to decode hex footer key from ConfigFileEncryptionProperties: {e}"))
3672            })?,
3673        )
3674        .with_plaintext_footer(!val.encrypt_footer)
3675        .with_aad_prefix_storage(val.store_aad_prefix);
3676
3677        if !val.footer_key_metadata_as_hex.is_empty() {
3678            fep = fep.with_footer_key_metadata(
3679                hex::decode(&val.footer_key_metadata_as_hex)
3680                    .map_err(|e| {
3681                        DataFusionError::Configuration(format!("Unable to decode hex footer key metadata from ConfigFileEncryptionProperties: {e}"))
3682                    })?,
3683            );
3684        }
3685
3686        for (column_name, encryption_props) in val.column_encryption_properties.iter() {
3687            let encryption_key = hex::decode(&encryption_props.column_key_as_hex)
3688                .map_err(|e| {
3689                    DataFusionError::Configuration(format!("Unable to decode hex encryption key for column {column_name}: {e}"))
3690                })?;
3691            let key_metadata = encryption_props
3692                .column_metadata_as_hex
3693                .as_ref()
3694                .map(hex::decode)
3695                .transpose()
3696                .map_err(|e| {
3697                    DataFusionError::Configuration(format!("Unable to decode hex column metadata for column {column_name}: {e}"))
3698                })?;
3699
3700            match key_metadata {
3701                Some(key_metadata) => {
3702                    fep = fep.with_column_key_and_metadata(
3703                        column_name,
3704                        encryption_key,
3705                        key_metadata,
3706                    );
3707                }
3708                None => {
3709                    fep = fep.with_column_key(column_name, encryption_key);
3710                }
3711            }
3712        }
3713
3714        if !val.aad_prefix_as_hex.is_empty() {
3715            let aad_prefix: Vec<u8> = hex::decode(&val.aad_prefix_as_hex).map_err(|e| {
3716                DataFusionError::Configuration(format!(
3717                    "Unable to decode hex AAD prefix from ConfigFileEncryptionProperties: {e}"
3718                ))
3719            })?;
3720            fep = fep.with_aad_prefix(aad_prefix);
3721        }
3722        Ok(Arc::unwrap_or_clone(fep.build().map_err(|e| {
3723            DataFusionError::Configuration(format!(
3724                "Could not build FileEncryptionProperties: {e}"
3725            ))
3726        })?))
3727    }
3728}
3729
3730#[cfg(feature = "parquet_encryption")]
3731impl From<&Arc<FileEncryptionProperties>> for ConfigFileEncryptionProperties {
3732    fn from(f: &Arc<FileEncryptionProperties>) -> Self {
3733        let (column_names_vec, column_keys_vec, column_metas_vec) = f.column_keys();
3734
3735        let mut column_encryption_properties: HashMap<
3736            String,
3737            ColumnEncryptionProperties,
3738        > = HashMap::with_capacity(column_names_vec.len());
3739
3740        for (i, column_name) in column_names_vec.iter().enumerate() {
3741            let column_key_as_hex = hex::encode(&column_keys_vec[i]);
3742            let column_metadata_as_hex: Option<String> =
3743                column_metas_vec.get(i).map(hex::encode);
3744            column_encryption_properties.insert(
3745                column_name.clone(),
3746                ColumnEncryptionProperties {
3747                    column_key_as_hex,
3748                    column_metadata_as_hex,
3749                },
3750            );
3751        }
3752        let aad_prefix = f.aad_prefix().cloned().unwrap_or_default();
3753        ConfigFileEncryptionProperties {
3754            encrypt_footer: f.encrypt_footer(),
3755            footer_key_as_hex: hex::encode(f.footer_key()),
3756            footer_key_metadata_as_hex: f
3757                .footer_key_metadata()
3758                .map(hex::encode)
3759                .unwrap_or_default(),
3760            column_encryption_properties,
3761            aad_prefix_as_hex: hex::encode(aad_prefix),
3762            store_aad_prefix: f.store_aad_prefix(),
3763        }
3764    }
3765}
3766
3767#[derive(Clone, Debug, PartialEq)]
3768pub struct ConfigFileDecryptionProperties {
3769    /// Binary string to use for the parquet footer encoded in hex format
3770    pub footer_key_as_hex: String,
3771    /// HashMap of column names --> key in hex format
3772    pub column_decryption_properties: HashMap<String, ColumnDecryptionProperties>,
3773    /// AAD prefix string uniquely identifies the file and prevents file swapping
3774    pub aad_prefix_as_hex: String,
3775    /// If true, then verify signature for files with plaintext footers.
3776    /// default = true
3777    pub footer_signature_verification: bool,
3778}
3779
3780config_namespace_with_hashmap! {
3781    pub struct ColumnDecryptionProperties {
3782        /// Per column encryption key
3783        pub column_key_as_hex: String, default = "".to_string()
3784    }
3785}
3786
3787// Setup to match DecryptionPropertiesBuilder::new()
3788impl Default for ConfigFileDecryptionProperties {
3789    fn default() -> Self {
3790        ConfigFileDecryptionProperties {
3791            footer_key_as_hex: String::new(),
3792            column_decryption_properties: Default::default(),
3793            aad_prefix_as_hex: String::new(),
3794            footer_signature_verification: true,
3795        }
3796    }
3797}
3798
3799impl ConfigField for ConfigFileDecryptionProperties {
3800    fn visit<V: Visit>(&self, v: &mut V, key_prefix: &str, _description: &'static str) {
3801        let key = format!("{key_prefix}.footer_key_as_hex");
3802        let desc = "Key to use for the parquet footer";
3803        self.footer_key_as_hex.visit(v, key.as_str(), desc);
3804
3805        let key = format!("{key_prefix}.aad_prefix_as_hex");
3806        let desc = "AAD prefix to use";
3807        self.aad_prefix_as_hex.visit(v, key.as_str(), desc);
3808
3809        let key = format!("{key_prefix}.footer_signature_verification");
3810        let desc = "If true, verify the footer signature";
3811        self.footer_signature_verification
3812            .visit(v, key.as_str(), desc);
3813
3814        self.column_decryption_properties.visit(v, key_prefix, desc);
3815    }
3816
3817    fn set(&mut self, key: &str, value: &str) -> Result<()> {
3818        // Any hex encoded values must be pre-encoded using
3819        // hex::encode() before calling set.
3820
3821        if key.contains("::") {
3822            // Handle any column specific properties
3823            return self.column_decryption_properties.set(key, value);
3824        }
3825
3826        let (key, rem) = key.split_once('.').unwrap_or((key, ""));
3827        match key {
3828            "footer_key_as_hex" => self.footer_key_as_hex.set(rem, value.as_ref()),
3829            "aad_prefix_as_hex" => self.aad_prefix_as_hex.set(rem, value.as_ref()),
3830            "footer_signature_verification" => {
3831                self.footer_signature_verification.set(rem, value.as_ref())
3832            }
3833            _ => _config_err!(
3834                "Config value \"{}\" not found on ConfigFileDecryptionProperties",
3835                key
3836            ),
3837        }
3838    }
3839}
3840
3841#[cfg(feature = "parquet_encryption")]
3842impl TryFrom<ConfigFileDecryptionProperties> for FileDecryptionProperties {
3843    type Error = DataFusionError;
3844
3845    fn try_from(val: ConfigFileDecryptionProperties) -> Result<Self> {
3846        let num_columns = val.column_decryption_properties.len();
3847        let mut column_names: Vec<&str> = Vec::with_capacity(num_columns);
3848        let mut column_keys: Vec<Vec<u8>> = Vec::with_capacity(num_columns);
3849
3850        for (col_name, decryption_properties) in val.column_decryption_properties.iter() {
3851            let column_key = hex::decode(&decryption_properties.column_key_as_hex).map_err(|e| {
3852                        DataFusionError::Configuration(format!
3853                            ("Could not decode hex column key from ConfigFileDecryptionProperties for column name {col_name}: {e}."))
3854                    })?;
3855            column_names.push(col_name.as_str());
3856            column_keys.push(column_key);
3857        }
3858
3859        let footer_key = hex::decode(val.footer_key_as_hex).map_err(|e| {
3860            DataFusionError::Configuration(format!(
3861                "Could not decode hex footer key from ConfigFileDecryptionProperties: {e}."
3862            ))
3863        })?;
3864
3865        let mut fep = FileDecryptionProperties::builder(footer_key)
3866            .with_column_keys(column_names, column_keys)
3867            .map_err(|e| {
3868                DataFusionError::Configuration(format!(
3869                    "Could not set column keys on FileDecryptionPropertiesBuilder: {e}."
3870                ))
3871            })?;
3872
3873        if !val.footer_signature_verification {
3874            fep = fep.disable_footer_signature_verification();
3875        }
3876
3877        if !val.aad_prefix_as_hex.is_empty() {
3878            let aad_prefix = hex::decode(&val.aad_prefix_as_hex).map_err(|e| {
3879                DataFusionError::Configuration(format!(
3880                    "Could not decode hex AAD prefix from ConfigFileDecryptionProperties: {e}."
3881                ))
3882            })?;
3883            fep = fep.with_aad_prefix(aad_prefix);
3884        }
3885
3886        Ok(Arc::unwrap_or_clone(fep.build().map_err(|e| {
3887            DataFusionError::Configuration(format!(
3888                "Could not build FileDecryptionProperties: {e}."
3889            ))
3890        })?))
3891    }
3892}
3893
3894#[cfg(feature = "parquet_encryption")]
3895impl TryFrom<&Arc<FileDecryptionProperties>> for ConfigFileDecryptionProperties {
3896    type Error = DataFusionError;
3897
3898    fn try_from(f: &Arc<FileDecryptionProperties>) -> Result<Self> {
3899        if f.uses_key_retriever() {
3900            // Getting the keys is not possible without the key metadata from
3901            // a Parquet file if a key retriever is used.
3902            return Err(
3903                DataFusionError::Configuration(
3904                    "Cannot convert FileDecryptionProperties that use a key retriever to ConfigFileDecryptionProperties".into()
3905                )
3906            );
3907        }
3908
3909        let footer_key = f.footer_key(None).map_err(|e| {
3910            // This shouldn't happen for FileDecryptionProperties that don't use a key retriever.
3911            DataFusionError::Configuration(format!(
3912                "Could not retrieve footer key from FileDecryptionProperties: {e}"
3913            ))
3914        })?;
3915
3916        let (column_names_vec, column_keys_vec) = f.column_keys();
3917        let mut column_decryption_properties: HashMap<
3918            String,
3919            ColumnDecryptionProperties,
3920        > = HashMap::with_capacity(column_names_vec.len());
3921        for (i, column_name) in column_names_vec.iter().enumerate() {
3922            let props = ColumnDecryptionProperties {
3923                column_key_as_hex: hex::encode(column_keys_vec[i].clone()),
3924            };
3925            column_decryption_properties.insert(column_name.clone(), props);
3926        }
3927
3928        let aad_prefix = f.aad_prefix().cloned().unwrap_or_default();
3929        Ok(ConfigFileDecryptionProperties {
3930            footer_key_as_hex: hex::encode(footer_key.as_ref()),
3931            column_decryption_properties,
3932            aad_prefix_as_hex: hex::encode(aad_prefix),
3933            footer_signature_verification: f.check_plaintext_footer_integrity(),
3934        })
3935    }
3936}
3937
3938/// Holds implementation-specific options for an encryption factory
3939#[derive(Clone, Debug, Default, PartialEq)]
3940pub struct EncryptionFactoryOptions {
3941    pub options: HashMap<String, String>,
3942}
3943
3944impl ConfigField for EncryptionFactoryOptions {
3945    fn visit<V: Visit>(&self, v: &mut V, key: &str, _description: &'static str) {
3946        for (option_key, option_value) in &self.options {
3947            v.some(
3948                &format!("{key}.{option_key}"),
3949                option_value,
3950                "Encryption factory specific option",
3951            );
3952        }
3953    }
3954
3955    fn set(&mut self, key: &str, value: &str) -> Result<()> {
3956        self.options.insert(key.to_owned(), value.to_owned());
3957        Ok(())
3958    }
3959}
3960
3961impl EncryptionFactoryOptions {
3962    /// Convert these encryption factory options to an [`ExtensionOptions`] instance.
3963    pub fn to_extension_options<T: ExtensionOptions + Default>(&self) -> Result<T> {
3964        let mut options = T::default();
3965        for (key, value) in &self.options {
3966            options.set(key, value)?;
3967        }
3968        Ok(options)
3969    }
3970}
3971
3972/// Compression codec used for the record batch bodies of Arrow IPC files.
3973#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3974pub enum ArrowIpcCompression {
3975    /// No compression
3976    Uncompressed,
3977    /// LZ4 (frame format)
3978    Lz4Frame,
3979    /// Zstd
3980    Zstd,
3981}
3982
3983impl FromStr for ArrowIpcCompression {
3984    type Err = DataFusionError;
3985
3986    fn from_str(s: &str) -> Result<Self, Self::Err> {
3987        match s.replace('\'', "").to_ascii_lowercase().as_str() {
3988            "uncompressed" | "" => Ok(Self::Uncompressed),
3989            "lz4_frame" => Ok(Self::Lz4Frame),
3990            "zstd" => Ok(Self::Zstd),
3991            other => Err(DataFusionError::Configuration(format!(
3992                "Invalid Arrow IPC compression type: {other}. \
3993                Expected one of: uncompressed, lz4_frame, zstd"
3994            ))),
3995        }
3996    }
3997}
3998
3999impl Display for ArrowIpcCompression {
4000    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4001        let str = match self {
4002            Self::Uncompressed => "uncompressed",
4003            Self::Lz4Frame => "lz4_frame",
4004            Self::Zstd => "zstd",
4005        };
4006        write!(f, "{str}")
4007    }
4008}
4009
4010impl ConfigField for ArrowIpcCompression {
4011    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
4012        v.some(key, self, description)
4013    }
4014
4015    fn set(&mut self, _: &str, value: &str) -> Result<()> {
4016        *self = ArrowIpcCompression::from_str(value)?;
4017        Ok(())
4018    }
4019}
4020
4021impl From<ArrowIpcCompression> for Option<CompressionType> {
4022    fn from(c: ArrowIpcCompression) -> Self {
4023        match c {
4024            ArrowIpcCompression::Uncompressed => None,
4025            ArrowIpcCompression::Lz4Frame => Some(CompressionType::LZ4_FRAME),
4026            ArrowIpcCompression::Zstd => Some(CompressionType::ZSTD),
4027        }
4028    }
4029}
4030
4031config_namespace! {
4032    /// Options controlling Arrow IPC format
4033    pub struct ArrowOptions {
4034        /// Compression codec used for the record batch bodies of Arrow IPC files.
4035        /// One of: "uncompressed", "lz4_frame", "zstd"
4036        pub compression: ArrowIpcCompression, default = ArrowIpcCompression::Lz4Frame
4037        /// Compression level to use with the "zstd" codec. Not supported by "lz4_frame"
4038        /// or "uncompressed". If not specified, the default zstd compression level is used.
4039        pub compression_level: Option<i32>, default = None
4040        /// Byte alignment to pad buffers to when writing Arrow IPC files.
4041        /// Must be one of 8, 16, 32, or 64.
4042        pub alignment: usize, default = 64
4043    }
4044}
4045
4046config_namespace! {
4047    /// Options controlling CSV format
4048    pub struct CsvOptions {
4049        /// Specifies whether there is a CSV header (i.e. the first line
4050        /// consists of is column names). The value `None` indicates that
4051        /// the configuration should be consulted.
4052        pub has_header: Option<bool>, default = None
4053        pub delimiter: u8, default = b','
4054        pub quote: u8, default = b'"'
4055        pub terminator: Option<u8>, default = None
4056        pub escape: Option<u8>, default = None
4057        pub double_quote: Option<bool>, default = None
4058        /// Quote style for CSV writing.
4059        /// One of: "Always", "Necessary", "NonNumeric", "Never"
4060        pub quote_style: CsvQuoteStyle, default = CsvQuoteStyle::Necessary
4061        /// Whether to ignore leading whitespace in string values when writing CSV.
4062        /// Defaults to `false` when `None`.
4063        pub ignore_leading_whitespace: Option<bool>, default = None
4064        /// Whether to ignore trailing whitespace in string values when writing CSV.
4065        /// Defaults to `false` when `None`.
4066        pub ignore_trailing_whitespace: Option<bool>, default = None
4067        /// Specifies whether newlines in (quoted) values are supported.
4068        ///
4069        /// Parsing newlines in quoted values may be affected by execution behaviour such as
4070        /// parallel file scanning. Setting this to `true` ensures that newlines in values are
4071        /// parsed successfully, which may reduce performance.
4072        ///
4073        /// The default behaviour depends on the `datafusion.catalog.newlines_in_values` setting.
4074        pub newlines_in_values: Option<bool>, default = None
4075        pub compression: CompressionTypeVariant, default = CompressionTypeVariant::UNCOMPRESSED
4076        /// Compression level for the output file. The valid range depends on the
4077        /// compression algorithm:
4078        /// - ZSTD: 1 to 22 (default: 3)
4079        /// - GZIP: 0 to 9 (default: 6)
4080        /// - BZIP2: 0 to 9 (default: 6)
4081        /// - XZ: 0 to 9 (default: 6)
4082        /// If not specified, the default level for the compression algorithm is used.
4083        pub compression_level: Option<u32>, default = None
4084        pub schema_infer_max_rec: Option<usize>, default = None
4085        pub date_format: Option<String>, default = None
4086        pub datetime_format: Option<String>, default = None
4087        pub timestamp_format: Option<String>, default = None
4088        pub timestamp_tz_format: Option<String>, default = None
4089        pub time_format: Option<String>, default = None
4090        // The output format for Nulls in the CSV writer.
4091        pub null_value: Option<String>, default = None
4092        // The input regex for Nulls when loading CSVs.
4093        pub null_regex: Option<String>, default = None
4094        pub comment: Option<u8>, default = None
4095        /// Whether to allow truncated rows when parsing, both within a single file and across files.
4096        ///
4097        /// When set to false (default), reading a single CSV file which has rows of different lengths will
4098        /// error; if reading multiple CSV files with different number of columns, it will also fail.
4099        ///
4100        /// When set to true, reading a single CSV file with rows of different lengths will pad the truncated
4101        /// rows with null values for the missing columns; if reading multiple CSV files with different number
4102        /// of columns, it creates a union schema containing all columns found across the files, and will
4103        /// pad any files missing columns with null values for their rows.
4104        pub truncated_rows: Option<bool>, default = None
4105    }
4106}
4107
4108impl CsvOptions {
4109    /// Set a limit in terms of records to scan to infer the schema
4110    /// - default to `DEFAULT_SCHEMA_INFER_MAX_RECORD`
4111    pub fn with_compression(
4112        mut self,
4113        compression_type_variant: CompressionTypeVariant,
4114    ) -> Self {
4115        self.compression = compression_type_variant;
4116        self
4117    }
4118
4119    /// Set a limit in terms of records to scan to infer the schema
4120    /// - default to `DEFAULT_SCHEMA_INFER_MAX_RECORD`
4121    pub fn with_schema_infer_max_rec(mut self, max_rec: usize) -> Self {
4122        self.schema_infer_max_rec = Some(max_rec);
4123        self
4124    }
4125
4126    /// Set true to indicate that the first line is a header.
4127    /// - default to true
4128    pub fn with_has_header(mut self, has_header: bool) -> Self {
4129        self.has_header = Some(has_header);
4130        self
4131    }
4132
4133    /// Returns true if the first line is a header. If format options does not
4134    /// specify whether there is a header, returns `None` (indicating that the
4135    /// configuration should be consulted).
4136    pub fn has_header(&self) -> Option<bool> {
4137        self.has_header
4138    }
4139
4140    /// The character separating values within a row.
4141    /// - default to ','
4142    pub fn with_delimiter(mut self, delimiter: u8) -> Self {
4143        self.delimiter = delimiter;
4144        self
4145    }
4146
4147    /// The quote character in a row.
4148    /// - default to '"'
4149    pub fn with_quote(mut self, quote: u8) -> Self {
4150        self.quote = quote;
4151        self
4152    }
4153
4154    /// The character that terminates a row.
4155    /// - default to None (CRLF)
4156    pub fn with_terminator(mut self, terminator: Option<u8>) -> Self {
4157        self.terminator = terminator;
4158        self
4159    }
4160
4161    /// The escape character in a row.
4162    /// - default is None
4163    pub fn with_escape(mut self, escape: Option<u8>) -> Self {
4164        self.escape = escape;
4165        self
4166    }
4167
4168    /// Set true to indicate that the CSV quotes should be doubled.
4169    /// - default to true
4170    pub fn with_double_quote(mut self, double_quote: bool) -> Self {
4171        self.double_quote = Some(double_quote);
4172        self
4173    }
4174
4175    /// Set the quote style for CSV writing.
4176    pub fn with_quote_style(mut self, quote_style: CsvQuoteStyle) -> Self {
4177        self.quote_style = quote_style;
4178        self
4179    }
4180
4181    /// Set whether to ignore leading whitespace in string values when writing CSV.
4182    pub fn with_ignore_leading_whitespace(
4183        mut self,
4184        ignore_leading_whitespace: bool,
4185    ) -> Self {
4186        self.ignore_leading_whitespace = Some(ignore_leading_whitespace);
4187        self
4188    }
4189
4190    /// Set whether to ignore trailing whitespace in string values when writing CSV.
4191    pub fn with_ignore_trailing_whitespace(
4192        mut self,
4193        ignore_trailing_whitespace: bool,
4194    ) -> Self {
4195        self.ignore_trailing_whitespace = Some(ignore_trailing_whitespace);
4196        self
4197    }
4198
4199    /// Specifies whether newlines in (quoted) values are supported.
4200    ///
4201    /// Parsing newlines in quoted values may be affected by execution behaviour such as
4202    /// parallel file scanning. Setting this to `true` ensures that newlines in values are
4203    /// parsed successfully, which may reduce performance.
4204    ///
4205    /// The default behaviour depends on the `datafusion.catalog.newlines_in_values` setting.
4206    pub fn with_newlines_in_values(mut self, newlines_in_values: bool) -> Self {
4207        self.newlines_in_values = Some(newlines_in_values);
4208        self
4209    }
4210
4211    /// Set a `CompressionTypeVariant` of CSV
4212    /// - defaults to `CompressionTypeVariant::UNCOMPRESSED`
4213    pub fn with_file_compression_type(
4214        mut self,
4215        compression: CompressionTypeVariant,
4216    ) -> Self {
4217        self.compression = compression;
4218        self
4219    }
4220
4221    /// Whether to allow truncated rows when parsing.
4222    /// By default this is set to false and will error if the CSV rows have different lengths.
4223    /// When set to true then it will allow records with less than the expected number of columns and fill the missing columns with nulls.
4224    /// If the record’s schema is not nullable, then it will still return an error.
4225    pub fn with_truncated_rows(mut self, allow: bool) -> Self {
4226        self.truncated_rows = Some(allow);
4227        self
4228    }
4229
4230    /// Set the compression level for the output file.
4231    /// The valid range depends on the compression algorithm.
4232    /// If not specified, the default level for the algorithm is used.
4233    pub fn with_compression_level(mut self, level: u32) -> Self {
4234        self.compression_level = Some(level);
4235        self
4236    }
4237
4238    /// The delimiter character.
4239    pub fn delimiter(&self) -> u8 {
4240        self.delimiter
4241    }
4242
4243    /// The quote character.
4244    pub fn quote(&self) -> u8 {
4245        self.quote
4246    }
4247
4248    /// The terminator character.
4249    pub fn terminator(&self) -> Option<u8> {
4250        self.terminator
4251    }
4252
4253    /// The escape character.
4254    pub fn escape(&self) -> Option<u8> {
4255        self.escape
4256    }
4257}
4258
4259config_namespace! {
4260    /// Options controlling JSON format
4261    pub struct JsonOptions {
4262        pub compression: CompressionTypeVariant, default = CompressionTypeVariant::UNCOMPRESSED
4263        /// Compression level for the output file. The valid range depends on the
4264        /// compression algorithm:
4265        /// - ZSTD: 1 to 22 (default: 3)
4266        /// - GZIP: 0 to 9 (default: 6)
4267        /// - BZIP2: 0 to 9 (default: 6)
4268        /// - XZ: 0 to 9 (default: 6)
4269        /// If not specified, the default level for the compression algorithm is used.
4270        pub compression_level: Option<u32>, default = None
4271        pub schema_infer_max_rec: Option<usize>, default = None
4272       /// The JSON format to use when reading files.
4273       ///
4274       /// When `true` (default), expects newline-delimited JSON (NDJSON):
4275       /// ```text
4276       /// {"key1": 1, "key2": "val"}
4277       /// {"key1": 2, "key2": "vals"}
4278       /// ```
4279       ///
4280       /// When `false`, expects JSON array format:
4281       /// ```text
4282       /// [
4283       ///   {"key1": 1, "key2": "val"},
4284       ///   {"key1": 2, "key2": "vals"}
4285       /// ]
4286       /// ```
4287       pub newline_delimited: bool, default = true
4288    }
4289}
4290
4291pub trait OutputFormatExt: Display {}
4292
4293#[derive(Debug, Clone, PartialEq)]
4294#[cfg_attr(feature = "parquet", expect(clippy::large_enum_variant))]
4295pub enum OutputFormat {
4296    CSV(CsvOptions),
4297    JSON(JsonOptions),
4298    #[cfg(feature = "parquet")]
4299    PARQUET(TableParquetOptions),
4300    AVRO,
4301    ARROW(ArrowOptions),
4302}
4303
4304impl Display for OutputFormat {
4305    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4306        let out = match self {
4307            OutputFormat::CSV(_) => "csv",
4308            OutputFormat::JSON(_) => "json",
4309            #[cfg(feature = "parquet")]
4310            OutputFormat::PARQUET(_) => "parquet",
4311            OutputFormat::AVRO => "avro",
4312            OutputFormat::ARROW(_) => "arrow",
4313        };
4314        write!(f, "{out}")
4315    }
4316}
4317
4318#[cfg(test)]
4319mod tests {
4320    use crate::assert_contains;
4321    #[cfg(feature = "parquet")]
4322    use crate::config::TableParquetOptions;
4323    use crate::config::{
4324        ConfigEntry, ConfigExtension, ConfigField, ConfigFileType, ExtensionOptions,
4325        Extensions, TableOptions,
4326    };
4327
4328    #[test]
4329    fn invalid_temporal_format_is_rejected_before_rendering() {
4330        use crate::config::FormatOptions;
4331
4332        let invalid_options = [
4333            (
4334                "date_format",
4335                FormatOptions {
4336                    date_format: Some("%".to_owned()),
4337                    ..Default::default()
4338                },
4339            ),
4340            (
4341                "datetime_format",
4342                FormatOptions {
4343                    datetime_format: Some("%".to_owned()),
4344                    ..Default::default()
4345                },
4346            ),
4347            (
4348                "timestamp_format",
4349                FormatOptions {
4350                    timestamp_format: Some("%".to_owned()),
4351                    ..Default::default()
4352                },
4353            ),
4354            (
4355                "timestamp_tz_format",
4356                FormatOptions {
4357                    timestamp_tz_format: Some("%".to_owned()),
4358                    ..Default::default()
4359                },
4360            ),
4361            (
4362                "time_format",
4363                FormatOptions {
4364                    time_format: Some("%".to_owned()),
4365                    ..Default::default()
4366                },
4367            ),
4368        ];
4369
4370        for (name, options) in invalid_options {
4371            let error = arrow::util::display::FormatOptions::try_from(&options)
4372                .expect_err("invalid format strings must be rejected before rendering");
4373            assert!(
4374                error
4375                    .to_string()
4376                    .contains(&format!("datafusion.format.{name}")),
4377                "unexpected validation error: {error}"
4378            );
4379        }
4380
4381        let incompatible_options = [
4382            (
4383                "time_format",
4384                FormatOptions {
4385                    time_format: Some("%Y".to_owned()),
4386                    ..Default::default()
4387                },
4388            ),
4389            (
4390                "date_format",
4391                FormatOptions {
4392                    date_format: Some("%H".to_owned()),
4393                    ..Default::default()
4394                },
4395            ),
4396            (
4397                "timestamp_format",
4398                FormatOptions {
4399                    timestamp_format: Some("%+".to_owned()),
4400                    ..Default::default()
4401                },
4402            ),
4403        ];
4404
4405        for (name, options) in incompatible_options {
4406            let error = arrow::util::display::FormatOptions::try_from(&options)
4407                .expect_err(
4408                    "type-incompatible formats must be rejected before rendering",
4409                );
4410            assert!(
4411                error
4412                    .to_string()
4413                    .contains(&format!("datafusion.format.{name}")),
4414                "unexpected validation error: {error}"
4415            );
4416        }
4417
4418        arrow::util::display::FormatOptions::try_from(&FormatOptions::default())
4419            .expect("the default temporal formats must remain valid");
4420
4421        let options = FormatOptions {
4422            timestamp_tz_format: Some("%+".to_owned()),
4423            ..Default::default()
4424        };
4425        let options: arrow::util::display::FormatOptions = (&options)
4426            .try_into()
4427            .expect("the timezone-aware ISO 8601 format must be valid");
4428        let schema = arrow::datatypes::Schema::new(vec![arrow::datatypes::Field::new(
4429            "timestamp",
4430            arrow::datatypes::DataType::Timestamp(
4431                arrow::datatypes::TimeUnit::Nanosecond,
4432                Some("UTC".into()),
4433            ),
4434            false,
4435        )]);
4436        let batch = arrow::record_batch::RecordBatch::try_new(
4437            std::sync::Arc::new(schema),
4438            vec![std::sync::Arc::new(
4439                arrow::array::TimestampNanosecondArray::from(vec![0])
4440                    .with_timezone("UTC"),
4441            )],
4442        )
4443        .expect("valid timestamp batch");
4444        let formatted =
4445            arrow::util::pretty::pretty_format_batches_with_options(&[batch], &options)
4446                .expect("valid timezone-aware format must render")
4447                .to_string();
4448        assert!(
4449            formatted.contains("1970-01-01T00:00:00+00:00"),
4450            "unexpected formatted output: {formatted}"
4451        );
4452    }
4453    use std::any::Any;
4454    use std::collections::HashMap;
4455
4456    #[derive(Default, Debug, Clone)]
4457    pub struct TestExtensionConfig {
4458        /// Should "foo" be replaced by "bar"?
4459        pub properties: HashMap<String, String>,
4460    }
4461
4462    impl ExtensionOptions for TestExtensionConfig {
4463        fn as_any(&self) -> &dyn Any {
4464            self
4465        }
4466
4467        fn as_any_mut(&mut self) -> &mut dyn Any {
4468            self
4469        }
4470
4471        fn cloned(&self) -> Box<dyn ExtensionOptions> {
4472            Box::new(self.clone())
4473        }
4474
4475        fn set(&mut self, key: &str, value: &str) -> crate::Result<()> {
4476            let (key, rem) = key.split_once('.').unwrap_or((key, ""));
4477            assert_eq!(key, "test");
4478            self.properties.insert(rem.to_owned(), value.to_owned());
4479            Ok(())
4480        }
4481
4482        fn entries(&self) -> Vec<ConfigEntry> {
4483            self.properties
4484                .iter()
4485                .map(|(k, v)| ConfigEntry {
4486                    key: k.into(),
4487                    value: Some(v.into()),
4488                    description: "",
4489                })
4490                .collect()
4491        }
4492    }
4493
4494    impl ConfigExtension for TestExtensionConfig {
4495        const PREFIX: &'static str = "test";
4496    }
4497
4498    #[test]
4499    fn create_table_config() {
4500        let mut extension = Extensions::new();
4501        extension.insert(TestExtensionConfig::default());
4502        let table_config = TableOptions::new().with_extensions(extension);
4503        let kafka_config = table_config.extensions.get::<TestExtensionConfig>();
4504        assert!(kafka_config.is_some())
4505    }
4506
4507    #[test]
4508    fn alter_test_extension_config() {
4509        let mut extension = Extensions::new();
4510        extension.insert(TestExtensionConfig::default());
4511        let mut table_config = TableOptions::new().with_extensions(extension);
4512        table_config.set_config_format(ConfigFileType::CSV);
4513        table_config.set("format.delimiter", ";").unwrap();
4514        assert_eq!(table_config.csv.delimiter, b';');
4515        table_config.set("test.bootstrap.servers", "asd").unwrap();
4516        let kafka_config = table_config
4517            .extensions
4518            .get::<TestExtensionConfig>()
4519            .unwrap();
4520        assert_eq!(
4521            kafka_config.properties.get("bootstrap.servers").unwrap(),
4522            "asd"
4523        );
4524    }
4525
4526    #[test]
4527    fn iter_test_extension_config() {
4528        let mut extension = Extensions::new();
4529        extension.insert(TestExtensionConfig::default());
4530        let table_config = TableOptions::new().with_extensions(extension);
4531        let extensions = table_config.extensions.iter().collect::<Vec<_>>();
4532        assert_eq!(extensions.len(), 1);
4533        assert_eq!(extensions[0].0, TestExtensionConfig::PREFIX);
4534    }
4535
4536    #[test]
4537    fn csv_u8_table_options() {
4538        let mut table_config = TableOptions::new();
4539        table_config.set_config_format(ConfigFileType::CSV);
4540        table_config.set("format.delimiter", ";").unwrap();
4541        assert_eq!(table_config.csv.delimiter as char, ';');
4542        table_config.set("format.escape", "\"").unwrap();
4543        assert_eq!(table_config.csv.escape.unwrap() as char, '"');
4544        table_config.set("format.escape", "\'").unwrap();
4545        assert_eq!(table_config.csv.escape.unwrap() as char, '\'');
4546    }
4547
4548    #[test]
4549    fn warning_only_not_default() {
4550        use std::sync::atomic::AtomicUsize;
4551        static COUNT: AtomicUsize = AtomicUsize::new(0);
4552        use log::{Level, LevelFilter, Metadata, Record};
4553        struct SimpleLogger;
4554        impl log::Log for SimpleLogger {
4555            fn enabled(&self, metadata: &Metadata) -> bool {
4556                metadata.level() <= Level::Info
4557            }
4558
4559            fn log(&self, record: &Record) {
4560                if self.enabled(record.metadata()) {
4561                    COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4562                }
4563            }
4564            fn flush(&self) {}
4565        }
4566        log::set_logger(&SimpleLogger).unwrap();
4567        log::set_max_level(LevelFilter::Info);
4568        let mut sql_parser_options = crate::config::SqlParserOptions::default();
4569        sql_parser_options
4570            .set("enable_options_value_normalization", "false")
4571            .unwrap();
4572        assert_eq!(COUNT.load(std::sync::atomic::Ordering::Relaxed), 0);
4573        sql_parser_options
4574            .set("enable_options_value_normalization", "true")
4575            .unwrap();
4576        assert_eq!(COUNT.load(std::sync::atomic::Ordering::Relaxed), 1);
4577    }
4578
4579    #[test]
4580    fn reset_nested_scalar_reports_helpful_error() {
4581        let mut value = true;
4582        let err = <bool as ConfigField>::reset(&mut value, "nested").unwrap_err();
4583        let message = err.to_string();
4584        assert!(
4585            message.starts_with(
4586                "Invalid or Unsupported Configuration: Config field is a scalar bool and does not have nested field \"nested\""
4587            ),
4588            "unexpected error message: {message}"
4589        );
4590    }
4591
4592    #[cfg(feature = "parquet")]
4593    #[test]
4594    fn parquet_table_options() {
4595        let mut table_config = TableOptions::new();
4596        table_config.set_config_format(ConfigFileType::PARQUET);
4597        table_config
4598            .set("format.bloom_filter_enabled::col1", "true")
4599            .unwrap();
4600        assert_eq!(
4601            table_config.parquet.column_specific_options["col1"].bloom_filter_enabled,
4602            Some(true)
4603        );
4604    }
4605
4606    #[cfg(feature = "parquet_encryption")]
4607    #[test]
4608    fn parquet_table_encryption() {
4609        use crate::config::{
4610            ConfigFileDecryptionProperties, ConfigFileEncryptionProperties,
4611        };
4612        use parquet::encryption::decrypt::FileDecryptionProperties;
4613        use parquet::encryption::encrypt::FileEncryptionProperties;
4614        use std::sync::Arc;
4615
4616        let footer_key = b"0123456789012345".to_vec(); // 128bit/16
4617        let column_names = vec!["double_field", "float_field"];
4618        let column_keys =
4619            vec![b"1234567890123450".to_vec(), b"1234567890123451".to_vec()];
4620
4621        let file_encryption_properties =
4622            FileEncryptionProperties::builder(footer_key.clone())
4623                .with_column_keys(column_names.clone(), column_keys.clone())
4624                .unwrap()
4625                .build()
4626                .unwrap();
4627
4628        let decryption_properties = FileDecryptionProperties::builder(footer_key.clone())
4629            .with_column_keys(column_names.clone(), column_keys.clone())
4630            .unwrap()
4631            .build()
4632            .unwrap();
4633
4634        // Test round-trip
4635        let config_encrypt =
4636            ConfigFileEncryptionProperties::from(&file_encryption_properties);
4637        let encryption_properties_built =
4638            Arc::new(FileEncryptionProperties::try_from(config_encrypt.clone()).unwrap());
4639        assert_eq!(file_encryption_properties, encryption_properties_built);
4640
4641        let config_decrypt =
4642            ConfigFileDecryptionProperties::try_from(&decryption_properties).unwrap();
4643        let decryption_properties_built =
4644            Arc::new(FileDecryptionProperties::try_from(config_decrypt.clone()).unwrap());
4645        assert_eq!(decryption_properties, decryption_properties_built);
4646
4647        ///////////////////////////////////////////////////////////////////////////////////
4648        // Test encryption config
4649
4650        // Display original encryption config
4651        // println!("{:#?}", config_encrypt);
4652
4653        let mut table_config = TableOptions::new();
4654        table_config.set_config_format(ConfigFileType::PARQUET);
4655        table_config
4656            .parquet
4657            .set(
4658                "crypto.file_encryption.encrypt_footer",
4659                config_encrypt.encrypt_footer.to_string().as_str(),
4660            )
4661            .unwrap();
4662        table_config
4663            .parquet
4664            .set(
4665                "crypto.file_encryption.footer_key_as_hex",
4666                config_encrypt.footer_key_as_hex.as_str(),
4667            )
4668            .unwrap();
4669
4670        for (i, col_name) in column_names.iter().enumerate() {
4671            let key = format!("crypto.file_encryption.column_key_as_hex::{col_name}");
4672            let value = hex::encode(column_keys[i].clone());
4673            table_config
4674                .parquet
4675                .set(key.as_str(), value.as_str())
4676                .unwrap();
4677        }
4678
4679        // Print matching final encryption config
4680        // println!("{:#?}", table_config.parquet.crypto.file_encryption);
4681
4682        assert_eq!(
4683            table_config.parquet.crypto.file_encryption,
4684            Some(config_encrypt)
4685        );
4686
4687        ///////////////////////////////////////////////////////////////////////////////////
4688        // Test decryption config
4689
4690        // Display original decryption config
4691        // println!("{:#?}", config_decrypt);
4692
4693        let mut table_config = TableOptions::new();
4694        table_config.set_config_format(ConfigFileType::PARQUET);
4695        table_config
4696            .parquet
4697            .set(
4698                "crypto.file_decryption.footer_key_as_hex",
4699                config_decrypt.footer_key_as_hex.as_str(),
4700            )
4701            .unwrap();
4702
4703        for (i, col_name) in column_names.iter().enumerate() {
4704            let key = format!("crypto.file_decryption.column_key_as_hex::{col_name}");
4705            let value = hex::encode(column_keys[i].clone());
4706            table_config
4707                .parquet
4708                .set(key.as_str(), value.as_str())
4709                .unwrap();
4710        }
4711
4712        // Print matching final decryption config
4713        // println!("{:#?}", table_config.parquet.crypto.file_decryption);
4714
4715        assert_eq!(
4716            table_config.parquet.crypto.file_decryption,
4717            Some(config_decrypt.clone())
4718        );
4719
4720        // Set config directly
4721        let mut table_config = TableOptions::new();
4722        table_config.set_config_format(ConfigFileType::PARQUET);
4723        table_config.parquet.crypto.file_decryption = Some(config_decrypt.clone());
4724        assert_eq!(
4725            table_config.parquet.crypto.file_decryption,
4726            Some(config_decrypt.clone())
4727        );
4728    }
4729
4730    #[cfg(feature = "parquet_encryption")]
4731    #[test]
4732    fn parquet_encryption_invalid_hex_errors_encryption() {
4733        use crate::config::ColumnEncryptionProperties;
4734        use crate::config::ConfigFileEncryptionProperties;
4735        use parquet::encryption::encrypt::FileEncryptionProperties;
4736        use std::collections::HashMap;
4737
4738        let valid_footer_key_as_hex = hex::encode(b"0123456789012345");
4739
4740        let mut enc = ConfigFileEncryptionProperties {
4741            encrypt_footer: true,
4742            footer_key_as_hex: valid_footer_key_as_hex.clone(),
4743            footer_key_metadata_as_hex: String::new(),
4744            column_encryption_properties: HashMap::new(),
4745            aad_prefix_as_hex: String::new(),
4746            store_aad_prefix: false,
4747        };
4748
4749        // Encryption: invalid footer key hex
4750        enc.footer_key_as_hex = "not_hex".to_string();
4751        let err = FileEncryptionProperties::try_from(enc.clone())
4752            .unwrap_err()
4753            .to_string();
4754        assert!(err.contains("Unable to decode hex footer key"));
4755        enc.footer_key_as_hex = valid_footer_key_as_hex.clone();
4756
4757        // Encryption: invalid footer key metadata hex
4758        enc.footer_key_metadata_as_hex = "zz".to_string();
4759        let err = FileEncryptionProperties::try_from(enc.clone())
4760            .unwrap_err()
4761            .to_string();
4762        assert!(err.contains("Unable to decode hex footer key metadata"));
4763        enc.footer_key_metadata_as_hex = String::new();
4764
4765        // Encryption: invalid column key hex
4766        enc.column_encryption_properties.insert(
4767            "col1".to_string(),
4768            ColumnEncryptionProperties {
4769                column_key_as_hex: "bad".to_string(),
4770                column_metadata_as_hex: None,
4771            },
4772        );
4773        let err = FileEncryptionProperties::try_from(enc.clone())
4774            .unwrap_err()
4775            .to_string();
4776        assert!(err.contains("Unable to decode hex encryption key for column col1"));
4777        enc.column_encryption_properties.clear();
4778
4779        // Encryption: invalid column metadata hex
4780        enc.column_encryption_properties.insert(
4781            "col1".to_string(),
4782            ColumnEncryptionProperties {
4783                column_key_as_hex: hex::encode(b"1234567890123450"),
4784                column_metadata_as_hex: Some("zz".to_string()),
4785            },
4786        );
4787        let err = FileEncryptionProperties::try_from(enc.clone())
4788            .unwrap_err()
4789            .to_string();
4790        assert!(err.contains("Unable to decode hex column metadata for column col1"));
4791        enc.column_encryption_properties.clear();
4792
4793        // Encryption: invalid AAD prefix hex
4794        enc.aad_prefix_as_hex = "zz".to_string();
4795        let err = FileEncryptionProperties::try_from(enc.clone())
4796            .unwrap_err()
4797            .to_string();
4798        assert!(err.contains("Unable to decode hex AAD prefix"));
4799    }
4800
4801    #[cfg(feature = "parquet_encryption")]
4802    #[test]
4803    fn parquet_encryption_invalid_hex_errors_decryption() {
4804        use crate::config::ColumnDecryptionProperties;
4805        use crate::config::ConfigFileDecryptionProperties;
4806        use parquet::encryption::decrypt::FileDecryptionProperties;
4807        use std::collections::HashMap;
4808
4809        let valid_footer_key_as_hex = hex::encode(b"0123456789012345");
4810
4811        let mut dec = ConfigFileDecryptionProperties {
4812            footer_key_as_hex: valid_footer_key_as_hex.clone(),
4813            column_decryption_properties: HashMap::new(),
4814            aad_prefix_as_hex: String::new(),
4815            footer_signature_verification: true,
4816        };
4817
4818        // Decryption: invalid column key hex
4819        dec.column_decryption_properties.insert(
4820            "col1".to_string(),
4821            ColumnDecryptionProperties {
4822                column_key_as_hex: "bad".to_string(),
4823            },
4824        );
4825        let err = FileDecryptionProperties::try_from(dec.clone())
4826            .unwrap_err()
4827            .to_string();
4828        assert!(err.contains("Could not decode hex column key"));
4829        assert!(err.contains("col1"));
4830        dec.column_decryption_properties.clear();
4831
4832        // Decryption: invalid footer key hex
4833        dec.footer_key_as_hex = "bad".to_string();
4834        let err = FileDecryptionProperties::try_from(dec.clone())
4835            .unwrap_err()
4836            .to_string();
4837        assert!(err.contains("Could not decode hex footer key"));
4838        dec.footer_key_as_hex = valid_footer_key_as_hex;
4839
4840        // Decryption: invalid AAD prefix hex
4841        dec.aad_prefix_as_hex = "zz".to_string();
4842        let err = FileDecryptionProperties::try_from(dec.clone())
4843            .unwrap_err()
4844            .to_string();
4845        assert!(err.contains("Could not decode hex AAD prefix"));
4846    }
4847
4848    #[cfg(feature = "parquet_encryption")]
4849    #[test]
4850    fn parquet_encryption_factory_config() {
4851        let mut parquet_options = TableParquetOptions::default();
4852
4853        assert_eq!(parquet_options.crypto.factory_id, None);
4854        assert_eq!(parquet_options.crypto.factory_options.options.len(), 0);
4855
4856        let mut input_config = TestExtensionConfig::default();
4857        input_config
4858            .properties
4859            .insert("key1".to_string(), "value 1".to_string());
4860        input_config
4861            .properties
4862            .insert("key2".to_string(), "value 2".to_string());
4863
4864        parquet_options
4865            .crypto
4866            .configure_factory("example_factory", &input_config);
4867
4868        assert_eq!(
4869            parquet_options.crypto.factory_id,
4870            Some("example_factory".to_string())
4871        );
4872        let factory_options = &parquet_options.crypto.factory_options.options;
4873        assert_eq!(factory_options.len(), 2);
4874        assert_eq!(factory_options.get("key1"), Some(&"value 1".to_string()));
4875        assert_eq!(factory_options.get("key2"), Some(&"value 2".to_string()));
4876    }
4877
4878    #[cfg(feature = "parquet_encryption")]
4879    struct ParquetEncryptionKeyRetriever {}
4880
4881    #[cfg(feature = "parquet_encryption")]
4882    impl parquet::encryption::decrypt::KeyRetriever for ParquetEncryptionKeyRetriever {
4883        fn retrieve_key(&self, _key_metadata: &[u8]) -> parquet::errors::Result<Vec<u8>> {
4884            // Ignore key metadata so we can verify that the key retriever isn't used
4885            // even if it can provide a key without using metadata.
4886            Ok(b"1234567890123450".to_vec())
4887        }
4888    }
4889
4890    #[cfg(feature = "parquet_encryption")]
4891    #[test]
4892    fn conversion_from_key_retriever_to_config_file_decryption_properties() {
4893        use crate::Result;
4894        use crate::config::ConfigFileDecryptionProperties;
4895        use crate::encryption::FileDecryptionProperties;
4896
4897        let retriever = std::sync::Arc::new(ParquetEncryptionKeyRetriever {});
4898        let decryption_properties =
4899            FileDecryptionProperties::with_key_retriever(retriever)
4900                .build()
4901                .unwrap();
4902        let config_file_decryption_properties: Result<ConfigFileDecryptionProperties> =
4903            (&decryption_properties).try_into();
4904        assert!(config_file_decryption_properties.is_err());
4905        let err = config_file_decryption_properties.unwrap_err().to_string();
4906        assert_contains!(
4907            err,
4908            "Cannot convert FileDecryptionProperties that use a key retriever to ConfigFileDecryptionProperties"
4909        );
4910    }
4911
4912    #[cfg(feature = "parquet")]
4913    #[test]
4914    fn parquet_table_options_config_entry() {
4915        let mut table_config = TableOptions::new();
4916        table_config.set_config_format(ConfigFileType::PARQUET);
4917        table_config
4918            .set("format.bloom_filter_enabled::col1", "true")
4919            .unwrap();
4920        let entries = table_config.entries();
4921        assert!(
4922            entries
4923                .iter()
4924                .any(|item| item.key == "format.bloom_filter_enabled::col1")
4925        )
4926    }
4927
4928    #[cfg(feature = "parquet")]
4929    #[test]
4930    fn parquet_table_parquet_options_config_entry() {
4931        let mut table_parquet_options = TableParquetOptions::new();
4932        table_parquet_options
4933            .set(
4934                "crypto.file_encryption.column_key_as_hex::double_field",
4935                "31323334353637383930313233343530",
4936            )
4937            .unwrap();
4938        let entries = table_parquet_options.entries();
4939        assert!(
4940            entries.iter().any(|item| item.key
4941                == "crypto.file_encryption.column_key_as_hex::double_field")
4942        )
4943    }
4944
4945    #[cfg(feature = "parquet")]
4946    #[test]
4947    fn parquet_table_options_config_metadata_entry() {
4948        let mut table_config = TableOptions::new();
4949        table_config.set_config_format(ConfigFileType::PARQUET);
4950        table_config.set("format.metadata::key1", "").unwrap();
4951        table_config.set("format.metadata::key2", "value2").unwrap();
4952        table_config
4953            .set("format.metadata::key3", "value with spaces ")
4954            .unwrap();
4955        table_config
4956            .set("format.metadata::key4", "value with special chars :: :")
4957            .unwrap();
4958
4959        let parsed_metadata = table_config.parquet.key_value_metadata.clone();
4960        assert_eq!(parsed_metadata.get("should not exist1"), None);
4961        assert_eq!(parsed_metadata.get("key1"), Some(&Some("".into())));
4962        assert_eq!(parsed_metadata.get("key2"), Some(&Some("value2".into())));
4963        assert_eq!(
4964            parsed_metadata.get("key3"),
4965            Some(&Some("value with spaces ".into()))
4966        );
4967        assert_eq!(
4968            parsed_metadata.get("key4"),
4969            Some(&Some("value with special chars :: :".into()))
4970        );
4971
4972        // duplicate keys are overwritten
4973        table_config.set("format.metadata::key_dupe", "A").unwrap();
4974        table_config.set("format.metadata::key_dupe", "B").unwrap();
4975        let parsed_metadata = table_config.parquet.key_value_metadata;
4976        assert_eq!(parsed_metadata.get("key_dupe"), Some(&Some("B".into())));
4977    }
4978    #[cfg(feature = "parquet")]
4979    #[test]
4980    fn test_parquet_writer_version_validation() {
4981        use crate::{config::ConfigOptions, parquet_config::DFParquetWriterVersion};
4982
4983        let mut config = ConfigOptions::default();
4984
4985        // Valid values should work
4986        config
4987            .set("datafusion.execution.parquet.writer_version", "1.0")
4988            .unwrap();
4989        assert_eq!(
4990            config.execution.parquet.writer_version,
4991            DFParquetWriterVersion::V1_0
4992        );
4993
4994        config
4995            .set("datafusion.execution.parquet.writer_version", "2.0")
4996            .unwrap();
4997        assert_eq!(
4998            config.execution.parquet.writer_version,
4999            DFParquetWriterVersion::V2_0
5000        );
5001
5002        // Invalid value should error immediately at SET time
5003        let err = config
5004            .set("datafusion.execution.parquet.writer_version", "3.0")
5005            .unwrap_err();
5006        assert_contains!(
5007            err.to_string(),
5008            "Invalid or Unsupported Configuration: Invalid parquet writer version: 3.0. Expected one of: 1.0, 2.0"
5009        );
5010    }
5011
5012    #[cfg(feature = "parquet")]
5013    #[test]
5014    fn test_parquet_statistics_validation() {
5015        use crate::{config::ConfigOptions, parquet_config::DFParquetStatistics};
5016
5017        let mut config = ConfigOptions::default();
5018
5019        for (value, expected) in [
5020            ("none", DFParquetStatistics::None),
5021            ("CHUNK", DFParquetStatistics::Chunk),
5022            ("page", DFParquetStatistics::Page),
5023        ] {
5024            config
5025                .set("datafusion.execution.parquet.statistics_enabled", value)
5026                .unwrap();
5027            assert_eq!(config.execution.parquet.statistics_enabled, Some(expected));
5028        }
5029
5030        let err = config
5031            .set("datafusion.execution.parquet.statistics_enabled", "invalid")
5032            .unwrap_err();
5033        assert_contains!(
5034            err.to_string(),
5035            "Invalid parquet statistics setting: invalid. Expected one of: none, chunk, page"
5036        );
5037
5038        // An unset value can arise from deserialization. An invalid update must
5039        // leave that state unchanged rather than inserting the default.
5040        config.execution.parquet.statistics_enabled = None;
5041        assert_eq!(config.execution.parquet.statistics_enabled, None);
5042
5043        assert!(
5044            config
5045                .set("datafusion.execution.parquet.statistics_enabled", "invalid")
5046                .is_err()
5047        );
5048        assert_eq!(config.execution.parquet.statistics_enabled, None);
5049
5050        config.execution.parquet.statistics_enabled = Some(DFParquetStatistics::Page);
5051        assert!(
5052            config
5053                .set(
5054                    "datafusion.execution.parquet.statistics_enabled.typo",
5055                    "none"
5056                )
5057                .is_err()
5058        );
5059        assert_eq!(
5060            config.execution.parquet.statistics_enabled,
5061            Some(DFParquetStatistics::Page)
5062        );
5063
5064        assert!(
5065            config
5066                .reset("datafusion.execution.parquet.statistics_enabled.typo")
5067                .is_err()
5068        );
5069        assert_eq!(
5070            config.execution.parquet.statistics_enabled,
5071            Some(DFParquetStatistics::Page)
5072        );
5073
5074        let mut scalar = DFParquetStatistics::Page;
5075        assert!(ConfigField::set(&mut scalar, "typo", "none").is_err());
5076        assert_eq!(scalar, DFParquetStatistics::Page);
5077    }
5078
5079    #[test]
5080    fn test_execution_time_zone_validation() {
5081        use crate::config::ConfigOptions;
5082
5083        const KEY: &str = "datafusion.execution.time_zone";
5084        let mut config = ConfigOptions::default();
5085        assert_eq!(config.execution.time_zone, None);
5086
5087        // Valid values are kept exactly as written.
5088        for value in ["+08:00", "-08:00", "+0800", "+08", "UTC", "Asia/Taipei"] {
5089            config.set(KEY, value).unwrap();
5090            assert_eq!(
5091                config.execution.time_zone.as_ref().map(|tz| tz.as_str()),
5092                Some(value)
5093            );
5094        }
5095
5096        // A rejected value leaves the previous one in place.
5097        for value in ["+08:00:00", "08:00", "08", "Asia/Taipei2", "AEST", ""] {
5098            let err = config.set(KEY, value).unwrap_err();
5099            assert_contains!(err.to_string(), format!("Invalid time zone: {value}."));
5100            assert_eq!(
5101                config.execution.time_zone.as_ref().map(|tz| tz.as_str()),
5102                Some("Asia/Taipei")
5103            );
5104        }
5105
5106        // An invalid update of an unset value leaves it unset.
5107        config.reset(KEY).unwrap();
5108        assert_eq!(config.execution.time_zone, None);
5109        assert!(config.set(KEY, "Asia/Taipei2").is_err());
5110        assert_eq!(config.execution.time_zone, None);
5111
5112        // The option has no nested fields.
5113        config.set(KEY, "UTC").unwrap();
5114        assert!(config.set(&format!("{KEY}.typo"), "UTC").is_err());
5115        assert!(config.reset(&format!("{KEY}.typo")).is_err());
5116        assert_eq!(
5117            config.execution.time_zone.as_ref().map(|tz| tz.as_str()),
5118            Some("UTC")
5119        );
5120    }
5121
5122    #[cfg(feature = "parquet")]
5123    #[test]
5124    fn test_parquet_compression_validation() {
5125        use crate::{config::ConfigOptions, parquet_config::DFParquetCompression};
5126
5127        let mut config = ConfigOptions::default();
5128        assert_eq!(
5129            config.execution.parquet.compression,
5130            Some(DFParquetCompression::Zstd(3))
5131        );
5132
5133        for (value, expected) in [
5134            ("snappy", DFParquetCompression::Snappy),
5135            ("GZIP(6)", DFParquetCompression::Gzip(6)),
5136            ("'zstd(22)'", DFParquetCompression::Zstd(22)),
5137        ] {
5138            config
5139                .set("datafusion.execution.parquet.compression", value)
5140                .unwrap();
5141            assert_eq!(config.execution.parquet.compression, Some(expected));
5142        }
5143
5144        for (value, message) in [
5145            (
5146                "zstdd(3)",
5147                "Unknown or unsupported parquet compression: zstdd(3)",
5148            ),
5149            (
5150                "zstd",
5151                "zstd compression requires specifying a level such as zstd(4)",
5152            ),
5153            (
5154                "snappy(2)",
5155                "Compression snappy does not support specifying a level",
5156            ),
5157            ("zstd(23)", "Invalid compression level 23 for zstd"),
5158        ] {
5159            let err = config
5160                .set("datafusion.execution.parquet.compression", value)
5161                .unwrap_err();
5162            assert_contains!(err.to_string(), message);
5163            // A rejected value leaves the previous one in place.
5164            assert_eq!(
5165                config.execution.parquet.compression,
5166                Some(DFParquetCompression::Zstd(22))
5167            );
5168        }
5169
5170        // An unset value can arise from deserialization. An invalid update must
5171        // leave that state unchanged rather than inserting the default.
5172        config.execution.parquet.compression = None;
5173        assert!(
5174            config
5175                .set("datafusion.execution.parquet.compression", "zstd")
5176                .is_err()
5177        );
5178        assert_eq!(config.execution.parquet.compression, None);
5179
5180        config.execution.parquet.compression = Some(DFParquetCompression::Lz4);
5181        assert!(
5182            config
5183                .set("datafusion.execution.parquet.compression.typo", "snappy")
5184                .is_err()
5185        );
5186        assert!(
5187            config
5188                .reset("datafusion.execution.parquet.compression.typo")
5189                .is_err()
5190        );
5191        assert_eq!(
5192            config.execution.parquet.compression,
5193            Some(DFParquetCompression::Lz4)
5194        );
5195
5196        let mut scalar = DFParquetCompression::Lz4;
5197        assert!(ConfigField::set(&mut scalar, "typo", "snappy").is_err());
5198        assert_eq!(scalar, DFParquetCompression::Lz4);
5199    }
5200
5201    #[cfg(feature = "parquet")]
5202    #[test]
5203    fn test_parquet_coerce_int96_validation() {
5204        use crate::{config::ConfigOptions, parquet_config::DFTimeUnit};
5205
5206        let mut config = ConfigOptions::default();
5207        assert_eq!(config.execution.parquet.coerce_int96, None);
5208
5209        for (value, expected) in [
5210            ("ns", DFTimeUnit::Nanosecond),
5211            ("US", DFTimeUnit::Microsecond),
5212            ("ms", DFTimeUnit::Millisecond),
5213            ("s", DFTimeUnit::Second),
5214        ] {
5215            config
5216                .set("datafusion.execution.parquet.coerce_int96", value)
5217                .unwrap();
5218            assert_eq!(config.execution.parquet.coerce_int96, Some(expected));
5219        }
5220
5221        let err = config
5222            .set("datafusion.execution.parquet.coerce_int96", "nanos")
5223            .unwrap_err();
5224        assert_contains!(
5225            err.to_string(),
5226            "Invalid parquet coerce_int96 setting: nanos. Expected one of: ns, us, ms, s"
5227        );
5228        // A rejected value leaves the previous one in place.
5229        assert_eq!(
5230            config.execution.parquet.coerce_int96,
5231            Some(DFTimeUnit::Second)
5232        );
5233
5234        // An invalid update must leave an unset option unset rather than
5235        // inserting a default.
5236        config.execution.parquet.coerce_int96 = None;
5237        assert!(
5238            config
5239                .set("datafusion.execution.parquet.coerce_int96", "nanos")
5240                .is_err()
5241        );
5242        assert_eq!(config.execution.parquet.coerce_int96, None);
5243
5244        config.execution.parquet.coerce_int96 = Some(DFTimeUnit::Microsecond);
5245        assert!(
5246            config
5247                .set("datafusion.execution.parquet.coerce_int96.typo", "ns")
5248                .is_err()
5249        );
5250        assert!(
5251            config
5252                .reset("datafusion.execution.parquet.coerce_int96.typo")
5253                .is_err()
5254        );
5255        assert_eq!(
5256            config.execution.parquet.coerce_int96,
5257            Some(DFTimeUnit::Microsecond)
5258        );
5259
5260        let mut scalar = DFTimeUnit::Microsecond;
5261        assert!(ConfigField::set(&mut scalar, "typo", "ns").is_err());
5262        assert_eq!(scalar, DFTimeUnit::Microsecond);
5263    }
5264
5265    #[test]
5266    fn test_parquet_coerce_int96_tz_validation() {
5267        use crate::config::ConfigOptions;
5268
5269        const KEY: &str = "datafusion.execution.parquet.coerce_int96_tz";
5270        let mut config = ConfigOptions::default();
5271        let tz = |config: &ConfigOptions| {
5272            config
5273                .execution
5274                .parquet
5275                .coerce_int96_tz
5276                .as_ref()
5277                .map(|tz| tz.to_string())
5278        };
5279        assert_eq!(tz(&config), None);
5280
5281        // Valid values are kept exactly as written, with or without coerce_int96.
5282        for value in ["UTC", "America/Los_Angeles", "+08:00", "-0530", "+08"] {
5283            config.set(KEY, value).unwrap();
5284            assert_eq!(tz(&config).as_deref(), Some(value));
5285        }
5286
5287        // A rejected value leaves the previous one in place.
5288        for value in ["Not/A_Timezone", "utc", "08:00", ""] {
5289            let err = config.set(KEY, value).unwrap_err();
5290            assert_contains!(err.to_string(), format!("Invalid time zone: {value}."));
5291            assert_eq!(tz(&config).as_deref(), Some("+08"));
5292        }
5293
5294        // Reset restores None, and an invalid update leaves it unset.
5295        config.reset(KEY).unwrap();
5296        assert_eq!(tz(&config), None);
5297        assert!(config.set(KEY, "Not/A_Timezone").is_err());
5298        assert_eq!(tz(&config), None);
5299
5300        // The option has no nested fields.
5301        config.set(KEY, "UTC").unwrap();
5302        assert!(config.set(&format!("{KEY}.typo"), "UTC").is_err());
5303        assert!(config.reset(&format!("{KEY}.typo")).is_err());
5304        assert_eq!(tz(&config).as_deref(), Some("UTC"));
5305    }
5306
5307    #[cfg(feature = "parquet")]
5308    #[test]
5309    fn set_cdc_enabled_flag() {
5310        use crate::config::ConfigOptions;
5311
5312        let mut config = ConfigOptions::default();
5313        // CDC is disabled by default.
5314        assert!(!config.execution.parquet.content_defined_chunking.enabled);
5315
5316        // `.enabled = true` enables CDC; parameters keep their defaults.
5317        config
5318            .set(
5319                "datafusion.execution.parquet.content_defined_chunking.enabled",
5320                "true",
5321            )
5322            .unwrap();
5323        let cdc = &config.execution.parquet.content_defined_chunking;
5324        assert!(cdc.enabled);
5325        assert_eq!(cdc.min_chunk_size, 256 * 1024);
5326        assert_eq!(cdc.max_chunk_size, 1024 * 1024);
5327        assert_eq!(cdc.norm_level, 0);
5328
5329        // `.enabled = false` disables CDC.
5330        config
5331            .set(
5332                "datafusion.execution.parquet.content_defined_chunking.enabled",
5333                "false",
5334            )
5335            .unwrap();
5336        assert!(!config.execution.parquet.content_defined_chunking.enabled);
5337    }
5338
5339    #[cfg(feature = "parquet")]
5340    #[test]
5341    fn set_cdc_param_does_not_enable() {
5342        use crate::config::ConfigOptions;
5343
5344        let mut config = ConfigOptions::default();
5345
5346        // Setting a parameter does NOT enable CDC (`enabled` is a distinct field,
5347        // defaulting to false), and the result is independent of key order.
5348        config
5349            .set(
5350                "datafusion.execution.parquet.content_defined_chunking.min_chunk_size",
5351                "1024",
5352            )
5353            .unwrap();
5354        let cdc = &config.execution.parquet.content_defined_chunking;
5355        assert!(!cdc.enabled);
5356        assert_eq!(cdc.min_chunk_size, 1024);
5357        assert_eq!(cdc.max_chunk_size, 1024 * 1024);
5358        assert_eq!(cdc.norm_level, 0);
5359    }
5360
5361    #[test]
5362    fn test_dialect_metadata_roundtrip() {
5363        use crate::config::Dialect;
5364        use std::str::FromStr;
5365
5366        assert_eq!(Dialect::default(), Dialect::Generic);
5367        assert!(!Dialect::metadata().is_empty());
5368
5369        for info in Dialect::metadata() {
5370            let dialect = info.dialect;
5371
5372            assert_eq!(Dialect::from_str(info.canonical_name).unwrap(), dialect);
5373            assert_eq!(
5374                Dialect::from_str(&info.canonical_name.to_ascii_uppercase()).unwrap(),
5375                dialect
5376            );
5377            assert_eq!(dialect.as_ref(), info.canonical_name);
5378            assert_eq!(dialect.to_string(), info.canonical_name);
5379        }
5380    }
5381
5382    #[test]
5383    fn test_dialect_aliases() {
5384        use crate::config::Dialect;
5385        use std::str::FromStr;
5386
5387        for info in Dialect::metadata() {
5388            for alias in info.aliases {
5389                assert_eq!(Dialect::from_str(alias).unwrap(), info.dialect);
5390                assert_eq!(
5391                    Dialect::from_str(&alias.to_ascii_uppercase()).unwrap(),
5392                    info.dialect
5393                );
5394            }
5395        }
5396    }
5397
5398    #[test]
5399    fn test_available_dialects_includes_each_display_name_once() {
5400        use crate::config::Dialect;
5401        use std::collections::BTreeSet;
5402
5403        let available = Dialect::available();
5404        let listed: Vec<_> = available.split(", ").collect();
5405        let display_names: Vec<_> = Dialect::metadata()
5406            .iter()
5407            .map(|info| info.display_name)
5408            .collect();
5409        let unique_display_names: BTreeSet<_> = display_names.iter().copied().collect();
5410
5411        assert_eq!(display_names.len(), unique_display_names.len());
5412        assert_eq!(listed, display_names);
5413    }
5414
5415    #[test]
5416    fn test_dialect_config_description_uses_metadata() {
5417        use crate::config::{ConfigOptions, Dialect, SQL_PARSER_DIALECT_CONFIG_KEY};
5418
5419        let description = ConfigOptions::default()
5420            .entries()
5421            .into_iter()
5422            .find(|entry| entry.key == SQL_PARSER_DIALECT_CONFIG_KEY)
5423            .unwrap()
5424            .description;
5425
5426        assert!(description.contains(Dialect::available()));
5427    }
5428
5429    #[test]
5430    fn test_invalid_dialect_error_lists_available_dialects() {
5431        use crate::config::Dialect;
5432        use std::str::FromStr;
5433
5434        let error = Dialect::from_str("notadialect").unwrap_err().to_string();
5435
5436        assert!(error.contains("Invalid Dialect: notadialect"));
5437        assert!(error.contains(Dialect::available()));
5438    }
5439
5440    #[test]
5441    fn max_row_group_bytes_rejects_zero() {
5442        use crate::config::MaxRowGroupBytes;
5443        use std::str::FromStr;
5444
5445        assert!(MaxRowGroupBytes::try_new(0).is_err());
5446        assert!(MaxRowGroupBytes::from_str("0").is_err());
5447        assert!(MaxRowGroupBytes::from_str("not_a_number").is_err());
5448        assert_eq!(MaxRowGroupBytes::try_new(128).unwrap().get(), 128);
5449        assert_eq!(MaxRowGroupBytes::from_str("128").unwrap().get(), 128);
5450    }
5451
5452    #[test]
5453    fn parquet_max_row_group_bytes_config_set_rejects_zero() {
5454        use crate::config::ConfigOptions;
5455
5456        let mut options = ConfigOptions::new();
5457        options
5458            .set("datafusion.execution.parquet.max_row_group_bytes", "1024")
5459            .unwrap();
5460        assert_eq!(
5461            options
5462                .execution
5463                .parquet
5464                .max_row_group_bytes
5465                .map(|v| v.get()),
5466            Some(1024)
5467        );
5468
5469        // Zero is rejected at set time, leaving the previous value unchanged.
5470        assert!(
5471            options
5472                .set("datafusion.execution.parquet.max_row_group_bytes", "0")
5473                .is_err()
5474        );
5475        assert_eq!(
5476            options
5477                .execution
5478                .parquet
5479                .max_row_group_bytes
5480                .map(|v| v.get()),
5481            Some(1024)
5482        );
5483    }
5484}