You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by "yukkit (via GitHub)" <gi...@apache.org> on 2024/09/03 14:34:45 UTC

[PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

yukkit opened a new pull request, #600:
URL: https://github.com/apache/iceberg-rust/pull/600

   resolve #586
   
   TODO: supplement unit tests and add validation of data


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "liurenjie1024 (via GitHub)" <gi...@apache.org>.
liurenjie1024 commented on code in PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#discussion_r1746466160


##########
crates/integrations/datafusion/src/table/table_provider_factory.rs:
##########
@@ -0,0 +1,180 @@
+// 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::collections::HashMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use datafusion::catalog::{Session, TableProvider, TableProviderFactory};
+use datafusion::error::Result as DFResult;
+use datafusion::logical_expr::CreateExternalTable;
+use datafusion::sql::TableReference;
+use iceberg::arrow::schema_to_arrow_schema;
+use iceberg::io::FileIO;
+use iceberg::table::StaticTable;
+use iceberg::{Error, ErrorKind, Result, TableIdent};
+
+use super::IcebergTableProvider;
+use crate::to_datafusion_error;
+
+#[derive(Default)]
+#[non_exhaustive]
+pub struct IcebergTableProviderFactory {}

Review Comment:
   It would be better to provide some doc to explain its usage.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "yukkit (via GitHub)" <gi...@apache.org>.
yukkit commented on code in PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#discussion_r1747989388


##########
crates/integrations/datafusion/src/table/table_provider_factory.rs:
##########
@@ -0,0 +1,312 @@
+// 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::borrow::Cow;
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use datafusion::catalog::{Session, TableProvider, TableProviderFactory};
+use datafusion::error::Result as DFResult;
+use datafusion::logical_expr::CreateExternalTable;
+use datafusion::sql::TableReference;
+use iceberg::arrow::schema_to_arrow_schema;
+use iceberg::io::FileIO;
+use iceberg::table::StaticTable;
+use iceberg::{Error, ErrorKind, Result, TableIdent};
+
+use super::IcebergTableProvider;
+use crate::to_datafusion_error;
+
+/// A factory that implements DataFusion's `TableProviderFactory` to create `IcebergTableProvider` instances.
+///
+/// # Example
+///
+/// The following example demonstrates how to create an Iceberg external table using SQL in
+/// a DataFusion session with `IcebergTableProviderFactory`:
+///
+/// ```
+/// use std::sync::Arc;
+///
+/// use datafusion::prelude::*;
+/// use iceberg_datafusion::IcebergTableProviderFactory;
+///
+/// #[tokio::main]
+/// async fn main() {
+///     // Create a new session context
+///     let mut state = SessionStateBuilder::new().with_default_features().build();
+///
+///     // Register the IcebergTableProviderFactory in the session
+///     state.table_factories_mut().insert(
+///         "ICEBERG".to_string(),
+///         Arc::new(IcebergTableProviderFactory::new()),
+///     );
+///
+///     let ctx = SessionContext::new_with_state(state);
+///
+///     // Define the table reference and the location of the Iceberg metadata file
+///     let table_ref = TableReference::bare("my_iceberg_table");
+///     let metadata_file_path = "/path/to/iceberg/metadata";
+///
+///     // SQL command to create the Iceberg external table
+///     let sql = format!(
+///         "CREATE EXTERNAL TABLE {} STORED AS ICEBERG LOCATION '{}'",
+///         table_ref, metadata_file_path
+///     );
+///
+///     // Execute the SQL to create the external table
+///     ctx.sql(&sql).await.expect("Failed to create table");
+///
+///     // Verify the table was created by retrieving the table provider
+///     let table_provider = ctx
+///         .table_provider(table_ref)
+///         .await
+///         .expect("Table not found");
+///
+///     println!("Iceberg external table created successfully.");
+/// }
+/// ```
+///
+/// # Note
+/// This factory is designed to work with the DataFusion query engine,
+/// specifically for handling Iceberg tables in external table commands.
+/// Currently, this implementation supports only reading Iceberg tables, with
+/// the creation of new tables not yet available.
+///
+/// # Errors
+/// An error will be returned if any unsupported feature, such as partition columns,
+/// order expressions, constraints, or column defaults, is detected in the table creation command.
+#[derive(Default)]
+#[non_exhaustive]
+pub struct IcebergTableProviderFactory {}
+
+impl IcebergTableProviderFactory {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+#[async_trait]
+impl TableProviderFactory for IcebergTableProviderFactory {
+    async fn create(
+        &self,
+        _state: &dyn Session,
+        cmd: &CreateExternalTable,
+    ) -> DFResult<Arc<dyn TableProvider>> {
+        check_cmd(cmd).map_err(to_datafusion_error)?;
+
+        let table_name = &cmd.name;
+        let metadata_file_path = &cmd.location;
+        let options = &cmd.options;
+
+        let table_name_with_ns = complement_namespace_if_necessary(table_name);
+
+        let table = create_static_table(table_name_with_ns, metadata_file_path, options)
+            .await
+            .map_err(to_datafusion_error)?
+            .into_table();
+
+        let schema = schema_to_arrow_schema(table.metadata().current_schema())
+            .map_err(to_datafusion_error)?;
+
+        Ok(Arc::new(IcebergTableProvider::new(table, Arc::new(schema))))
+    }
+}
+
+fn check_cmd(cmd: &CreateExternalTable) -> Result<()> {
+    println!("Checking command: {:?}", cmd);
+
+    let CreateExternalTable {
+        schema,
+        table_partition_cols,
+        order_exprs,
+        constraints,
+        column_defaults,
+        ..
+    } = cmd;
+
+    // Check if any of the fields violate the constraints in a single condition
+    let is_invalid = !schema.fields().is_empty()
+        || !table_partition_cols.is_empty()
+        || !order_exprs.is_empty()
+        || !constraints.is_empty()
+        || !column_defaults.is_empty();
+
+    if is_invalid {
+        return Err(Error::new(ErrorKind::FeatureUnsupported, "Currently we only support reading existing icebergs tables in external table command. To create new table, please use catalog provider."));
+    }
+
+    Ok(())
+}
+
+/// Complements the namespace of a table name if necessary.
+///
+/// # Example
+///
+/// ```
+/// use datafusion::sql::TableReference;
+/// use iceberg_datafusion::complement_namespace_if_necessary;
+///
+/// let table_name = TableReference::bare("table_name");
+/// let table_name_with_ns = complement_namespace_if_necessary(&table_name);
+///
+/// assert_eq!(
+///     table_name_with_ns,
+///     TableReference::partial("default", "table_name")
+/// );
+/// ```
+///
+/// # Note
+/// If the table name is a bare name, it will be complemented with the 'default' namespace.
+/// Otherwise, it will be returned as is. Because Iceberg tables are always namespaced, but DataFusion
+/// external table commands not include the namespace, this function ensures that the namespace is always present.
+///
+/// # See also
+/// - [`iceberg::NamespaceIdent`]
+/// - [`datafusion::sql::planner::SqlToRel::external_table_to_plan`]
+fn complement_namespace_if_necessary(table_name: &TableReference) -> Cow<'_, TableReference> {
+    match table_name {
+        TableReference::Bare { table } => {
+            Cow::Owned(TableReference::partial("default", table.as_ref()))
+        }
+        other => Cow::Borrowed(other),
+    }
+}

Review Comment:
   Please pay attention to this function, because when `DataFusion` creates external tables, it only creates bare `TableReference`, which does not include a `schema`. However, when constructing `TableIdent` in Iceberg, the 'schema' is required. Does anyone have a good approach for handling compatibility?



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "matthewmturner (via GitHub)" <gi...@apache.org>.
matthewmturner commented on code in PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#discussion_r1777144414


##########
crates/integrations/datafusion/src/table/table_provider_factory.rs:
##########
@@ -0,0 +1,312 @@
+// 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::borrow::Cow;
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use datafusion::catalog::{Session, TableProvider, TableProviderFactory};
+use datafusion::error::Result as DFResult;
+use datafusion::logical_expr::CreateExternalTable;
+use datafusion::sql::TableReference;
+use iceberg::arrow::schema_to_arrow_schema;
+use iceberg::io::FileIO;
+use iceberg::table::StaticTable;
+use iceberg::{Error, ErrorKind, Result, TableIdent};
+
+use super::IcebergTableProvider;
+use crate::to_datafusion_error;
+
+/// A factory that implements DataFusion's `TableProviderFactory` to create `IcebergTableProvider` instances.
+///
+/// # Example
+///
+/// The following example demonstrates how to create an Iceberg external table using SQL in
+/// a DataFusion session with `IcebergTableProviderFactory`:
+///
+/// ```
+/// use std::sync::Arc;
+///
+/// use datafusion::prelude::*;
+/// use iceberg_datafusion::IcebergTableProviderFactory;
+///
+/// #[tokio::main]
+/// async fn main() {
+///     // Create a new session context
+///     let mut state = SessionStateBuilder::new().with_default_features().build();
+///
+///     // Register the IcebergTableProviderFactory in the session
+///     state.table_factories_mut().insert(
+///         "ICEBERG".to_string(),
+///         Arc::new(IcebergTableProviderFactory::new()),
+///     );
+///
+///     let ctx = SessionContext::new_with_state(state);
+///
+///     // Define the table reference and the location of the Iceberg metadata file
+///     let table_ref = TableReference::bare("my_iceberg_table");
+///     let metadata_file_path = "/path/to/iceberg/metadata";
+///
+///     // SQL command to create the Iceberg external table
+///     let sql = format!(
+///         "CREATE EXTERNAL TABLE {} STORED AS ICEBERG LOCATION '{}'",
+///         table_ref, metadata_file_path
+///     );
+///
+///     // Execute the SQL to create the external table
+///     ctx.sql(&sql).await.expect("Failed to create table");
+///
+///     // Verify the table was created by retrieving the table provider
+///     let table_provider = ctx
+///         .table_provider(table_ref)
+///         .await
+///         .expect("Table not found");
+///
+///     println!("Iceberg external table created successfully.");
+/// }
+/// ```
+///
+/// # Note
+/// This factory is designed to work with the DataFusion query engine,
+/// specifically for handling Iceberg tables in external table commands.
+/// Currently, this implementation supports only reading Iceberg tables, with
+/// the creation of new tables not yet available.
+///
+/// # Errors
+/// An error will be returned if any unsupported feature, such as partition columns,
+/// order expressions, constraints, or column defaults, is detected in the table creation command.
+#[derive(Default)]
+#[non_exhaustive]
+pub struct IcebergTableProviderFactory {}
+
+impl IcebergTableProviderFactory {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+#[async_trait]
+impl TableProviderFactory for IcebergTableProviderFactory {
+    async fn create(
+        &self,
+        _state: &dyn Session,
+        cmd: &CreateExternalTable,
+    ) -> DFResult<Arc<dyn TableProvider>> {
+        check_cmd(cmd).map_err(to_datafusion_error)?;
+
+        let table_name = &cmd.name;
+        let metadata_file_path = &cmd.location;
+        let options = &cmd.options;
+
+        let table_name_with_ns = complement_namespace_if_necessary(table_name);
+
+        let table = create_static_table(table_name_with_ns, metadata_file_path, options)
+            .await
+            .map_err(to_datafusion_error)?
+            .into_table();
+
+        let schema = schema_to_arrow_schema(table.metadata().current_schema())
+            .map_err(to_datafusion_error)?;
+
+        Ok(Arc::new(IcebergTableProvider::new(table, Arc::new(schema))))
+    }
+}
+
+fn check_cmd(cmd: &CreateExternalTable) -> Result<()> {
+    println!("Checking command: {:?}", cmd);
+
+    let CreateExternalTable {
+        schema,
+        table_partition_cols,
+        order_exprs,
+        constraints,
+        column_defaults,
+        ..
+    } = cmd;
+
+    // Check if any of the fields violate the constraints in a single condition
+    let is_invalid = !schema.fields().is_empty()
+        || !table_partition_cols.is_empty()
+        || !order_exprs.is_empty()
+        || !constraints.is_empty()
+        || !column_defaults.is_empty();
+
+    if is_invalid {
+        return Err(Error::new(ErrorKind::FeatureUnsupported, "Currently we only support reading existing icebergs tables in external table command. To create new table, please use catalog provider."));
+    }
+
+    Ok(())
+}
+
+/// Complements the namespace of a table name if necessary.
+///
+/// # Example
+///
+/// ```
+/// use datafusion::sql::TableReference;
+/// use iceberg_datafusion::complement_namespace_if_necessary;
+///
+/// let table_name = TableReference::bare("table_name");
+/// let table_name_with_ns = complement_namespace_if_necessary(&table_name);
+///
+/// assert_eq!(
+///     table_name_with_ns,
+///     TableReference::partial("default", "table_name")
+/// );
+/// ```
+///
+/// # Note
+/// If the table name is a bare name, it will be complemented with the 'default' namespace.
+/// Otherwise, it will be returned as is. Because Iceberg tables are always namespaced, but DataFusion
+/// external table commands not include the namespace, this function ensures that the namespace is always present.
+///
+/// # See also
+/// - [`iceberg::NamespaceIdent`]
+/// - [`datafusion::sql::planner::SqlToRel::external_table_to_plan`]
+fn complement_namespace_if_necessary(table_name: &TableReference) -> Cow<'_, TableReference> {
+    match table_name {
+        TableReference::Bare { table } => {
+            Cow::Owned(TableReference::partial("default", table.as_ref()))
+        }
+        other => Cow::Borrowed(other),
+    }
+}

Review Comment:
   Yeah weve got a [ticket](https://github.com/apache/datafusion/issues/12607) created for that now. thanks @yukkit 



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "matthewmturner (via GitHub)" <gi...@apache.org>.
matthewmturner commented on code in PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#discussion_r1773470190


##########
crates/integrations/datafusion/src/table/table_provider_factory.rs:
##########
@@ -0,0 +1,312 @@
+// 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::borrow::Cow;
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use datafusion::catalog::{Session, TableProvider, TableProviderFactory};
+use datafusion::error::Result as DFResult;
+use datafusion::logical_expr::CreateExternalTable;
+use datafusion::sql::TableReference;
+use iceberg::arrow::schema_to_arrow_schema;
+use iceberg::io::FileIO;
+use iceberg::table::StaticTable;
+use iceberg::{Error, ErrorKind, Result, TableIdent};
+
+use super::IcebergTableProvider;
+use crate::to_datafusion_error;
+
+/// A factory that implements DataFusion's `TableProviderFactory` to create `IcebergTableProvider` instances.
+///
+/// # Example
+///
+/// The following example demonstrates how to create an Iceberg external table using SQL in
+/// a DataFusion session with `IcebergTableProviderFactory`:
+///
+/// ```
+/// use std::sync::Arc;
+///
+/// use datafusion::prelude::*;
+/// use iceberg_datafusion::IcebergTableProviderFactory;
+///
+/// #[tokio::main]
+/// async fn main() {
+///     // Create a new session context
+///     let mut state = SessionStateBuilder::new().with_default_features().build();
+///
+///     // Register the IcebergTableProviderFactory in the session
+///     state.table_factories_mut().insert(
+///         "ICEBERG".to_string(),
+///         Arc::new(IcebergTableProviderFactory::new()),
+///     );
+///
+///     let ctx = SessionContext::new_with_state(state);
+///
+///     // Define the table reference and the location of the Iceberg metadata file
+///     let table_ref = TableReference::bare("my_iceberg_table");
+///     let metadata_file_path = "/path/to/iceberg/metadata";
+///
+///     // SQL command to create the Iceberg external table
+///     let sql = format!(
+///         "CREATE EXTERNAL TABLE {} STORED AS ICEBERG LOCATION '{}'",
+///         table_ref, metadata_file_path
+///     );
+///
+///     // Execute the SQL to create the external table
+///     ctx.sql(&sql).await.expect("Failed to create table");
+///
+///     // Verify the table was created by retrieving the table provider
+///     let table_provider = ctx
+///         .table_provider(table_ref)
+///         .await
+///         .expect("Table not found");
+///
+///     println!("Iceberg external table created successfully.");
+/// }
+/// ```
+///
+/// # Note
+/// This factory is designed to work with the DataFusion query engine,
+/// specifically for handling Iceberg tables in external table commands.
+/// Currently, this implementation supports only reading Iceberg tables, with
+/// the creation of new tables not yet available.
+///
+/// # Errors
+/// An error will be returned if any unsupported feature, such as partition columns,
+/// order expressions, constraints, or column defaults, is detected in the table creation command.
+#[derive(Default)]
+#[non_exhaustive]
+pub struct IcebergTableProviderFactory {}
+
+impl IcebergTableProviderFactory {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+#[async_trait]
+impl TableProviderFactory for IcebergTableProviderFactory {
+    async fn create(
+        &self,
+        _state: &dyn Session,
+        cmd: &CreateExternalTable,
+    ) -> DFResult<Arc<dyn TableProvider>> {
+        check_cmd(cmd).map_err(to_datafusion_error)?;
+
+        let table_name = &cmd.name;
+        let metadata_file_path = &cmd.location;
+        let options = &cmd.options;
+
+        let table_name_with_ns = complement_namespace_if_necessary(table_name);
+
+        let table = create_static_table(table_name_with_ns, metadata_file_path, options)
+            .await
+            .map_err(to_datafusion_error)?
+            .into_table();
+
+        let schema = schema_to_arrow_schema(table.metadata().current_schema())
+            .map_err(to_datafusion_error)?;
+
+        Ok(Arc::new(IcebergTableProvider::new(table, Arc::new(schema))))
+    }
+}
+
+fn check_cmd(cmd: &CreateExternalTable) -> Result<()> {
+    println!("Checking command: {:?}", cmd);
+
+    let CreateExternalTable {
+        schema,
+        table_partition_cols,
+        order_exprs,
+        constraints,
+        column_defaults,
+        ..
+    } = cmd;
+
+    // Check if any of the fields violate the constraints in a single condition
+    let is_invalid = !schema.fields().is_empty()
+        || !table_partition_cols.is_empty()
+        || !order_exprs.is_empty()
+        || !constraints.is_empty()
+        || !column_defaults.is_empty();
+
+    if is_invalid {
+        return Err(Error::new(ErrorKind::FeatureUnsupported, "Currently we only support reading existing icebergs tables in external table command. To create new table, please use catalog provider."));
+    }
+
+    Ok(())
+}
+
+/// Complements the namespace of a table name if necessary.
+///
+/// # Example
+///
+/// ```
+/// use datafusion::sql::TableReference;
+/// use iceberg_datafusion::complement_namespace_if_necessary;
+///
+/// let table_name = TableReference::bare("table_name");
+/// let table_name_with_ns = complement_namespace_if_necessary(&table_name);
+///
+/// assert_eq!(
+///     table_name_with_ns,
+///     TableReference::partial("default", "table_name")
+/// );
+/// ```
+///
+/// # Note
+/// If the table name is a bare name, it will be complemented with the 'default' namespace.
+/// Otherwise, it will be returned as is. Because Iceberg tables are always namespaced, but DataFusion
+/// external table commands not include the namespace, this function ensures that the namespace is always present.
+///
+/// # See also
+/// - [`iceberg::NamespaceIdent`]
+/// - [`datafusion::sql::planner::SqlToRel::external_table_to_plan`]
+fn complement_namespace_if_necessary(table_name: &TableReference) -> Cow<'_, TableReference> {
+    match table_name {
+        TableReference::Bare { table } => {
+            Cow::Owned(TableReference::partial("default", table.as_ref()))
+        }
+        other => Cow::Borrowed(other),
+    }
+}

Review Comment:
   I ran into an issue with external tables only creating bare `TableReference` as well - do you know if thats the intended behavior or if its a bug in datafusion?



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "yukkit (via GitHub)" <gi...@apache.org>.
yukkit commented on code in PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#discussion_r1817714442


##########
crates/integrations/datafusion/src/table/table_provider_factory.rs:
##########
@@ -0,0 +1,312 @@
+// 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::borrow::Cow;
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use datafusion::catalog::{Session, TableProvider, TableProviderFactory};
+use datafusion::error::Result as DFResult;
+use datafusion::logical_expr::CreateExternalTable;
+use datafusion::sql::TableReference;
+use iceberg::arrow::schema_to_arrow_schema;
+use iceberg::io::FileIO;
+use iceberg::table::StaticTable;
+use iceberg::{Error, ErrorKind, Result, TableIdent};
+
+use super::IcebergTableProvider;
+use crate::to_datafusion_error;
+
+/// A factory that implements DataFusion's `TableProviderFactory` to create `IcebergTableProvider` instances.
+///
+/// # Example
+///
+/// The following example demonstrates how to create an Iceberg external table using SQL in
+/// a DataFusion session with `IcebergTableProviderFactory`:
+///
+/// ```
+/// use std::sync::Arc;
+///
+/// use datafusion::prelude::*;
+/// use iceberg_datafusion::IcebergTableProviderFactory;
+///
+/// #[tokio::main]
+/// async fn main() {
+///     // Create a new session context
+///     let mut state = SessionStateBuilder::new().with_default_features().build();
+///
+///     // Register the IcebergTableProviderFactory in the session
+///     state.table_factories_mut().insert(
+///         "ICEBERG".to_string(),
+///         Arc::new(IcebergTableProviderFactory::new()),
+///     );
+///
+///     let ctx = SessionContext::new_with_state(state);
+///
+///     // Define the table reference and the location of the Iceberg metadata file
+///     let table_ref = TableReference::bare("my_iceberg_table");
+///     let metadata_file_path = "/path/to/iceberg/metadata";
+///
+///     // SQL command to create the Iceberg external table
+///     let sql = format!(
+///         "CREATE EXTERNAL TABLE {} STORED AS ICEBERG LOCATION '{}'",
+///         table_ref, metadata_file_path
+///     );
+///
+///     // Execute the SQL to create the external table
+///     ctx.sql(&sql).await.expect("Failed to create table");
+///
+///     // Verify the table was created by retrieving the table provider
+///     let table_provider = ctx
+///         .table_provider(table_ref)
+///         .await
+///         .expect("Table not found");
+///
+///     println!("Iceberg external table created successfully.");
+/// }
+/// ```
+///
+/// # Note
+/// This factory is designed to work with the DataFusion query engine,
+/// specifically for handling Iceberg tables in external table commands.
+/// Currently, this implementation supports only reading Iceberg tables, with
+/// the creation of new tables not yet available.
+///
+/// # Errors
+/// An error will be returned if any unsupported feature, such as partition columns,
+/// order expressions, constraints, or column defaults, is detected in the table creation command.
+#[derive(Default)]
+#[non_exhaustive]
+pub struct IcebergTableProviderFactory {}
+
+impl IcebergTableProviderFactory {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+#[async_trait]
+impl TableProviderFactory for IcebergTableProviderFactory {
+    async fn create(
+        &self,
+        _state: &dyn Session,
+        cmd: &CreateExternalTable,
+    ) -> DFResult<Arc<dyn TableProvider>> {
+        check_cmd(cmd).map_err(to_datafusion_error)?;
+
+        let table_name = &cmd.name;
+        let metadata_file_path = &cmd.location;
+        let options = &cmd.options;
+
+        let table_name_with_ns = complement_namespace_if_necessary(table_name);
+
+        let table = create_static_table(table_name_with_ns, metadata_file_path, options)
+            .await
+            .map_err(to_datafusion_error)?
+            .into_table();
+
+        let schema = schema_to_arrow_schema(table.metadata().current_schema())
+            .map_err(to_datafusion_error)?;
+
+        Ok(Arc::new(IcebergTableProvider::new(table, Arc::new(schema))))
+    }
+}
+
+fn check_cmd(cmd: &CreateExternalTable) -> Result<()> {
+    println!("Checking command: {:?}", cmd);
+
+    let CreateExternalTable {
+        schema,
+        table_partition_cols,
+        order_exprs,
+        constraints,
+        column_defaults,
+        ..
+    } = cmd;
+
+    // Check if any of the fields violate the constraints in a single condition
+    let is_invalid = !schema.fields().is_empty()
+        || !table_partition_cols.is_empty()
+        || !order_exprs.is_empty()
+        || !constraints.is_empty()
+        || !column_defaults.is_empty();
+
+    if is_invalid {
+        return Err(Error::new(ErrorKind::FeatureUnsupported, "Currently we only support reading existing icebergs tables in external table command. To create new table, please use catalog provider."));
+    }
+
+    Ok(())
+}
+
+/// Complements the namespace of a table name if necessary.
+///
+/// # Example
+///
+/// ```
+/// use datafusion::sql::TableReference;
+/// use iceberg_datafusion::complement_namespace_if_necessary;
+///
+/// let table_name = TableReference::bare("table_name");
+/// let table_name_with_ns = complement_namespace_if_necessary(&table_name);
+///
+/// assert_eq!(
+///     table_name_with_ns,
+///     TableReference::partial("default", "table_name")
+/// );
+/// ```
+///
+/// # Note
+/// If the table name is a bare name, it will be complemented with the 'default' namespace.
+/// Otherwise, it will be returned as is. Because Iceberg tables are always namespaced, but DataFusion
+/// external table commands not include the namespace, this function ensures that the namespace is always present.
+///
+/// # See also
+/// - [`iceberg::NamespaceIdent`]
+/// - [`datafusion::sql::planner::SqlToRel::external_table_to_plan`]
+fn complement_namespace_if_necessary(table_name: &TableReference) -> Cow<'_, TableReference> {
+    match table_name {
+        TableReference::Bare { table } => {
+            Cow::Owned(TableReference::partial("default", table.as_ref()))
+        }
+        other => Cow::Borrowed(other),
+    }
+}

Review Comment:
   @liurenjie1024 You’re right. When creating an external table in DataFusion without specifying a schema, it will to being created under the default schema. In this case, the table name passed to `TableProviderFactory` does not include schema information. However, `TableIdent` requires a namespace, so I use "default" to populate this value. Anyway, the `IcebergTableProvider` doesn't actually rely on the specific content of `TableIdent`, so it has no impact when used as an external table in DataFusion (at least as things stand).



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "yukkit (via GitHub)" <gi...@apache.org>.
yukkit commented on code in PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#discussion_r1747927949


##########
crates/integrations/datafusion/src/table/table_provider_factory.rs:
##########
@@ -0,0 +1,180 @@
+// 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::collections::HashMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use datafusion::catalog::{Session, TableProvider, TableProviderFactory};
+use datafusion::error::Result as DFResult;
+use datafusion::logical_expr::CreateExternalTable;
+use datafusion::sql::TableReference;
+use iceberg::arrow::schema_to_arrow_schema;
+use iceberg::io::FileIO;
+use iceberg::table::StaticTable;
+use iceberg::{Error, ErrorKind, Result, TableIdent};
+
+use super::IcebergTableProvider;
+use crate::to_datafusion_error;
+
+#[derive(Default)]
+#[non_exhaustive]
+pub struct IcebergTableProviderFactory {}
+
+impl IcebergTableProviderFactory {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+#[async_trait]
+impl TableProviderFactory for IcebergTableProviderFactory {
+    async fn create(
+        &self,
+        _state: &dyn Session,
+        cmd: &CreateExternalTable,
+    ) -> DFResult<Arc<dyn TableProvider>> {
+        check_cmd(cmd).map_err(to_datafusion_error)?;
+
+        let table_name = &cmd.name;
+        let metadata_file_path = &cmd.location;
+        let options = &cmd.options;
+
+        let table = create_static_table(table_name, metadata_file_path, options)
+            .await
+            .map_err(to_datafusion_error)?
+            .into_table();
+
+        let schema = schema_to_arrow_schema(table.metadata().current_schema())
+            .map_err(to_datafusion_error)?;
+
+        Ok(Arc::new(IcebergTableProvider::new(table, Arc::new(schema))))
+    }
+}
+
+fn check_cmd(cmd: &CreateExternalTable) -> Result<()> {
+    let CreateExternalTable {
+        schema,
+        table_partition_cols,
+        order_exprs,
+        constraints,
+        column_defaults,
+        ..
+    } = cmd;
+
+    if !schema.fields().is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Schema specification is not supported",
+        ));
+    }
+
+    if !table_partition_cols.is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Partition columns cannot be specified",
+        ));
+    }
+
+    if !order_exprs.is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Ordering clause is not supported",
+        ));
+    }
+
+    if !constraints.is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Constraints are not supported",
+        ));
+    }
+
+    if !column_defaults.is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Default values for columns are not supported",
+        ));
+    }
+
+    Ok(())
+}
+
+async fn create_static_table(
+    table_name: &TableReference,
+    metadata_file_path: &str,
+    props: &HashMap<String, String>,
+) -> Result<StaticTable> {
+    let table_ident = TableIdent::from_strs(table_name.to_vec())?;
+    let file_io = FileIO::from_path(metadata_file_path)?
+        .with_props(props)
+        .build()?;
+    StaticTable::from_metadata_file(metadata_file_path, table_ident, file_io).await
+}
+
+#[cfg(test)]
+mod tests {
+
+    use datafusion::catalog::TableProviderFactory;
+    use datafusion::common::{Constraints, DFSchema};
+    use datafusion::logical_expr::CreateExternalTable;
+    use datafusion::prelude::SessionContext;
+    use datafusion::sql::TableReference;
+
+    use super::*;
+
+    #[tokio::test]
+    async fn test_schema_of_created_table() {
+        let factory = IcebergTableProviderFactory::new();
+
+        let metadata_file_path = format!(
+            "{}/testdata/table_metadata/{}",
+            env!("CARGO_MANIFEST_DIR"),
+            "TableMetadataV2.json"
+        );
+
+        let cmd = CreateExternalTable {
+            name: TableReference::partial("static_ns", "static_table"),
+            location: metadata_file_path,
+            schema: Arc::new(DFSchema::empty()),
+            file_type: "iceberg".to_string(),
+            options: Default::default(),
+            table_partition_cols: Default::default(),
+            order_exprs: Default::default(),
+            constraints: Constraints::empty(),
+            column_defaults: Default::default(),
+            if_not_exists: Default::default(),
+            definition: Default::default(),
+            unbounded: Default::default(),
+        };
+
+        let ctx = SessionContext::new();
+        let state = ctx.state();
+        let table_provider = factory
+            .create(&state, &cmd)
+            .await
+            .expect("create table failed");
+
+        // Field { name: "x", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {"PARQUET:field_id": "1"} },
+        // Field { name: "y", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {"PARQUET:field_id": "2"} },
+        // Field { name: "z", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {"PARQUET:field_id": "3"} }
+        let actual_schema = table_provider.schema();
+        let expected_schema_str = "Field { name: \"x\", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {\"PARQUET:field_id\": \"1\"} }, Field { name: \"y\", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {\"PARQUET:field_id\": \"2\"} }, Field { name: \"z\", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {\"PARQUET:field_id\": \"3\"} }";

Review Comment:
   sounds good



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "yukkit (via GitHub)" <gi...@apache.org>.
yukkit commented on code in PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#discussion_r1747927449


##########
crates/integrations/datafusion/src/table/table_provider_factory.rs:
##########
@@ -0,0 +1,180 @@
+// 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::collections::HashMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use datafusion::catalog::{Session, TableProvider, TableProviderFactory};
+use datafusion::error::Result as DFResult;
+use datafusion::logical_expr::CreateExternalTable;
+use datafusion::sql::TableReference;
+use iceberg::arrow::schema_to_arrow_schema;
+use iceberg::io::FileIO;
+use iceberg::table::StaticTable;
+use iceberg::{Error, ErrorKind, Result, TableIdent};
+
+use super::IcebergTableProvider;
+use crate::to_datafusion_error;
+
+#[derive(Default)]
+#[non_exhaustive]
+pub struct IcebergTableProviderFactory {}
+
+impl IcebergTableProviderFactory {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+#[async_trait]
+impl TableProviderFactory for IcebergTableProviderFactory {
+    async fn create(
+        &self,
+        _state: &dyn Session,
+        cmd: &CreateExternalTable,
+    ) -> DFResult<Arc<dyn TableProvider>> {
+        check_cmd(cmd).map_err(to_datafusion_error)?;
+
+        let table_name = &cmd.name;
+        let metadata_file_path = &cmd.location;
+        let options = &cmd.options;
+
+        let table = create_static_table(table_name, metadata_file_path, options)
+            .await
+            .map_err(to_datafusion_error)?
+            .into_table();
+
+        let schema = schema_to_arrow_schema(table.metadata().current_schema())
+            .map_err(to_datafusion_error)?;
+
+        Ok(Arc::new(IcebergTableProvider::new(table, Arc::new(schema))))
+    }
+}
+
+fn check_cmd(cmd: &CreateExternalTable) -> Result<()> {
+    let CreateExternalTable {
+        schema,
+        table_partition_cols,
+        order_exprs,
+        constraints,
+        column_defaults,
+        ..
+    } = cmd;
+
+    if !schema.fields().is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Schema specification is not supported",
+        ));
+    }
+
+    if !table_partition_cols.is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Partition columns cannot be specified",

Review Comment:
   Ok, I roughly understand your intention. First, inform the user that external tables currently only support read operations, but this doesn't mean write operations won't be supported in the future. Secondly, provide a method for creating a new table.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "liurenjie1024 (via GitHub)" <gi...@apache.org>.
liurenjie1024 commented on PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#issuecomment-2408470892

   > remind @liurenjie1024
   
   Sorry for late reply, would you mind to fix comments and resolve conflicts?


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "yukkit (via GitHub)" <gi...@apache.org>.
yukkit commented on PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#issuecomment-2342515435

   @liurenjie1024  Please help review the PR again when you get a chance


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "liurenjie1024 (via GitHub)" <gi...@apache.org>.
liurenjie1024 commented on PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#issuecomment-2451839743

   Thanks @yukkit for this pr!


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "yukkit (via GitHub)" <gi...@apache.org>.
yukkit commented on PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#issuecomment-2378319330

   remind @liurenjie1024 


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "liurenjie1024 (via GitHub)" <gi...@apache.org>.
liurenjie1024 commented on code in PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#discussion_r1746464932


##########
crates/integrations/datafusion/src/table/table_provider_factory.rs:
##########
@@ -0,0 +1,180 @@
+// 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::collections::HashMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use datafusion::catalog::{Session, TableProvider, TableProviderFactory};
+use datafusion::error::Result as DFResult;
+use datafusion::logical_expr::CreateExternalTable;
+use datafusion::sql::TableReference;
+use iceberg::arrow::schema_to_arrow_schema;
+use iceberg::io::FileIO;
+use iceberg::table::StaticTable;
+use iceberg::{Error, ErrorKind, Result, TableIdent};
+
+use super::IcebergTableProvider;
+use crate::to_datafusion_error;
+
+#[derive(Default)]
+#[non_exhaustive]
+pub struct IcebergTableProviderFactory {}
+
+impl IcebergTableProviderFactory {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+#[async_trait]
+impl TableProviderFactory for IcebergTableProviderFactory {
+    async fn create(
+        &self,
+        _state: &dyn Session,
+        cmd: &CreateExternalTable,
+    ) -> DFResult<Arc<dyn TableProvider>> {
+        check_cmd(cmd).map_err(to_datafusion_error)?;
+
+        let table_name = &cmd.name;
+        let metadata_file_path = &cmd.location;
+        let options = &cmd.options;
+
+        let table = create_static_table(table_name, metadata_file_path, options)
+            .await
+            .map_err(to_datafusion_error)?
+            .into_table();
+
+        let schema = schema_to_arrow_schema(table.metadata().current_schema())
+            .map_err(to_datafusion_error)?;
+
+        Ok(Arc::new(IcebergTableProvider::new(table, Arc::new(schema))))
+    }
+}
+
+fn check_cmd(cmd: &CreateExternalTable) -> Result<()> {
+    let CreateExternalTable {
+        schema,
+        table_partition_cols,
+        order_exprs,
+        constraints,
+        column_defaults,
+        ..
+    } = cmd;
+
+    if !schema.fields().is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Schema specification is not supported",
+        ));
+    }
+
+    if !table_partition_cols.is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Partition columns cannot be specified",
+        ));
+    }
+
+    if !order_exprs.is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Ordering clause is not supported",
+        ));
+    }
+
+    if !constraints.is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Constraints are not supported",
+        ));
+    }
+
+    if !column_defaults.is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Default values for columns are not supported",
+        ));
+    }
+
+    Ok(())
+}
+
+async fn create_static_table(
+    table_name: &TableReference,
+    metadata_file_path: &str,
+    props: &HashMap<String, String>,
+) -> Result<StaticTable> {
+    let table_ident = TableIdent::from_strs(table_name.to_vec())?;
+    let file_io = FileIO::from_path(metadata_file_path)?
+        .with_props(props)
+        .build()?;
+    StaticTable::from_metadata_file(metadata_file_path, table_ident, file_io).await
+}
+
+#[cfg(test)]
+mod tests {
+
+    use datafusion::catalog::TableProviderFactory;
+    use datafusion::common::{Constraints, DFSchema};
+    use datafusion::logical_expr::CreateExternalTable;
+    use datafusion::prelude::SessionContext;
+    use datafusion::sql::TableReference;
+
+    use super::*;
+
+    #[tokio::test]
+    async fn test_schema_of_created_table() {
+        let factory = IcebergTableProviderFactory::new();
+
+        let metadata_file_path = format!(
+            "{}/testdata/table_metadata/{}",
+            env!("CARGO_MANIFEST_DIR"),
+            "TableMetadataV2.json"
+        );
+
+        let cmd = CreateExternalTable {
+            name: TableReference::partial("static_ns", "static_table"),
+            location: metadata_file_path,
+            schema: Arc::new(DFSchema::empty()),
+            file_type: "iceberg".to_string(),
+            options: Default::default(),
+            table_partition_cols: Default::default(),
+            order_exprs: Default::default(),
+            constraints: Constraints::empty(),
+            column_defaults: Default::default(),
+            if_not_exists: Default::default(),
+            definition: Default::default(),
+            unbounded: Default::default(),
+        };
+
+        let ctx = SessionContext::new();
+        let state = ctx.state();
+        let table_provider = factory
+            .create(&state, &cmd)
+            .await
+            .expect("create table failed");
+
+        // Field { name: "x", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {"PARQUET:field_id": "1"} },
+        // Field { name: "y", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {"PARQUET:field_id": "2"} },
+        // Field { name: "z", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {"PARQUET:field_id": "3"} }
+        let actual_schema = table_provider.schema();
+        let expected_schema_str = "Field { name: \"x\", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {\"PARQUET:field_id\": \"1\"} }, Field { name: \"y\", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {\"PARQUET:field_id\": \"2\"} }, Field { name: \"z\", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {\"PARQUET:field_id\": \"3\"} }";

Review Comment:
   Pure format string comparison doesn't sound like a good idea to me. It would be better to use schema builder api to create schema and compare them.



##########
crates/integrations/datafusion/src/table/table_provider_factory.rs:
##########
@@ -0,0 +1,180 @@
+// 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::collections::HashMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use datafusion::catalog::{Session, TableProvider, TableProviderFactory};
+use datafusion::error::Result as DFResult;
+use datafusion::logical_expr::CreateExternalTable;
+use datafusion::sql::TableReference;
+use iceberg::arrow::schema_to_arrow_schema;
+use iceberg::io::FileIO;
+use iceberg::table::StaticTable;
+use iceberg::{Error, ErrorKind, Result, TableIdent};
+
+use super::IcebergTableProvider;
+use crate::to_datafusion_error;
+
+#[derive(Default)]
+#[non_exhaustive]
+pub struct IcebergTableProviderFactory {}
+
+impl IcebergTableProviderFactory {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+#[async_trait]
+impl TableProviderFactory for IcebergTableProviderFactory {
+    async fn create(
+        &self,
+        _state: &dyn Session,
+        cmd: &CreateExternalTable,
+    ) -> DFResult<Arc<dyn TableProvider>> {
+        check_cmd(cmd).map_err(to_datafusion_error)?;
+
+        let table_name = &cmd.name;
+        let metadata_file_path = &cmd.location;
+        let options = &cmd.options;
+
+        let table = create_static_table(table_name, metadata_file_path, options)
+            .await
+            .map_err(to_datafusion_error)?
+            .into_table();
+
+        let schema = schema_to_arrow_schema(table.metadata().current_schema())
+            .map_err(to_datafusion_error)?;
+
+        Ok(Arc::new(IcebergTableProvider::new(table, Arc::new(schema))))
+    }
+}
+
+fn check_cmd(cmd: &CreateExternalTable) -> Result<()> {
+    let CreateExternalTable {
+        schema,
+        table_partition_cols,
+        order_exprs,
+        constraints,
+        column_defaults,
+        ..
+    } = cmd;
+
+    if !schema.fields().is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Schema specification is not supported",
+        ));
+    }
+
+    if !table_partition_cols.is_empty() {
+        return Err(Error::new(
+            ErrorKind::FeatureUnsupported,
+            "Partition columns cannot be specified",

Review Comment:
   Instead of returning different errors for each check, I think a more appropriate message would be like 
   ```
   Currently we only support reading existing icebergs tables in external table command. To create new table, please use catalog provider.
   ```



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "yukkit (via GitHub)" <gi...@apache.org>.
yukkit commented on code in PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#discussion_r1747928274


##########
crates/integrations/datafusion/src/table/table_provider_factory.rs:
##########
@@ -0,0 +1,180 @@
+// 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::collections::HashMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use datafusion::catalog::{Session, TableProvider, TableProviderFactory};
+use datafusion::error::Result as DFResult;
+use datafusion::logical_expr::CreateExternalTable;
+use datafusion::sql::TableReference;
+use iceberg::arrow::schema_to_arrow_schema;
+use iceberg::io::FileIO;
+use iceberg::table::StaticTable;
+use iceberg::{Error, ErrorKind, Result, TableIdent};
+
+use super::IcebergTableProvider;
+use crate::to_datafusion_error;
+
+#[derive(Default)]
+#[non_exhaustive]
+pub struct IcebergTableProviderFactory {}

Review Comment:
   Alright, I will add doc for it



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "liurenjie1024 (via GitHub)" <gi...@apache.org>.
liurenjie1024 commented on code in PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#discussion_r1797634121


##########
crates/integrations/datafusion/src/table/table_provider_factory.rs:
##########
@@ -0,0 +1,301 @@
+// 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::borrow::Cow;
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use datafusion::catalog::{Session, TableProvider, TableProviderFactory};
+use datafusion::error::Result as DFResult;
+use datafusion::logical_expr::CreateExternalTable;
+use datafusion::sql::TableReference;
+use iceberg::arrow::schema_to_arrow_schema;
+use iceberg::io::FileIO;
+use iceberg::table::StaticTable;
+use iceberg::{Error, ErrorKind, Result, TableIdent};
+
+use super::IcebergTableProvider;
+use crate::to_datafusion_error;
+
+/// A factory that implements DataFusion's `TableProviderFactory` to create `IcebergTableProvider` instances.
+///
+/// # Example
+///
+/// The following example demonstrates how to create an Iceberg external table using SQL in
+/// a DataFusion session with `IcebergTableProviderFactory`:
+///
+/// ```
+/// use std::sync::Arc;
+///
+/// use datafusion::execution::session_state::SessionStateBuilder;
+/// use datafusion::prelude::*;
+/// use datafusion::sql::TableReference;
+/// use iceberg_datafusion::IcebergTableProviderFactory;
+///
+/// #[tokio::main]
+/// async fn main() {
+///     // Create a new session context
+///     let mut state = SessionStateBuilder::new().with_default_features().build();
+///
+///     // Register the IcebergTableProviderFactory in the session
+///     state.table_factories_mut().insert(
+///         "ICEBERG".to_string(),
+///         Arc::new(IcebergTableProviderFactory::new()),
+///     );
+///
+///     let ctx = SessionContext::new_with_state(state);
+///
+///     // Define the table reference and the location of the Iceberg metadata file
+///     let table_ref = TableReference::bare("my_iceberg_table");
+///     // /path/to/iceberg/metadata
+///     let metadata_file_path = format!(
+///         "{}/testdata/table_metadata/{}",
+///         env!("CARGO_MANIFEST_DIR"),
+///         "TableMetadataV2.json"
+///     );
+///
+///     // SQL command to create the Iceberg external table
+///     let sql = format!(
+///         "CREATE EXTERNAL TABLE {} STORED AS ICEBERG LOCATION '{}'",
+///         table_ref, metadata_file_path
+///     );
+///
+///     // Execute the SQL to create the external table
+///     ctx.sql(&sql).await.expect("Failed to create table");
+///
+///     // Verify the table was created by retrieving the table provider
+///     let table_provider = ctx
+///         .table_provider(table_ref)
+///         .await
+///         .expect("Table not found");
+///
+///     println!("Iceberg external table created successfully.");
+/// }
+/// ```
+///
+/// # Note
+/// This factory is designed to work with the DataFusion query engine,
+/// specifically for handling Iceberg tables in external table commands.
+/// Currently, this implementation supports only reading Iceberg tables, with
+/// the creation of new tables not yet available.
+///
+/// # Errors
+/// An error will be returned if any unsupported feature, such as partition columns,
+/// order expressions, constraints, or column defaults, is detected in the table creation command.
+#[derive(Default)]
+#[non_exhaustive]

Review Comment:
   Sorry, I don't quite understand why we need to add this annotation here?



##########
crates/integrations/datafusion/src/table/table_provider_factory.rs:
##########
@@ -0,0 +1,312 @@
+// 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::borrow::Cow;
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use datafusion::catalog::{Session, TableProvider, TableProviderFactory};
+use datafusion::error::Result as DFResult;
+use datafusion::logical_expr::CreateExternalTable;
+use datafusion::sql::TableReference;
+use iceberg::arrow::schema_to_arrow_schema;
+use iceberg::io::FileIO;
+use iceberg::table::StaticTable;
+use iceberg::{Error, ErrorKind, Result, TableIdent};
+
+use super::IcebergTableProvider;
+use crate::to_datafusion_error;
+
+/// A factory that implements DataFusion's `TableProviderFactory` to create `IcebergTableProvider` instances.
+///
+/// # Example
+///
+/// The following example demonstrates how to create an Iceberg external table using SQL in
+/// a DataFusion session with `IcebergTableProviderFactory`:
+///
+/// ```
+/// use std::sync::Arc;
+///
+/// use datafusion::prelude::*;
+/// use iceberg_datafusion::IcebergTableProviderFactory;
+///
+/// #[tokio::main]
+/// async fn main() {
+///     // Create a new session context
+///     let mut state = SessionStateBuilder::new().with_default_features().build();
+///
+///     // Register the IcebergTableProviderFactory in the session
+///     state.table_factories_mut().insert(
+///         "ICEBERG".to_string(),
+///         Arc::new(IcebergTableProviderFactory::new()),
+///     );
+///
+///     let ctx = SessionContext::new_with_state(state);
+///
+///     // Define the table reference and the location of the Iceberg metadata file
+///     let table_ref = TableReference::bare("my_iceberg_table");
+///     let metadata_file_path = "/path/to/iceberg/metadata";
+///
+///     // SQL command to create the Iceberg external table
+///     let sql = format!(
+///         "CREATE EXTERNAL TABLE {} STORED AS ICEBERG LOCATION '{}'",
+///         table_ref, metadata_file_path
+///     );
+///
+///     // Execute the SQL to create the external table
+///     ctx.sql(&sql).await.expect("Failed to create table");
+///
+///     // Verify the table was created by retrieving the table provider
+///     let table_provider = ctx
+///         .table_provider(table_ref)
+///         .await
+///         .expect("Table not found");
+///
+///     println!("Iceberg external table created successfully.");
+/// }
+/// ```
+///
+/// # Note
+/// This factory is designed to work with the DataFusion query engine,
+/// specifically for handling Iceberg tables in external table commands.
+/// Currently, this implementation supports only reading Iceberg tables, with
+/// the creation of new tables not yet available.
+///
+/// # Errors
+/// An error will be returned if any unsupported feature, such as partition columns,
+/// order expressions, constraints, or column defaults, is detected in the table creation command.
+#[derive(Default)]
+#[non_exhaustive]
+pub struct IcebergTableProviderFactory {}
+
+impl IcebergTableProviderFactory {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+#[async_trait]
+impl TableProviderFactory for IcebergTableProviderFactory {
+    async fn create(
+        &self,
+        _state: &dyn Session,
+        cmd: &CreateExternalTable,
+    ) -> DFResult<Arc<dyn TableProvider>> {
+        check_cmd(cmd).map_err(to_datafusion_error)?;
+
+        let table_name = &cmd.name;
+        let metadata_file_path = &cmd.location;
+        let options = &cmd.options;
+
+        let table_name_with_ns = complement_namespace_if_necessary(table_name);
+
+        let table = create_static_table(table_name_with_ns, metadata_file_path, options)
+            .await
+            .map_err(to_datafusion_error)?
+            .into_table();
+
+        let schema = schema_to_arrow_schema(table.metadata().current_schema())
+            .map_err(to_datafusion_error)?;
+
+        Ok(Arc::new(IcebergTableProvider::new(table, Arc::new(schema))))
+    }
+}
+
+fn check_cmd(cmd: &CreateExternalTable) -> Result<()> {
+    println!("Checking command: {:?}", cmd);
+
+    let CreateExternalTable {
+        schema,
+        table_partition_cols,
+        order_exprs,
+        constraints,
+        column_defaults,
+        ..
+    } = cmd;
+
+    // Check if any of the fields violate the constraints in a single condition
+    let is_invalid = !schema.fields().is_empty()
+        || !table_partition_cols.is_empty()
+        || !order_exprs.is_empty()
+        || !constraints.is_empty()
+        || !column_defaults.is_empty();
+
+    if is_invalid {
+        return Err(Error::new(ErrorKind::FeatureUnsupported, "Currently we only support reading existing icebergs tables in external table command. To create new table, please use catalog provider."));
+    }
+
+    Ok(())
+}
+
+/// Complements the namespace of a table name if necessary.
+///
+/// # Example
+///
+/// ```
+/// use datafusion::sql::TableReference;
+/// use iceberg_datafusion::complement_namespace_if_necessary;
+///
+/// let table_name = TableReference::bare("table_name");
+/// let table_name_with_ns = complement_namespace_if_necessary(&table_name);
+///
+/// assert_eq!(
+///     table_name_with_ns,
+///     TableReference::partial("default", "table_name")
+/// );
+/// ```
+///
+/// # Note
+/// If the table name is a bare name, it will be complemented with the 'default' namespace.
+/// Otherwise, it will be returned as is. Because Iceberg tables are always namespaced, but DataFusion
+/// external table commands not include the namespace, this function ensures that the namespace is always present.
+///
+/// # See also
+/// - [`iceberg::NamespaceIdent`]
+/// - [`datafusion::sql::planner::SqlToRel::external_table_to_plan`]
+fn complement_namespace_if_necessary(table_name: &TableReference) -> Cow<'_, TableReference> {
+    match table_name {
+        TableReference::Bare { table } => {
+            Cow::Owned(TableReference::partial("default", table.as_ref()))
+        }
+        other => Cow::Borrowed(other),
+    }
+}

Review Comment:
   > Does anyone have a good approach for handling compatibility?
   
   I'm not quite familiar with datafusion, but typicall it should be registered with current namespace? For example, a  user has executed `use ns1` before registering this table, then ideally this table should be register under `ns1`?



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "yukkit (via GitHub)" <gi...@apache.org>.
yukkit commented on code in PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600#discussion_r1777112888


##########
crates/integrations/datafusion/src/table/table_provider_factory.rs:
##########
@@ -0,0 +1,312 @@
+// 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::borrow::Cow;
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use datafusion::catalog::{Session, TableProvider, TableProviderFactory};
+use datafusion::error::Result as DFResult;
+use datafusion::logical_expr::CreateExternalTable;
+use datafusion::sql::TableReference;
+use iceberg::arrow::schema_to_arrow_schema;
+use iceberg::io::FileIO;
+use iceberg::table::StaticTable;
+use iceberg::{Error, ErrorKind, Result, TableIdent};
+
+use super::IcebergTableProvider;
+use crate::to_datafusion_error;
+
+/// A factory that implements DataFusion's `TableProviderFactory` to create `IcebergTableProvider` instances.
+///
+/// # Example
+///
+/// The following example demonstrates how to create an Iceberg external table using SQL in
+/// a DataFusion session with `IcebergTableProviderFactory`:
+///
+/// ```
+/// use std::sync::Arc;
+///
+/// use datafusion::prelude::*;
+/// use iceberg_datafusion::IcebergTableProviderFactory;
+///
+/// #[tokio::main]
+/// async fn main() {
+///     // Create a new session context
+///     let mut state = SessionStateBuilder::new().with_default_features().build();
+///
+///     // Register the IcebergTableProviderFactory in the session
+///     state.table_factories_mut().insert(
+///         "ICEBERG".to_string(),
+///         Arc::new(IcebergTableProviderFactory::new()),
+///     );
+///
+///     let ctx = SessionContext::new_with_state(state);
+///
+///     // Define the table reference and the location of the Iceberg metadata file
+///     let table_ref = TableReference::bare("my_iceberg_table");
+///     let metadata_file_path = "/path/to/iceberg/metadata";
+///
+///     // SQL command to create the Iceberg external table
+///     let sql = format!(
+///         "CREATE EXTERNAL TABLE {} STORED AS ICEBERG LOCATION '{}'",
+///         table_ref, metadata_file_path
+///     );
+///
+///     // Execute the SQL to create the external table
+///     ctx.sql(&sql).await.expect("Failed to create table");
+///
+///     // Verify the table was created by retrieving the table provider
+///     let table_provider = ctx
+///         .table_provider(table_ref)
+///         .await
+///         .expect("Table not found");
+///
+///     println!("Iceberg external table created successfully.");
+/// }
+/// ```
+///
+/// # Note
+/// This factory is designed to work with the DataFusion query engine,
+/// specifically for handling Iceberg tables in external table commands.
+/// Currently, this implementation supports only reading Iceberg tables, with
+/// the creation of new tables not yet available.
+///
+/// # Errors
+/// An error will be returned if any unsupported feature, such as partition columns,
+/// order expressions, constraints, or column defaults, is detected in the table creation command.
+#[derive(Default)]
+#[non_exhaustive]
+pub struct IcebergTableProviderFactory {}
+
+impl IcebergTableProviderFactory {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+#[async_trait]
+impl TableProviderFactory for IcebergTableProviderFactory {
+    async fn create(
+        &self,
+        _state: &dyn Session,
+        cmd: &CreateExternalTable,
+    ) -> DFResult<Arc<dyn TableProvider>> {
+        check_cmd(cmd).map_err(to_datafusion_error)?;
+
+        let table_name = &cmd.name;
+        let metadata_file_path = &cmd.location;
+        let options = &cmd.options;
+
+        let table_name_with_ns = complement_namespace_if_necessary(table_name);
+
+        let table = create_static_table(table_name_with_ns, metadata_file_path, options)
+            .await
+            .map_err(to_datafusion_error)?
+            .into_table();
+
+        let schema = schema_to_arrow_schema(table.metadata().current_schema())
+            .map_err(to_datafusion_error)?;
+
+        Ok(Arc::new(IcebergTableProvider::new(table, Arc::new(schema))))
+    }
+}
+
+fn check_cmd(cmd: &CreateExternalTable) -> Result<()> {
+    println!("Checking command: {:?}", cmd);
+
+    let CreateExternalTable {
+        schema,
+        table_partition_cols,
+        order_exprs,
+        constraints,
+        column_defaults,
+        ..
+    } = cmd;
+
+    // Check if any of the fields violate the constraints in a single condition
+    let is_invalid = !schema.fields().is_empty()
+        || !table_partition_cols.is_empty()
+        || !order_exprs.is_empty()
+        || !constraints.is_empty()
+        || !column_defaults.is_empty();
+
+    if is_invalid {
+        return Err(Error::new(ErrorKind::FeatureUnsupported, "Currently we only support reading existing icebergs tables in external table command. To create new table, please use catalog provider."));
+    }
+
+    Ok(())
+}
+
+/// Complements the namespace of a table name if necessary.
+///
+/// # Example
+///
+/// ```
+/// use datafusion::sql::TableReference;
+/// use iceberg_datafusion::complement_namespace_if_necessary;
+///
+/// let table_name = TableReference::bare("table_name");
+/// let table_name_with_ns = complement_namespace_if_necessary(&table_name);
+///
+/// assert_eq!(
+///     table_name_with_ns,
+///     TableReference::partial("default", "table_name")
+/// );
+/// ```
+///
+/// # Note
+/// If the table name is a bare name, it will be complemented with the 'default' namespace.
+/// Otherwise, it will be returned as is. Because Iceberg tables are always namespaced, but DataFusion
+/// external table commands not include the namespace, this function ensures that the namespace is always present.
+///
+/// # See also
+/// - [`iceberg::NamespaceIdent`]
+/// - [`datafusion::sql::planner::SqlToRel::external_table_to_plan`]
+fn complement_namespace_if_necessary(table_name: &TableReference) -> Cow<'_, TableReference> {
+    match table_name {
+        TableReference::Bare { table } => {
+            Cow::Owned(TableReference::partial("default", table.as_ref()))
+        }
+        other => Cow::Borrowed(other),
+    }
+}

Review Comment:
   @matthewmturner I believe this is a known issue, see https://github.com/apache/datafusion/blob/main/datafusion/sql/src/statement.rs#L1242



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] feat: implement IcebergTableProviderFactory for datafusion [iceberg-rust]

Posted by "liurenjie1024 (via GitHub)" <gi...@apache.org>.
liurenjie1024 merged PR #600:
URL: https://github.com/apache/iceberg-rust/pull/600


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org