Skip to content

Apache DataFusion SQL Query Engine

Implemented a ReadOptions trait for cleaner code. (#5025)

Sai Krishna Reddy Lakkam556fffbf25db
diff --git a/datafusion/core/src/datasource/listing/table.rs b/datafusion/core/src/datasource/listing/table.rs
index f595e52461..29e2259e44 100644
--- a/datafusion/core/src/datasource/listing/table.rs
+++ b/datafusion/core/src/datasource/listing/table.rs
@@ -781,6 +781,7 @@ mod tests {
use crate::prelude::*;
use crate::{
datasource::file_format::{avro::AvroFormat, parquet::ParquetFormat},
+ execution::options::ReadOptions,
logical_expr::{col, lit},
test::{columns, object_store::register_test_store},
};
@@ -1097,7 +1098,8 @@ mod tests {
#[values(true, false)] infinite_data: bool,
) -> Result<()> {
let config = CsvReadOptions::new().mark_infinite(infinite_data);
- let listing_options = config.to_listing_options(1);
+ let session_config = SessionConfig::new().with_target_partitions(1);
+ let listing_options = config.to_listing_options(&session_config);
unbounded_table_helper(FileType::CSV, listing_options, infinite_data).await
}
@@ -1107,7 +1109,8 @@ mod tests {
#[values(true, false)] infinite_data: bool,
) -> Result<()> {
let config = NdJsonReadOptions::default().mark_infinite(infinite_data);
- let listing_options = config.to_listing_options(1);
+ let session_config = SessionConfig::new().with_target_partitions(1);
+ let listing_options = config.to_listing_options(&session_config);
unbounded_table_helper(FileType::JSON, listing_options, infinite_data).await
}
@@ -1117,7 +1120,8 @@ mod tests {
#[values(true, false)] infinite_data: bool,
) -> Result<()> {
let config = AvroReadOptions::default().mark_infinite(infinite_data);
- let listing_options = config.to_listing_options(1);
+ let session_config = SessionConfig::new().with_target_partitions(1);
+ let listing_options = config.to_listing_options(&session_config);
unbounded_table_helper(FileType::AVRO, listing_options, infinite_data).await
}
diff --git a/datafusion/core/src/execution/context.rs b/datafusion/core/src/execution/context.rs
index 1df9bf111e..0705c9b5ab 100644
--- a/datafusion/core/src/execution/context.rs
+++ b/datafusion/core/src/execution/context.rs
@@ -103,7 +103,7 @@ use datafusion_sql::planner::object_name_to_table_reference;
use uuid::Uuid;
use super::options::{
- AvroReadOptions, CsvReadOptions, NdJsonReadOptions, ParquetReadOptions,
+ AvroReadOptions, CsvReadOptions, NdJsonReadOptions, ParquetReadOptions, ReadOptions,
};
/// SessionContext is the main interface for executing queries with DataFusion. It stands for
@@ -607,35 +607,25 @@ impl SessionContext {
.insert(f.name.clone(), Arc::new(f));
}
- /// Creates a [`DataFrame`] for reading an Avro data source.
+ /// Creates a [`DataFrame`] for reading a data source.
///
/// For more control such as reading multiple files, you can use
/// [`read_table`](Self::read_table) with a [`ListingTable`].
- pub async fn read_avro(
+ async fn _read_type<'a>(
&self,
table_path: impl AsRef<str>,
- options: AvroReadOptions<'_>,
+ options: impl ReadOptions<'a>,
) -> Result<DataFrame> {
let table_path = ListingTableUrl::parse(table_path)?;
- let target_partitions = self.copied_config().target_partitions();
-
- let listing_options = options.to_listing_options(target_partitions);
-
- let resolved_schema = match (options.schema, options.infinite) {
- (Some(s), _) => Arc::new(s.to_owned()),
- (None, false) => {
- listing_options
- .infer_schema(&self.state(), &table_path)
- .await?
- }
- (None, true) => {
- return Err(DataFusionError::Plan(
- "Schema inference for infinite data sources is not supported."
- .to_string(),
- ))
- }
+ let session_config = self.copied_config();
+ let listing_options = options.to_listing_options(&session_config);
+ let resolved_schema = match options
+ .get_resolved_schema(&session_config, self.state(), table_path.clone())
+ .await
+ {
+ Ok(resolved_schema) => resolved_schema,
+ Err(e) => return Err(e),
};
-
let config = ListingTableConfig::new(table_path)
.with_listing_options(listing_options)
.with_schema(resolved_schema);
@@ -643,6 +633,18 @@ impl SessionContext {
self.read_table(Arc::new(provider))
}
+ /// Creates a [`DataFrame`] for reading an Avro data source.
+ ///
+ /// For more control such as reading multiple files, you can use
+ /// [`read_table`](Self::read_table) with a [`ListingTable`].
+ pub async fn read_avro(
+ &self,
+ table_path: impl AsRef<str>,
+ options: AvroReadOptions<'_>,
+ ) -> Result<DataFrame> {
+ self._read_type(table_path, options).await
+ }
+
/// Creates a [`DataFrame`] for reading an Json data source.
///
/// For more control such as reading multiple files, you can use
@@ -652,31 +654,7 @@ impl SessionContext {
table_path: impl AsRef<str>,
options: NdJsonReadOptions<'_>,
) -> Result<DataFrame> {
- let table_path = ListingTableUrl::parse(table_path)?;
- let target_partitions = self.copied_config().target_partitions();
-
- let listing_options = options.to_listing_options(target_partitions);
-
- let resolved_schema = match (options.schema, options.infinite) {
- (Some(s), _) => Arc::new(s.to_owned()),
- (None, false) => {
- listing_options
- .infer_schema(&self.state(), &table_path)
- .await?
- }
- (None, true) => {
- return Err(DataFusionError::Plan(
- "Schema inference for infinite data sources is not supported."
- .to_string(),
- ))
- }
- };
- let config = ListingTableConfig::new(table_path)
- .with_listing_options(listing_options)
- .with_schema(resolved_schema);
- let provider = ListingTable::try_new(config)?;
-
- self.read_table(Arc::new(provider))
+ self._read_type(table_path, options).await
}
/// Creates an empty DataFrame.
@@ -696,29 +674,7 @@ impl SessionContext {
table_path: impl AsRef<str>,
options: CsvReadOptions<'_>,
) -> Result<DataFrame> {
- let table_path = ListingTableUrl::parse(table_path)?;
- let target_partitions = self.copied_config().target_partitions();
- let listing_options = options.to_listing_options(target_partitions);
- let resolved_schema = match (options.schema, options.infinite) {
- (Some(s), _) => Arc::new(s.to_owned()),
- (None, false) => {
- listing_options
- .infer_schema(&self.state(), &table_path)
- .await?
- }
- (None, true) => {
- return Err(DataFusionError::Plan(
- "Schema inference for infinite data sources is not supported."
- .to_string(),
- ))
- }
- };
- let config = ListingTableConfig::new(table_path.clone())
- .with_listing_options(listing_options)
- .with_schema(resolved_schema);
-
- let provider = ListingTable::try_new(config)?;
- self.read_table(Arc::new(provider))
+ self._read_type(table_path, options).await
}
/// Creates a [`DataFrame`] for reading a Parquet data source.
@@ -730,20 +686,7 @@ impl SessionContext {
table_path: impl AsRef<str>,
options: ParquetReadOptions<'_>,
) -> Result<DataFrame> {
- let table_path = ListingTableUrl::parse(table_path)?;
- let listing_options = options.to_listing_options(&self.state.read().config);
-
- // with parquet we resolve the schema in all cases
- let resolved_schema = listing_options
- .infer_schema(&self.state(), &table_path)
- .await?;
-
- let config = ListingTableConfig::new(table_path)
- .with_listing_options(listing_options)
- .with_schema(resolved_schema);
-
- let provider = ListingTable::try_new(config)?;
- self.read_table(Arc::new(provider))
+ self._read_type(table_path, options).await
}
/// Creates a [`DataFrame`] for a [`TableProvider`] such as a
@@ -812,8 +755,7 @@ impl SessionContext {
table_path: &str,
options: CsvReadOptions<'_>,
) -> Result<()> {
- let listing_options =
- options.to_listing_options(self.copied_config().target_partitions());
+ let listing_options = options.to_listing_options(&self.copied_config());
self.register_listing_table(
name,
@@ -835,8 +777,7 @@ impl SessionContext {
table_path: &str,
options: NdJsonReadOptions<'_>,
) -> Result<()> {
- let listing_options =
- options.to_listing_options(self.copied_config().target_partitions());
+ let listing_options = options.to_listing_options(&self.copied_config());
self.register_listing_table(
name,
@@ -872,8 +813,7 @@ impl SessionContext {
table_path: &str,
options: AvroReadOptions<'_>,
) -> Result<()> {
- let listing_options =
- options.to_listing_options(self.copied_config().target_partitions());
+ let listing_options = options.to_listing_options(&self.copied_config());
self.register_listing_table(
name,
diff --git a/datafusion/core/src/execution/options.rs b/datafusion/core/src/execution/options.rs
index 6ecf89e002..c7a5dea7e2 100644
--- a/datafusion/core/src/execution/options.rs
+++ b/datafusion/core/src/execution/options.rs
@@ -19,22 +19,25 @@
use std::sync::Arc;
-use arrow::datatypes::{DataType, Schema};
+use arrow::datatypes::{DataType, Schema, SchemaRef};
+use async_trait::async_trait;
+use datafusion_common::DataFusionError;
+use super::context::{SessionConfig, SessionState};
use crate::datasource::file_format::avro::DEFAULT_AVRO_EXTENSION;
use crate::datasource::file_format::csv::DEFAULT_CSV_EXTENSION;
use crate::datasource::file_format::file_type::FileCompressionType;
use crate::datasource::file_format::json::DEFAULT_JSON_EXTENSION;
use crate::datasource::file_format::parquet::DEFAULT_PARQUET_EXTENSION;
use crate::datasource::file_format::DEFAULT_SCHEMA_INFER_MAX_RECORD;
+use crate::datasource::listing::ListingTableUrl;
use crate::datasource::{
file_format::{
avro::AvroFormat, csv::CsvFormat, json::JsonFormat, parquet::ParquetFormat,
},
listing::ListingOptions,
};
-
-use super::context::SessionConfig;
+use crate::error::Result;
/// Options that control the reading of CSV files.
///
@@ -149,23 +152,6 @@ impl<'a> CsvReadOptions<'a> {
self.file_compression_type = file_compression_type;
self
}
-
- /// Helper to convert these user facing options to `ListingTable` options
- pub fn to_listing_options(&self, target_partitions: usize) -> ListingOptions {
- let file_format = CsvFormat::default()
- .with_has_header(self.has_header)
- .with_delimiter(self.delimiter)
- .with_schema_infer_max_rec(Some(self.schema_infer_max_records))
- .with_file_compression_type(self.file_compression_type.to_owned());
-
- ListingOptions::new(Arc::new(file_format))
- .with_file_extension(self.file_extension)
- .with_target_partitions(target_partitions)
- .with_table_partition_cols(self.table_partition_cols.clone())
- // TODO: Add file sort order into CsvReadOptions and introduce here.
- .with_file_sort_order(None)
- .with_infinite_source(self.infinite)
- }
}
/// Options that control the reading of Parquet files.
@@ -226,18 +212,6 @@ impl<'a> ParquetReadOptions<'a> {
self.table_partition_cols = table_partition_cols;
self
}
-
- /// Helper to convert these user facing options to `ListingTable` options
- pub fn to_listing_options(&self, config: &SessionConfig) -> ListingOptions {
- let file_format = ParquetFormat::new()
- .with_enable_pruning(self.parquet_pruning)
- .with_skip_metadata(self.skip_metadata);
-
- ListingOptions::new(Arc::new(file_format))
- .with_file_extension(self.file_extension)
- .with_target_partitions(config.target_partitions())
- .with_table_partition_cols(self.table_partition_cols.clone())
- }
}
/// Options that control the reading of AVRO files.
@@ -281,17 +255,6 @@ impl<'a> AvroReadOptions<'a> {
self
}
- /// Helper to convert these user facing options to `ListingTable` options
- pub fn to_listing_options(&self, target_partitions: usize) -> ListingOptions {
- let file_format = AvroFormat::default();
-
- ListingOptions::new(Arc::new(file_format))
- .with_file_extension(self.file_extension)
- .with_target_partitions(target_partitions)
- .with_table_partition_cols(self.table_partition_cols.clone())
- .with_infinite_source(self.infinite)
- }
-
/// Configure mark_infinite setting
pub fn mark_infinite(mut self, infinite: bool) -> Self {
self.infinite = infinite;
@@ -377,16 +340,147 @@ impl<'a> NdJsonReadOptions<'a> {
self.schema = Some(schema);
self
}
+}
+#[async_trait]
+/// ['ReadOptions'] is implemented by Options like ['CsvReadOptions'] that control the reading of respective files/sources.
+pub trait ReadOptions<'a> {
/// Helper to convert these user facing options to `ListingTable` options
- pub fn to_listing_options(&self, target_partitions: usize) -> ListingOptions {
+ fn to_listing_options(&self, config: &SessionConfig) -> ListingOptions;
+
+ /// Infer and resolve the schema from the files/sources provided.
+ async fn get_resolved_schema(
+ &self,
+ config: &SessionConfig,
+ state: SessionState,
+ table_path: ListingTableUrl,
+ ) -> Result<SchemaRef>;
+
+ /// helper function to reduce repetitive code. Infers the schema from sources if not provided. Infinite data sources not supported through this function.
+ async fn _get_resolved_schema(
+ &'a self,
+ config: &SessionConfig,
+ state: SessionState,
+ table_path: ListingTableUrl,
+ schema: Option<&'a Schema>,
+ infinite: bool,
+ ) -> Result<SchemaRef>
+ where
+ 'a: 'async_trait,
+ {
+ match (schema, infinite) {
+ (Some(s), _) => Ok(Arc::new(s.to_owned())),
+ (None, false) => Ok(self
+ .to_listing_options(config)
+ .infer_schema(&state, &table_path)
+ .await?),
+ (None, true) => Err(DataFusionError::Plan(
+ "Schema inference for infinite data sources is not supported."
+ .to_string(),
+ )),
+ }
+ }
+}
+
+#[async_trait]
+impl ReadOptions<'_> for CsvReadOptions<'_> {
+ fn to_listing_options(&self, config: &SessionConfig) -> ListingOptions {
+ let file_format = CsvFormat::default()
+ .with_has_header(self.has_header)
+ .with_delimiter(self.delimiter)
+ .with_schema_infer_max_rec(Some(self.schema_infer_max_records))
+ .with_file_compression_type(self.file_compression_type.to_owned());
+
+ ListingOptions::new(Arc::new(file_format))
+ .with_file_extension(self.file_extension)
+ .with_target_partitions(config.target_partitions())
+ .with_table_partition_cols(self.table_partition_cols.clone())
+ // TODO: Add file sort order into CsvReadOptions and introduce here.
+ .with_file_sort_order(None)
+ .with_infinite_source(self.infinite)
+ }
+
+ async fn get_resolved_schema(
+ &self,
+ config: &SessionConfig,
+ state: SessionState,
+ table_path: ListingTableUrl,
+ ) -> Result<SchemaRef> {
+ self._get_resolved_schema(config, state, table_path, self.schema, self.infinite)
+ .await
+ }
+}
+
+#[async_trait]
+impl ReadOptions<'_> for ParquetReadOptions<'_> {
+ fn to_listing_options(&self, config: &SessionConfig) -> ListingOptions {
+ let file_format = ParquetFormat::new()
+ .with_enable_pruning(self.parquet_pruning)
+ .with_skip_metadata(self.skip_metadata);
+
+ ListingOptions::new(Arc::new(file_format))
+ .with_file_extension(self.file_extension)
+ .with_target_partitions(config.target_partitions())
+ .with_table_partition_cols(self.table_partition_cols.clone())
+ }
+
+ async fn get_resolved_schema(
+ &self,
+ config: &SessionConfig,
+ state: SessionState,
+ table_path: ListingTableUrl,
+ ) -> Result<SchemaRef> {
+ // with parquet we resolve the schema in all cases
+ Ok(self
+ .to_listing_options(config)
+ .infer_schema(&state, &table_path)
+ .await?)
+ }
+}
+
+#[async_trait]
+impl ReadOptions<'_> for NdJsonReadOptions<'_> {
+ fn to_listing_options(&self, config: &SessionConfig) -> ListingOptions {
let file_format = JsonFormat::default()
.with_file_compression_type(self.file_compression_type.to_owned());
ListingOptions::new(Arc::new(file_format))
.with_file_extension(self.file_extension)
- .with_target_partitions(target_partitions)
+ .with_target_partitions(config.target_partitions())
.with_table_partition_cols(self.table_partition_cols.clone())
.with_infinite_source(self.infinite)
}
+
+ async fn get_resolved_schema(
+ &self,
+ config: &SessionConfig,
+ state: SessionState,
+ table_path: ListingTableUrl,
+ ) -> Result<SchemaRef> {
+ self._get_resolved_schema(config, state, table_path, self.schema, self.infinite)
+ .await
+ }
+}
+
+#[async_trait]
+impl ReadOptions<'_> for AvroReadOptions<'_> {
+ fn to_listing_options(&self, config: &SessionConfig) -> ListingOptions {
+ let file_format = AvroFormat::default();
+
+ ListingOptions::new(Arc::new(file_format))
+ .with_file_extension(self.file_extension)
+ .with_target_partitions(config.target_partitions())
+ .with_table_partition_cols(self.table_partition_cols.clone())
+ .with_infinite_source(self.infinite)
+ }
+
+ async fn get_resolved_schema(
+ &self,
+ config: &SessionConfig,
+ state: SessionState,
+ table_path: ListingTableUrl,
+ ) -> Result<SchemaRef> {
+ self._get_resolved_schema(config, state, table_path, self.schema, self.infinite)
+ .await
+ }
}
diff --git a/datafusion/core/tests/sql/parquet.rs b/datafusion/core/tests/sql/parquet.rs
index 1f16307010..b01e8b843d 100644
--- a/datafusion/core/tests/sql/parquet.rs
+++ b/datafusion/core/tests/sql/parquet.rs
@@ -18,7 +18,7 @@
use std::{fs, path::Path};
use ::parquet::arrow::ArrowWriter;
-use datafusion::datasource::listing::ListingOptions;
+use datafusion::{datasource::listing::ListingOptions, execution::options::ReadOptions};
use datafusion_common::cast::{as_list_array, as_primitive_array, as_string_array};
use tempfile::TempDir;
diff --git a/datafusion/core/tests/sql/window.rs b/datafusion/core/tests/sql/window.rs
index f0fd04efd1..17cf63b7c8 100644
--- a/datafusion/core/tests/sql/window.rs
+++ b/datafusion/core/tests/sql/window.rs
@@ -18,6 +18,7 @@
use super::*;
use ::parquet::arrow::arrow_writer::ArrowWriter;
use ::parquet::file::properties::WriterProperties;
+use datafusion::execution::options::ReadOptions;
/// for window functions without order by the first, last, and nth function call does not make sense
#[tokio::test]