Skip to content

Commit a12007b

Browse files
committed
[substrait] Add support for ExtensionTable
1 parent 668984e commit a12007b

4 files changed

Lines changed: 199 additions & 37 deletions

File tree

datafusion/core/src/execution/context/mod.rs

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ use datafusion_expr::{
6363
expr_rewriter::FunctionRewrite,
6464
logical_plan::{DdlStatement, Statement},
6565
planner::ExprPlanner,
66-
Expr, UserDefinedLogicalNode, WindowUDF,
66+
Expr, WindowUDF,
6767
};
6868

6969
// backwards compatibility
@@ -1679,27 +1679,7 @@ pub enum RegisterFunction {
16791679
#[derive(Debug)]
16801680
pub struct EmptySerializerRegistry;
16811681

1682-
impl SerializerRegistry for EmptySerializerRegistry {
1683-
fn serialize_logical_plan(
1684-
&self,
1685-
node: &dyn UserDefinedLogicalNode,
1686-
) -> Result<Vec<u8>> {
1687-
not_impl_err!(
1688-
"Serializing user defined logical plan node `{}` is not supported",
1689-
node.name()
1690-
)
1691-
}
1692-
1693-
fn deserialize_logical_plan(
1694-
&self,
1695-
name: &str,
1696-
_bytes: &[u8],
1697-
) -> Result<Arc<dyn UserDefinedLogicalNode>> {
1698-
not_impl_err!(
1699-
"Deserializing user defined logical plan node `{name}` is not supported"
1700-
)
1701-
}
1702-
}
1682+
impl SerializerRegistry for EmptySerializerRegistry {}
17031683

17041684
/// Describes which SQL statements can be run.
17051685
///

datafusion/expr/src/registry.rs

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
2020
use crate::expr_rewriter::FunctionRewrite;
2121
use crate::planner::ExprPlanner;
22-
use crate::{AggregateUDF, ScalarUDF, UserDefinedLogicalNode, WindowUDF};
22+
use crate::{AggregateUDF, ScalarUDF, TableSource, UserDefinedLogicalNode, WindowUDF};
2323
use datafusion_common::{not_impl_err, plan_datafusion_err, HashMap, Result};
2424
use std::collections::HashSet;
2525
use std::fmt::Debug;
@@ -123,22 +123,52 @@ pub trait FunctionRegistry {
123123
}
124124
}
125125

126-
/// Serializer and deserializer registry for extensions like [UserDefinedLogicalNode].
126+
/// Serializer and deserializer registry for extensions like [UserDefinedLogicalNode]
127+
/// and custom table providers for which the name alone is meaningless in the target
128+
/// execution context, e.g. UDTFs, manually registered tables etc.
127129
pub trait SerializerRegistry: Debug + Send + Sync {
128130
/// Serialize this node to a byte array. This serialization should not include
129131
/// input plans.
130132
fn serialize_logical_plan(
131133
&self,
132134
node: &dyn UserDefinedLogicalNode,
133-
) -> Result<Vec<u8>>;
135+
) -> Result<Vec<u8>> {
136+
not_impl_err!(
137+
"Serializing user defined logical plan node `{}` is not supported",
138+
node.name()
139+
)
140+
}
134141

135142
/// Deserialize user defined logical plan node ([UserDefinedLogicalNode]) from
136143
/// bytes.
137144
fn deserialize_logical_plan(
138145
&self,
139146
name: &str,
140-
bytes: &[u8],
141-
) -> Result<Arc<dyn UserDefinedLogicalNode>>;
147+
_bytes: &[u8],
148+
) -> Result<Arc<dyn UserDefinedLogicalNode>> {
149+
not_impl_err!(
150+
"Deserializing user defined logical plan node `{name}` is not supported"
151+
)
152+
}
153+
154+
/// Serialized table definition for UDTFs or manually registered table providers that can't be
155+
/// marshaled by reference. Should return some benign error for regular tables that can be
156+
/// found/restored by name in the destination execution context.
157+
fn serialize_custom_table(&self, _table: &dyn TableSource) -> Result<Vec<u8>> {
158+
not_impl_err!("No custom table support")
159+
}
160+
161+
/// Deserialize the custom table with the given name.
162+
/// Note: more often than not, the name can't be used as a discriminator if multiple different
163+
/// `TableSource` and/or `TableProvider` implementations are expected (this is particularly true
164+
/// for UDTFs in DataFusion, which are always registered under the same name: `tmp_table`).
165+
fn deserialize_custom_table(
166+
&self,
167+
name: &str,
168+
_bytes: &[u8],
169+
) -> Result<Arc<dyn TableSource>> {
170+
not_impl_err!("Deserializing custom table `{name}` is not supported")
171+
}
142172
}
143173

144174
/// A [`FunctionRegistry`] that uses in memory [`HashMap`]s

datafusion/substrait/src/logical_plan/consumer.rs

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ use datafusion::logical_expr::expr::{Exists, InSubquery, Sort};
3131

