Kontinuation commented on code in PR #251:
URL: https://github.com/apache/sedona-db/pull/251#discussion_r2501756210


##########
rust/sedona-datasource/src/format.rs:
##########
@@ -0,0 +1,717 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::{any::Any, collections::HashMap, fmt::Debug, sync::Arc};
+
+use arrow_schema::{Schema, SchemaRef};
+use async_trait::async_trait;
+use datafusion::{
+    config::ConfigOptions,
+    datasource::{
+        file_format::{file_compression_type::FileCompressionType, FileFormat, 
FileFormatFactory},
+        listing::PartitionedFile,
+        physical_plan::{
+            FileGroupPartitioner, FileMeta, FileOpenFuture, FileOpener, 
FileScanConfig,
+            FileSinkConfig, FileSource,
+        },
+    },
+};
+use datafusion_catalog::{memory::DataSourceExec, Session};
+use datafusion_common::{not_impl_err, DataFusionError, GetExt, Result, 
Statistics};
+use datafusion_physical_expr::{LexOrdering, LexRequirement, PhysicalExpr};
+use datafusion_physical_plan::{
+    filter_pushdown::{FilterPushdownPropagation, PushedDown},
+    metrics::ExecutionPlanMetricsSet,
+    ExecutionPlan,
+};
+use futures::{StreamExt, TryStreamExt};
+use object_store::{ObjectMeta, ObjectStore};
+use sedona_common::sedona_internal_err;
+
+use crate::spec::{ExternalFormatSpec, Object, OpenReaderArgs, 
SupportsRepartition};
+
+/// Create a [FileFormatFactory] from a [ExternalFormatSpec]
+///
+/// The FileFormatFactory is the object that may be registered with a
+/// SessionStateBuilder to allow SQL queries to access this format.
+#[derive(Debug)]
+pub struct ExternalFormatFactory {
+    spec: Arc<dyn ExternalFormatSpec>,
+}
+
+impl ExternalFormatFactory {
+    pub fn new(spec: Arc<dyn ExternalFormatSpec>) -> Self {
+        Self { spec }
+    }
+}
+
+impl FileFormatFactory for ExternalFormatFactory {
+    fn create(
+        &self,
+        _state: &dyn Session,
+        format_options: &HashMap<String, String>,
+    ) -> Result<Arc<dyn FileFormat>> {
+        Ok(Arc::new(ExternalFileFormat {
+            spec: self.spec.with_options(format_options)?,
+        }))
+    }
+
+    fn default(&self) -> Arc<dyn FileFormat> {
+        Arc::new(ExternalFileFormat {
+            spec: self.spec.clone(),
+        })
+    }
+
+    fn as_any(&self) -> &dyn std::any::Any {
+        self
+    }
+}
+
+impl GetExt for ExternalFormatFactory {
+    fn get_ext(&self) -> String {
+        self.spec.extension().to_string()
+    }
+}
+
+#[derive(Debug)]
+pub(crate) struct ExternalFileFormat {
+    spec: Arc<dyn ExternalFormatSpec>,
+}
+
+impl ExternalFileFormat {
+    pub fn new(spec: Arc<dyn ExternalFormatSpec>) -> Self {
+        Self { spec }
+    }
+}
+
+#[async_trait]
+impl FileFormat for ExternalFileFormat {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn get_ext(&self) -> String {
+        self.spec.extension().to_string()
+    }
+
+    fn get_ext_with_compression(
+        &self,
+        _file_compression_type: &FileCompressionType,
+    ) -> Result<String> {
+        not_impl_err!("extension with compression type")
+    }
+
+    fn compression_type(&self) -> Option<FileCompressionType> {
+        None
+    }
+
+    async fn infer_schema(
+        &self,
+        state: &dyn Session,
+        store: &Arc<dyn ObjectStore>,
+        objects: &[ObjectMeta],
+    ) -> Result<SchemaRef> {
+        let mut schemas: Vec<_> = futures::stream::iter(objects)
+            .map(|object| async move {
+                let schema = self
+                    .spec
+                    .infer_schema(&Object {
+                        store: Some(store.clone()),
+                        url: None,
+                        meta: Some(object.clone()),
+                        range: None,
+                    })
+                    .await?;
+                Ok::<_, DataFusionError>((object.location.clone(), schema))
+            })
+            .boxed() // Workaround 
https://github.com/rust-lang/rust/issues/64552
+            .buffered(state.config_options().execution.meta_fetch_concurrency)
+            .try_collect()
+            .await?;
+
+        schemas.sort_by(|(location1, _), (location2, _)| 
location1.cmp(location2));
+
+        let schemas = schemas
+            .into_iter()
+            .map(|(_, schema)| schema)
+            .collect::<Vec<_>>();
+
+        let schema = Schema::try_merge(schemas)?;
+        Ok(Arc::new(schema))
+    }
+
+    async fn infer_stats(
+        &self,
+        _state: &dyn Session,
+        store: &Arc<dyn ObjectStore>,
+        table_schema: SchemaRef,
+        object: &ObjectMeta,
+    ) -> Result<Statistics> {
+        self.spec
+            .infer_stats(
+                &Object {
+                    store: Some(store.clone()),
+                    url: None,
+                    meta: Some(object.clone()),
+                    range: None,
+                },
+                &table_schema,
+            )
+            .await
+    }
+
+    async fn create_physical_plan(
+        &self,
+        _state: &dyn Session,
+        config: FileScanConfig,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        Ok(DataSourceExec::from_data_source(config))
+    }
+
+    async fn create_writer_physical_plan(
+        &self,
+        _input: Arc<dyn ExecutionPlan>,
+        _state: &dyn Session,
+        _conf: FileSinkConfig,
+        _order_requirements: Option<LexRequirement>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        not_impl_err!("writing not yet supported for SimpleSedonaFormat")
+    }
+
+    fn file_source(&self) -> Arc<dyn FileSource> {
+        Arc::new(ExternalFileSource::new(self.spec.clone()))
+    }
+}
+
+#[derive(Debug, Clone)]
+struct ExternalFileSource {
+    spec: Arc<dyn ExternalFormatSpec>,
+    batch_size: Option<usize>,
+    file_schema: Option<SchemaRef>,
+    file_projection: Option<Vec<usize>>,
+    filters: Vec<Arc<dyn PhysicalExpr>>,
+    metrics: ExecutionPlanMetricsSet,
+    projected_statistics: Option<Statistics>,
+}
+
+impl ExternalFileSource {
+    pub fn new(spec: Arc<dyn ExternalFormatSpec>) -> Self {
+        Self {
+            spec,
+            batch_size: None,
+            file_schema: None,
+            file_projection: None,
+            filters: Vec::new(),
+            metrics: ExecutionPlanMetricsSet::default(),
+            projected_statistics: None,
+        }
+    }
+}
+
+impl FileSource for ExternalFileSource {
+    fn create_file_opener(
+        &self,
+        store: Arc<dyn ObjectStore>,
+        base_config: &FileScanConfig,
+        _partition: usize,
+    ) -> Arc<dyn FileOpener> {
+        let args = OpenReaderArgs {
+            src: Object {
+                store: Some(store.clone()),
+                url: Some(base_config.object_store_url.clone()),
+                meta: None,
+                range: None,
+            },
+            batch_size: self.batch_size,
+            file_schema: self.file_schema.clone(),
+            file_projection: self.file_projection.clone(),
+            filters: self.filters.clone(),
+        };
+
+        Arc::new(ExternalFileOpener {
+            spec: self.spec.clone(),
+            args,
+        })
+    }
+
+    fn try_pushdown_filters(
+        &self,
+        filters: Vec<Arc<dyn PhysicalExpr>>,
+        _config: &ConfigOptions,
+    ) -> Result<FilterPushdownPropagation<Arc<dyn FileSource>>> {
+        // Record any new filters
+        let num_filters = filters.len();
+        let mut new_filters = self.filters.clone();
+        new_filters.extend(filters);
+        let source = Self {
+            filters: new_filters,
+            ..self.clone()
+        };
+
+        // ...but don't indicate that we handled them so that the filters are
+        // applied by the other node.
+        Ok(FilterPushdownPropagation::with_parent_pushdown_result(vec![
+            PushedDown::No;
+            num_filters
+        ])
+        .with_updated_node(Arc::new(source)))
+    }
+
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn with_batch_size(&self, batch_size: usize) -> Arc<dyn FileSource> {
+        Arc::new(Self {
+            batch_size: Some(batch_size),
+            ..self.clone()
+        })
+    }
+
+    fn with_schema(&self, schema: SchemaRef) -> Arc<dyn FileSource> {
+        Arc::new(Self {
+            file_schema: Some(schema),
+            ..self.clone()
+        })
+    }
+
+    fn with_projection(&self, config: &FileScanConfig) -> Arc<dyn FileSource> {
+        Arc::new(Self {
+            file_projection: config.file_column_projection_indices(),
+            ..self.clone()
+        })
+    }
+
+    fn with_statistics(&self, statistics: Statistics) -> Arc<dyn FileSource> {
+        Arc::new(Self {
+            projected_statistics: Some(statistics),
+            ..self.clone()
+        })
+    }
+
+    fn metrics(&self) -> &ExecutionPlanMetricsSet {
+        &self.metrics
+    }
+
+    fn statistics(&self) -> Result<Statistics> {
+        let statistics = &self.projected_statistics;
+        Ok(statistics
+            .clone()
+            .expect("projected_statistics must be set"))
+    }
+
+    fn file_type(&self) -> &str {
+        self.spec.extension()
+    }
+
+    fn repartitioned(
+        &self,
+        target_partitions: usize,
+        repartition_file_min_size: usize,
+        output_ordering: Option<LexOrdering>,
+        config: &FileScanConfig,
+    ) -> Result<Option<FileScanConfig>> {
+        match self.spec.supports_repartition() {
+            SupportsRepartition::None => Ok(None),
+            SupportsRepartition::ByRange => {
+                // Default implementation
+                if config.file_compression_type.is_compressed() || 
config.new_lines_in_values {
+                    return Ok(None);
+                }
+
+                let repartitioned_file_groups_option = 
FileGroupPartitioner::new()
+                    .with_target_partitions(target_partitions)
+                    .with_repartition_file_min_size(repartition_file_min_size)
+                    
.with_preserve_order_within_groups(output_ordering.is_some())
+                    .repartition_file_groups(&config.file_groups);
+
+                if let Some(repartitioned_file_groups) = 
repartitioned_file_groups_option {
+                    let mut source = config.clone();
+                    source.file_groups = repartitioned_file_groups;
+                    return Ok(Some(source));
+                }
+                Ok(None)
+            }
+        }
+    }
+}
+
+#[derive(Debug, Clone)]
+struct ExternalFileOpener {
+    spec: Arc<dyn ExternalFormatSpec>,
+    args: OpenReaderArgs,
+}
+
+impl FileOpener for ExternalFileOpener {
+    fn open(&self, file_meta: FileMeta, _file: PartitionedFile) -> 
Result<FileOpenFuture> {
+        if file_meta.range.is_some() {
+            return sedona_internal_err!(
+                "Expected SimpleOpener to open a single partition per file"

Review Comment:
   I believe that this should be `ExternalFileOpener`.



##########
rust/sedona-datasource/src/format.rs:
##########
@@ -0,0 +1,717 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::{any::Any, collections::HashMap, fmt::Debug, sync::Arc};
+
+use arrow_schema::{Schema, SchemaRef};
+use async_trait::async_trait;
+use datafusion::{
+    config::ConfigOptions,
+    datasource::{
+        file_format::{file_compression_type::FileCompressionType, FileFormat, 
FileFormatFactory},
+        listing::PartitionedFile,
+        physical_plan::{
+            FileGroupPartitioner, FileMeta, FileOpenFuture, FileOpener, 
FileScanConfig,
+            FileSinkConfig, FileSource,
+        },
+    },
+};
+use datafusion_catalog::{memory::DataSourceExec, Session};
+use datafusion_common::{not_impl_err, DataFusionError, GetExt, Result, 
Statistics};
+use datafusion_physical_expr::{LexOrdering, LexRequirement, PhysicalExpr};
+use datafusion_physical_plan::{
+    filter_pushdown::{FilterPushdownPropagation, PushedDown},
+    metrics::ExecutionPlanMetricsSet,
+    ExecutionPlan,
+};
+use futures::{StreamExt, TryStreamExt};
+use object_store::{ObjectMeta, ObjectStore};
+use sedona_common::sedona_internal_err;
+
+use crate::spec::{ExternalFormatSpec, Object, OpenReaderArgs, 
SupportsRepartition};
+
+/// Create a [FileFormatFactory] from a [ExternalFormatSpec]
+///
+/// The FileFormatFactory is the object that may be registered with a
+/// SessionStateBuilder to allow SQL queries to access this format.
+#[derive(Debug)]
+pub struct ExternalFormatFactory {
+    spec: Arc<dyn ExternalFormatSpec>,
+}
+
+impl ExternalFormatFactory {
+    pub fn new(spec: Arc<dyn ExternalFormatSpec>) -> Self {
+        Self { spec }
+    }
+}
+
+impl FileFormatFactory for ExternalFormatFactory {
+    fn create(
+        &self,
+        _state: &dyn Session,
+        format_options: &HashMap<String, String>,
+    ) -> Result<Arc<dyn FileFormat>> {
+        Ok(Arc::new(ExternalFileFormat {
+            spec: self.spec.with_options(format_options)?,
+        }))
+    }
+
+    fn default(&self) -> Arc<dyn FileFormat> {
+        Arc::new(ExternalFileFormat {
+            spec: self.spec.clone(),
+        })
+    }
+
+    fn as_any(&self) -> &dyn std::any::Any {
+        self
+    }
+}
+
+impl GetExt for ExternalFormatFactory {
+    fn get_ext(&self) -> String {
+        self.spec.extension().to_string()
+    }
+}
+
+#[derive(Debug)]
+pub(crate) struct ExternalFileFormat {
+    spec: Arc<dyn ExternalFormatSpec>,
+}
+
+impl ExternalFileFormat {
+    pub fn new(spec: Arc<dyn ExternalFormatSpec>) -> Self {
+        Self { spec }
+    }
+}
+
+#[async_trait]
+impl FileFormat for ExternalFileFormat {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn get_ext(&self) -> String {
+        self.spec.extension().to_string()
+    }
+
+    fn get_ext_with_compression(
+        &self,
+        _file_compression_type: &FileCompressionType,
+    ) -> Result<String> {
+        not_impl_err!("extension with compression type")
+    }
+
+    fn compression_type(&self) -> Option<FileCompressionType> {
+        None
+    }
+
+    async fn infer_schema(
+        &self,
+        state: &dyn Session,
+        store: &Arc<dyn ObjectStore>,
+        objects: &[ObjectMeta],
+    ) -> Result<SchemaRef> {
+        let mut schemas: Vec<_> = futures::stream::iter(objects)
+            .map(|object| async move {
+                let schema = self
+                    .spec
+                    .infer_schema(&Object {
+                        store: Some(store.clone()),
+                        url: None,
+                        meta: Some(object.clone()),
+                        range: None,
+                    })
+                    .await?;
+                Ok::<_, DataFusionError>((object.location.clone(), schema))
+            })
+            .boxed() // Workaround 
https://github.com/rust-lang/rust/issues/64552
+            .buffered(state.config_options().execution.meta_fetch_concurrency)
+            .try_collect()
+            .await?;
+
+        schemas.sort_by(|(location1, _), (location2, _)| 
location1.cmp(location2));
+
+        let schemas = schemas
+            .into_iter()
+            .map(|(_, schema)| schema)
+            .collect::<Vec<_>>();
+
+        let schema = Schema::try_merge(schemas)?;
+        Ok(Arc::new(schema))
+    }
+
+    async fn infer_stats(
+        &self,
+        _state: &dyn Session,
+        store: &Arc<dyn ObjectStore>,
+        table_schema: SchemaRef,
+        object: &ObjectMeta,
+    ) -> Result<Statistics> {
+        self.spec
+            .infer_stats(
+                &Object {
+                    store: Some(store.clone()),
+                    url: None,
+                    meta: Some(object.clone()),
+                    range: None,
+                },
+                &table_schema,
+            )
+            .await
+    }
+
+    async fn create_physical_plan(
+        &self,
+        _state: &dyn Session,
+        config: FileScanConfig,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        Ok(DataSourceExec::from_data_source(config))
+    }
+
+    async fn create_writer_physical_plan(
+        &self,
+        _input: Arc<dyn ExecutionPlan>,
+        _state: &dyn Session,
+        _conf: FileSinkConfig,
+        _order_requirements: Option<LexRequirement>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        not_impl_err!("writing not yet supported for SimpleSedonaFormat")

Review Comment:
   Should this be `"ExternalFileFormat"`?



##########
rust/sedona-datasource/Cargo.toml:
##########
@@ -0,0 +1,66 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[package]
+name = "sedona-datasource"
+version.workspace = true
+homepage.workspace = true
+repository.workspace = true
+description.workspace = true
+readme.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+
+[lints.clippy]
+result_large_err = "allow"
+
+[features]
+default = []
+
+[dev-dependencies]
+sedona-testing = { path = "../sedona-testing" }
+url = { workspace = true }
+rstest = { workspace = true }
+tempfile = { workspace = true }
+tokio = { workspace = true }
+
+[dependencies]
+async-trait = { workspace = true }
+arrow-schema = { workspace = true }
+arrow-array = { workspace = true }
+bytes = { workspace = true }
+chrono = { workspace = true }
+datafusion = { workspace = true, features = ["parquet"] }
+datafusion-catalog = { workspace = true }
+datafusion-common = { workspace = true }
+datafusion-execution = { workspace = true }
+datafusion-expr = { workspace = true }
+datafusion-physical-expr = { workspace = true }
+datafusion-physical-plan = { workspace = true }
+float_next_after = { workspace = true }
+geo-traits = { workspace = true }
+futures = { workspace = true }
+object_store = { workspace = true }
+parquet = { workspace = true }
+sedona-common = { path = "../sedona-common" }
+sedona-expr = { path = "../sedona-expr" }
+sedona-functions = { path = "../sedona-functions" }
+sedona-geometry = { path = "../sedona-geometry" }
+sedona-schema = { path = "../sedona-schema" }
+serde = { workspace = true }
+serde_json = { workspace = true }
+serde_with = { workspace = true }

Review Comment:
   Are there unneeded dependencies? I believe that `chrono`, 
`float_next_after`, and `parquet` are not needed here.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to