martin-g commented on code in PR #20222:
URL: https://github.com/apache/datafusion/pull/20222#discussion_r2781680944
##########
datafusion-examples/examples/udf/main.rs:
##########
Review Comment:
```suggestion
//! (file: simple_udwf.rs, desc: Simple UDWF example)
//!
//! - `table_list_udtf`
//! (file: table_list_udtf.rs, desc: Session-aware UDTF table list example)
```
##########
datafusion/ffi/src/udtf.rs:
##########
@@ -43,11 +45,18 @@ use crate::{df_result, rresult_return};
#[repr(C)]
#[derive(Debug, StableAbi)]
pub struct FFI_TableFunction {
- /// Equivalent to the `call` function of the TableFunctionImpl.
+ /// Equivalent to the [`TableFunctionImpl::call`].
/// The arguments are Expr passed as protobuf encoded bytes.
pub call:
unsafe extern "C" fn(udtf: &Self, args: RVec<u8>) ->
FFIResult<FFI_TableProvider>,
+ /// Equivalent to the [`TableFunctionImpl::call_with_args`].
+ call_with_args: unsafe extern "C" fn(
Review Comment:
The `call` field above is `pub`. Is it intentional that `call_with_args` is
private ?
##########
datafusion-examples/examples/udf/table_list_udtf.rs:
##########
@@ -0,0 +1,125 @@
+// 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.
+
+//! See `main.rs` for how to run it.
+
+use std::sync::{Arc, LazyLock};
+
+use arrow::array::{RecordBatch, StringArray};
+use arrow_schema::{DataType, Field, Schema, SchemaRef};
+use datafusion::{
+ catalog::{MemTable, TableFunctionArgs, TableFunctionImpl, TableProvider},
+ common::Result,
+ execution::SessionState,
+ prelude::SessionContext,
+};
+use datafusion_common::{DataFusionError, plan_err};
+use futures::executor::block_on;
+
+const FUNCTION_NAME: &str = "table_list";
+
+// The example shows, how to create UDTF that depends on the session state.
+// There is `table_list` UDTF is defined which returns list of tables within
session.
+
+pub async fn table_list_udtf() -> Result<()> {
+ let ctx = SessionContext::new();
+ ctx.register_udtf(FUNCTION_NAME, Arc::new(TableListUdtf));
+
+ // Register different kinds of tables.
+ ctx.sql("create view v as select 1")
+ .await?
+ .collect()
+ .await?;
+ ctx.sql("create table t(a int)").await?.collect().await?;
+
+ // Print results.
+ ctx.sql("select * from table_list()").await?.show().await?;
+
+ Ok(())
+}
+
+#[derive(Debug, Default)]
+struct TableListUdtf;
+
+static SCHEMA: LazyLock<SchemaRef> = LazyLock::new(|| {
+ SchemaRef::new(Schema::new(vec![
+ Field::new("catalog", DataType::Utf8, false),
+ Field::new("schema", DataType::Utf8, false),
+ Field::new("table", DataType::Utf8, false),
+ Field::new("type", DataType::Utf8, false),
+ ]))
+});
+
+impl TableFunctionImpl for TableListUdtf {
+ fn call_with_args(&self, args: TableFunctionArgs) -> Result<Arc<dyn
TableProvider>> {
+ if !args.args.is_empty() {
+ return plan_err!(
+ "{}: unexpected number of arguments: {}, expected: 0",
+ FUNCTION_NAME,
+ args.args.len()
+ );
+ }
+ let state = args
+ .session
+ .as_any()
+ .downcast_ref::<SessionState>()
+ .ok_or_else(|| {
+ DataFusionError::Internal("failed to downcast state".into())
+ })?;
+
+ let mut catalogs = vec![];
+ let mut schemas = vec![];
+ let mut tables = vec![];
+ let mut types = vec![];
+
+ let catalog_list = state.catalog_list();
+ for catalog_name in catalog_list.catalog_names() {
+ let Some(catalog) = catalog_list.catalog(&catalog_name) else {
+ continue;
+ };
+ for schema_name in catalog.schema_names() {
+ let Some(schema) = catalog.schema(&schema_name) else {
+ continue;
+ };
+ for table_name in schema.table_names() {
+ let Some(provider) = block_on(schema.table(&table_name))?
else {
Review Comment:
The example is executed inside Tokio runtime
(https://github.com/apache/datafusion/pull/20222/changes#diff-53dddc5b69b35049efec032575318a260c5538e27cef966ffe2e634c41d5e949R113),
so it will be better to use `Handle::current().block_on()` instead.
See https://docs.rs/tokio/latest/tokio/task/fn.block_in_place.html for an
example
##########
datafusion-examples/examples/udf/table_list_udtf.rs:
##########
@@ -0,0 +1,125 @@
+// 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.
+
+//! See `main.rs` for how to run it.
+
+use std::sync::{Arc, LazyLock};
+
+use arrow::array::{RecordBatch, StringArray};
+use arrow_schema::{DataType, Field, Schema, SchemaRef};
+use datafusion::{
+ catalog::{MemTable, TableFunctionArgs, TableFunctionImpl, TableProvider},
+ common::Result,
+ execution::SessionState,
+ prelude::SessionContext,
+};
+use datafusion_common::{DataFusionError, plan_err};
+use futures::executor::block_on;
+
+const FUNCTION_NAME: &str = "table_list";
+
+// The example shows, how to create UDTF that depends on the session state.
+// There is `table_list` UDTF is defined which returns list of tables within
session.
Review Comment:
```suggestion
// Defines a `table_list` UDTF that returns a list of tables within the
provided session.
```
--
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]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]