3232
use datafusion::logical_expr::{
3333
Aggregate, BinaryExpr, Case, EmptyRelation, Expr, ExprSchemable, LogicalPlan,
34-
Operator, Projection, SortExpr, TryCast, Values,
34+
Operator, Projection, SortExpr, TableScan, TryCast, Values,
3535
};
3636
use substrait::proto::aggregate_rel::Grouping;
3737
use substrait::proto::expression::subquery::set_predicate::PredicateOp;
@@ -994,8 +994,34 @@ pub async fn from_substrait_rel(
994994
)
995995
.await
996996
}
997-
_ => {
998-
not_impl_err!("Unsupported ReadType: {:?}", &read.as_ref().read_type)
997+
Some(ReadType::ExtensionTable(ext)) => {
998+
if let Some(ext_detail) = &ext.detail {
999+
let source =
1000+
state.serializer_registry().deserialize_custom_table(
1001+
&ext_detail.type_url,
1002+
&ext_detail.value,
1003+
)?;
1004+
let table_name = ext_detail
1005+
.type_url
1006+
.rsplit_once('/')
1007+
.map(|(_, name)| name)
1008+
.unwrap_or(&ext_detail.type_url);
1009+
let plan = LogicalPlan::TableScan(TableScan::try_new(
1010+
table_name,
1011+
source,
1012+
None,
1013+
vec![],
1014+
None,
1015+
)?);
1016+
let schema = apply_masking(substrait_schema, &read.projection)?;
1017+
ensure_schema_compatability(plan.schema(), schema.clone())?;
1018+
apply_projection(plan, schema)
1019+
} else {
1020+
substrait_err!("Unexpected empty detail in ExtensionTable")
1021+
}
1022+
}
1023+
None => {
1024+
substrait_err!("Unexpected empty read_type")
9991025
}
10001026
}
10011027
}

datafusion/substrait/src/logical_plan/producer.rs

