Skip to main content

datafusion_common/
lib.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#![doc(
6    html_logo_url = "https://raw.githubusercontent.com/apache/datafusion/19fe44cf2f30cbdd63d4a4f52c74055163c6cc38/docs/logos/standalone_logo/logo_original.svg",
7    html_favicon_url = "https://raw.githubusercontent.com/apache/datafusion/19fe44cf2f30cbdd63d4a4f52c74055163c6cc38/docs/logos/standalone_logo/logo_original.svg"
8)]
9#![cfg_attr(docsrs, feature(doc_cfg))]
10// Make sure fast / cheap clones on Arc are explicit:
11// https://github.com/apache/datafusion/issues/11143
12#![deny(clippy::clone_on_ref_ptr)]
13#![cfg_attr(test, allow(clippy::needless_pass_by_value))]
14
15mod column;
16mod dfschema;
17mod functional_dependencies;
18mod join_type;
19mod param_value;
20mod partitioning;
21mod schema_reference;
22mod table_reference;
23mod unnest;
24
25pub mod alias;
26pub mod cast;
27pub mod config;
28pub mod cse;
29pub mod datatype;
30pub mod diagnostic;
31pub mod display;
32pub mod encryption;
33pub mod error;
34pub mod extensions;
35pub mod file_options;
36pub mod float_semantics;
37pub mod format;
38pub mod hash_utils;
39pub mod heap_size;
40pub mod instant;
41pub mod metadata;
42pub mod nested_struct;
43mod null_equality;
44pub mod parquet_config;
45pub mod parsers;
46pub mod pruning;
47pub mod rounding;
48pub mod scalar;
49pub mod spans;
50pub mod stats;
51pub mod test_util;
52pub mod tree_node;
53pub mod types;
54pub mod utils;
55
56/// Reexport arrow crate
57pub use arrow;
58pub use column::Column;
59pub use dfschema::{
60    DFSchema, DFSchemaRef, ExprSchema, SchemaExt, ToDFSchema, qualified_name,
61};
62pub use diagnostic::Diagnostic;
63pub use display::human_readable::{
64    human_readable_count, human_readable_duration, human_readable_size, units,
65};
66pub use error::{
67    DataFusionError, Result, SchemaError, SharedResult, field_not_found,
68    unqualified_field_not_found,
69};
70pub use file_options::file_type::{
71    DEFAULT_ARROW_EXTENSION, DEFAULT_AVRO_EXTENSION, DEFAULT_CSV_EXTENSION,
72    DEFAULT_JSON_EXTENSION, DEFAULT_PARQUET_EXTENSION, GetExt,
73};
74pub use functional_dependencies::{
75    Constraint, Constraints, Dependency, FunctionalDependence, FunctionalDependencies,
76    aggregate_functional_dependencies, get_required_group_by_exprs_indices,
77    get_required_sort_exprs_indices, get_target_functional_dependencies,
78};
79use hashbrown::DefaultHashBuilder;
80pub use join_type::{JoinConstraint, JoinSide, JoinType};
81pub use nested_struct::cast_column;
82pub use null_equality::NullEquality;
83pub use param_value::ParamValues;
84pub use partitioning::{SplitPoint, validate_range_split_points};
85pub use scalar::{ScalarType, ScalarValue};
86pub use schema_reference::SchemaReference;
87pub use spans::{Location, Span, Spans};
88pub use stats::{ColumnStatistics, Statistics};
89pub use table_reference::{ResolvedTableReference, TableReference};
90pub use unnest::{NullHandling, RecursionUnnestOption, UnnestOptions};
91pub use utils::project_schema;
92
93// These are hidden from docs purely to avoid polluting the public view of what this crate exports.
94// These are just re-exports of macros by the same name, which gets around the 'cannot refer to
95// macro-expanded macro_export macros by their full path' error.
96// The design to get around this comes from this comment:
97// https://github.com/rust-lang/rust/pull/52234#issuecomment-976702997
98#[doc(hidden)]
99pub use error::{
100    _config_datafusion_err, _exec_datafusion_err, _ffi_datafusion_err,
101    _internal_datafusion_err, _not_impl_datafusion_err, _plan_datafusion_err,
102    _resources_datafusion_err, _substrait_datafusion_err,
103};
104
105// The HashMap and HashSet implementations that should be used as the uniform defaults
106pub type HashMap<K, V, S = DefaultHashBuilder> = hashbrown::HashMap<K, V, S>;
107pub type HashSet<T, S = DefaultHashBuilder> = hashbrown::HashSet<T, S>;
108pub mod hash_map {
109    pub use hashbrown::hash_map::Entry;
110    pub use hashbrown::hash_map::EntryRef;
111}
112pub mod hash_set {
113    pub use hashbrown::hash_set::Entry;
114}
115
116/// Downcast an Arrow Array to a concrete type, return an `DataFusionError::Internal` if the cast is
117/// not possible. In normal usage of DataFusion the downcast should always succeed.
118///
119/// Example: `let array = downcast_value!(values, Int32Array)`
120#[macro_export]
121macro_rules! downcast_value {
122    ($Value: expr, $Type: ident) => {{
123        use $crate::__private::DowncastArrayHelper;
124        $Value.downcast_array_helper::<$Type>()?
125    }};
126    ($Value: expr, $Type: ident, $T: tt) => {{
127        use $crate::__private::DowncastArrayHelper;
128        $Value.downcast_array_helper::<$Type<$T>>()?
129    }};
130}
131
132// Not public API.
133#[doc(hidden)]
134pub mod __private {
135    use crate::Result;
136    use crate::error::_internal_datafusion_err;
137    use arrow::array::Array;
138    use std::any::{Any, type_name};
139
140    #[doc(hidden)]
141    pub trait DowncastArrayHelper {
142        fn downcast_array_helper<U: Any>(&self) -> Result<&U>;
143    }
144
145    impl<T: Array + ?Sized> DowncastArrayHelper for T {
146        fn downcast_array_helper<U: Any>(&self) -> Result<&U> {
147            self.as_any().downcast_ref().ok_or_else(|| {
148                let actual_type = self.data_type();
149                let desired_type_name = type_name::<U>();
150                _internal_datafusion_err!(
151                    "could not cast array of type {} to {}",
152                    actual_type,
153                    desired_type_name
154                )
155            })
156        }
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use arrow::array::{ArrayRef, Int32Array, UInt64Array};
163    use std::any::{type_name, type_name_of_val};
164    use std::sync::Arc;
165
166    #[test]
167    fn test_downcast_value() -> crate::Result<()> {
168        let boxed: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
169        let array = downcast_value!(&boxed, Int32Array);
170        assert_eq!(type_name_of_val(&array), type_name::<&Int32Array>());
171
172        let expected: Int32Array = vec![1, 2, 3].into_iter().map(Some).collect();
173        assert_eq!(array, &expected);
174        Ok(())
175    }
176
177    #[test]
178    fn test_downcast_value_err_message() {
179        let boxed: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
180        let error: crate::DataFusionError = (|| {
181            downcast_value!(&boxed, UInt64Array);
182            Ok(())
183        })()
184        .err()
185        .unwrap();
186
187        assert_starts_with(
188            error.to_string(),
189            "Internal error: could not cast array of type Int32 to arrow_array::array::primitive_array::PrimitiveArray<arrow_array::types::UInt64Type>",
190        );
191    }
192
193    // `err.to_string()` depends on backtrace being present (may have backtrace appended)
194    // `err.strip_backtrace()` also depends on backtrace being present (may have "This was likely caused by ..." stripped)
195    fn assert_starts_with(actual: impl AsRef<str>, expected_prefix: impl AsRef<str>) {
196        let actual = actual.as_ref();
197        let expected_prefix = expected_prefix.as_ref();
198        assert!(
199            actual.starts_with(expected_prefix),
200            "Expected '{actual}' to start with '{expected_prefix}'"
201        );
202    }
203}