Lines changed: 133 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ use substrait::proto::expression::literal::{
6565
};
6666
use substrait::proto::expression::subquery::InPredicate;
6767
use substrait::proto::expression::window_function::BoundsType;
68-
use substrait::proto::read_rel::VirtualTable;
68+
use substrait::proto::read_rel::{ExtensionTable, VirtualTable};
6969
use substrait::proto::rel_common::EmitKind;
7070
use substrait::proto::rel_common::EmitKind::Emit;
7171
use substrait::proto::{
@@ -212,6 +212,23 @@ pub fn to_substrait_rel(
212212
let table_schema = scan.source.schema().to_dfschema_ref()?;
213213
let base_schema = to_substrait_named_struct(&table_schema)?;
214214

215+
let table = if let Ok(bytes) = state
216+
.serializer_registry()
217+
.serialize_custom_table(scan.source.as_ref())
218+
{
219+
ReadType::ExtensionTable(ExtensionTable {
220+
detail: Some(ProtoAny {
221+
type_url: scan.table_name.to_string(),
222+
value: bytes.into(),
223+
}),
224+
})
225+
} else {
226+
ReadType::NamedTable(NamedTable {
227+
names: scan.table_name.to_vec(),
228+
advanced_extension: None,
229+
})
230+
};
231+
215232
Ok(Box::new(Rel {
216233
rel_type: Some(RelType::Read(Box::new(ReadRel {
217234
common: None,
@@ -220,10 +237,7 @@ pub fn to_substrait_rel(
220237
best_effort_filter: None,
221238
projection,
222239
advanced_extension: None,
223-
read_type: Some(ReadType::NamedTable(NamedTable {
224-
names: scan.table_name.to_vec(),
225-
advanced_extension: None,
226-
})),
240+
read_type: Some(table),
227241
}))),
228242
}))
229243
}
@@ -2204,16 +2218,22 @@ mod test {
22042218
use super::*;
22052219
use crate::logical_plan::consumer::{
22062220
from_substrait_extended_expr, from_substrait_literal_without_names,
2207-
from_substrait_named_struct, from_substrait_type_without_names,
2221+
from_substrait_named_struct, from_substrait_plan,
2222+
from_substrait_type_without_names,
22082223
};
22092224
use arrow_buffer::{IntervalDayTime, IntervalMonthDayNano};
22102225
use datafusion::arrow::array::{
22112226
GenericListArray, Int64Builder, MapBuilder, StringBuilder,
22122227
};
22132228
use datafusion::arrow::datatypes::{Field, Fields, Schema};
22142229
use datafusion::common::scalar::ScalarStructBuilder;
2215-
use datafusion::common::DFSchema;
2230+
use datafusion::common::{assert_contains, DFSchema};
2231+
use datafusion::datasource::empty::EmptyTable;
2232+
use datafusion::datasource::{DefaultTableSource, TableProvider};
2233+
use datafusion::execution::registry::SerializerRegistry;
22162234
use datafusion::execution::SessionStateBuilder;
2235+
use datafusion::logical_expr::TableSource;
2236+
use datafusion::prelude::SessionContext;
22172237

22182238
#[test]
22192239
fn round_trip_literals() -> Result<()> {
@@ -2540,4 +2560,110 @@ mod test {
25402560

25412561
assert!(matches!(err, Err(DataFusionError::SchemaError(_, _))));
25422562
}
2563+
2564+
#[tokio::test]
2565+
async fn round_trip_extension_table() {
2566+
const TABLE_NAME: &str = "custom_table";
2567+
const SERIALIZED: &[u8] = "table definition".as_bytes();
2568+
2569+
fn custom_table() -> Arc<dyn TableProvider> {
2570+
Arc::new(EmptyTable::new(Arc::new(Schema::new([
2571+
Arc::new(Field::new("id", DataType::Int32, false)),
2572+
Arc::new(Field::new("name", DataType::Utf8, false)),
2573+
]))))
2574+
}
2575+
2576+
#[derive(Debug)]
2577+
struct Registry;
2578+
impl SerializerRegistry for Registry {
2579+
fn serialize_custom_table(&self, table: &dyn TableSource) -> Result<Vec<u8>> {
2580+
if table.schema() == custom_table().schema() {
2581+
Ok(SERIALIZED.to_vec())
2582+
} else {
2583+
Err(DataFusionError::Internal("Not our table".into()))
2584+
}
2585+
}
2586+
fn deserialize_custom_table(
2587+
&self,
2588+
name: &str,
2589+
bytes: &[u8],
2590+
) -> Result<Arc<dyn TableSource>> {
2591+
if name == TABLE_NAME && bytes == SERIALIZED {
2592+
Ok(Arc::new(DefaultTableSource::new(custom_table())))
2593+
} else {
2594+
panic!("Unexpected extension table: {name}");
2595+
}
2596+
}
2597+
}
2598+
2599+
async fn round_trip_logical_plans(
2600+
local: &SessionContext,
2601+
remote: &SessionContext,
2602+
) -> Result<()> {
2603+
local.register_table(TABLE_NAME, custom_table())?;
2604+
remote.table_provider(TABLE_NAME).await.expect_err(
2605+
"The remote context is not supposed to know about custom_table",
2606+
);
2607+
let initial_plan = local
2608+
.sql(&format!("select id from {TABLE_NAME}"))
2609+
.await?
2610+
.logical_plan()
2611+
.clone();
2612+
2613+
// write substrait locally
2614+
let substrait = to_substrait_plan(&initial_plan, &local.state())?;
2615+
2616+
// read substrait remotely
2617+
// since we know there's no `custom_table` registered in the remote context, this will only succeed
2618+
// if our table got encoded as an ExtensionTable and is now decoded back to a table source.
2619+
let restored = from_substrait_plan(&remote.state(), &substrait).await?;
2620+
assert_contains!(
2621+
// confirm that the Substrait plan contains our custom_table as an ExtensionTable
2622+
serde_json::to_string(substrait.as_ref()).unwrap(),
2623+
format!(r#""extensionTable":{{"detail":{{"typeUrl":"{TABLE_NAME}","#)
2624+
);
2625+
remote // make sure the restored plan is fully working in the remote context
2626+
.execute_logical_plan(restored.clone())
2627+
.await?
2628+
.collect()
2629+
.await
2630+
.expect("Restored plan cannot be executed remotely");
2631+
assert_eq!(
2632+
// check that the restored plan is functionally equivalent (and almost identical) to the initial one
2633+
initial_plan.to_string(),
2634+
restored.to_string().replace(
2635+
// substrait will add an explicit full-schema projection if the original table had none
2636+
&format!("TableScan: {TABLE_NAME} projection=[id, name]"),
2637+
&format!("TableScan: {TABLE_NAME}"),
2638+
)
2639+
);
2640+
Ok(())
2641+
}
2642+
2643+
// take 1
2644+
let failed_attempt =
2645+
round_trip_logical_plans(&SessionContext::new(), &SessionContext::new())
2646+
.await
2647+
.expect_err(
2648+
"The round trip should fail in the absence of a SerializerRegistry",
2649+
);
2650+
assert_contains!(
2651+
failed_attempt.message(),
2652+
format!("No table named '{TABLE_NAME}'")
2653+
);
2654+
2655+
// take 2
2656+
fn proper_context() -> SessionContext {
2657+
SessionContext::new_with_state(
2658+
SessionStateBuilder::new()
2659+
// This will transport our custom_table as a Substrait ExtensionTable
2660+
.with_serializer_registry(Arc::new(Registry))
2661+
.build(),
2662+
)
2663+
}
2664+
2665+
round_trip_logical_plans(&proper_context(), &proper_context())
2666+
.await
2667+
.expect("Local plan could not be restored remotely");
2668+
}
25432669
}

0 commit comments

Comments
 (0)