diff --git a/datafusion-examples/README.md b/datafusion-examples/README.md index 737fcddc6c556..fc235b5611443 100644 --- a/datafusion-examples/README.md +++ b/datafusion-examples/README.md @@ -155,11 +155,12 @@ cargo run --example dataframe -- dataframe #### Category: Single Process -| Subcommand | File Path | Description | -| ------------------------ | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | -| composed_extension_codec | [`proto/composed_extension_codec.rs`](examples/proto/composed_extension_codec.rs) | Use multiple extension codecs for serialization/deserialization | -| expression_deduplication | [`proto/expression_deduplication.rs`](examples/proto/expression_deduplication.rs) | Example of expression caching/deduplication using the codec decorator pattern | -| extension_plan_registry | [`proto/extension_plan_registry.rs`](examples/proto/extension_plan_registry.rs) | Decode two crates' extension plans by name, with no composed codec | +| Subcommand | File Path | Description | +| ------------------------ | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| composed_extension_codec | [`proto/composed_extension_codec.rs`](examples/proto/composed_extension_codec.rs) | Use multiple extension codecs for serialization/deserialization | +| expression_deduplication | [`proto/expression_deduplication.rs`](examples/proto/expression_deduplication.rs) | Example of expression caching/deduplication using the codec decorator pattern | +| extension_crate | [`proto/extension_crate.rs`](examples/proto/extension_crate.rs) | Recommended path. A crate whose custom expression, plan, file source and UDF serialize, with one function that registers them | +| extension_plan_registry | [`proto/extension_plan_registry.rs`](examples/proto/extension_plan_registry.rs) | Decode two crates' extension plans by name, with no composed codec | ## Query Planning Examples diff --git a/datafusion-examples/examples/proto/extension_crate.rs b/datafusion-examples/examples/proto/extension_crate.rs new file mode 100644 index 0000000000000..e13600cb9ca10 --- /dev/null +++ b/datafusion-examples/examples/proto/extension_crate.rs @@ -0,0 +1,624 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! See `main.rs` for how to run it. +//! +//! This example shows how to write an extension crate whose extensions can be +//! serialized and sent across the network in a distributed system. +//! +//! The [`numbers_crate`] module stands in for that crate. It provides: +//! +//! 1. A custom `PhysicalExpr`: [`numbers_crate::ScaleExpr`] +//! 2. A custom `ExecutionPlan`: [`numbers_crate::RepeatExec`] +//! 3. A custom `FileSource`: [`numbers_crate::NumbersSource`] +//! 4. A scalar UDF: `numbers_square` +//! 5. One function, [`numbers_crate::register_all`], that registers all of +//! the above in a session +//! +//! The coordinator builds this plan, serializes it, and sends the bytes to a +//! worker: +//! +//! ```text +//! RepeatExec: times=2 <- custom ExecutionPlan +//! ProjectionExec <- built-in plan +//! ScaleExpr(value) <- custom PhysicalExpr +//! numbers_square(value) <- scalar UDF +//! DataSourceExec, FileScanConfig <- built-in, DataFusion serializes them +//! NumbersSource <- custom FileSource +//! ``` +//! +//! | Kind | Encode | Decode | +//! |------------------------------------------------|-------------------------------------|-----------------------------------------------| +//! | `PhysicalExpr`, `ExecutionPlan`, `FileSource` | The type writes its name and state | The decoder registered under that name | +//! | Scalar UDF | DataFusion writes the function name | The function registered under that name | +//! +//! Only the decoding side registers anything, so the worker calls +//! `register_all` and the coordinator does not have to. +//! +//! This example covers physical plans. It does not cover logical plans, or +//! functions that carry state of their own beyond their name. + +use std::sync::Arc; + +use bytes::Bytes; +use datafusion::arrow::array::{Int64Array, RecordBatch}; +use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use datafusion::common::{Result, assert_batches_eq}; +use datafusion::physical_plan::{ExecutionPlan, collect, displayable}; +use datafusion::prelude::SessionContext; +use datafusion_proto::bytes::{physical_plan_from_bytes, physical_plan_to_bytes}; + +pub async fn extension_crate() -> Result<()> { + let dir = tempfile::tempdir()?; + let path = dir.path().join("data.numbers"); + std::fs::write(&path, "1\n2\n3\n")?; + let file_size = std::fs::metadata(&path)?.len(); + + // The bytes are the only thing that the coordinator and the worker share. + let bytes = coordinator(path.to_str().unwrap(), file_size)?; + let batches = worker(&bytes).await?; + + assert_batches_eq!( + [ + "+--------+---------+", + "| scaled | squared |", + "+--------+---------+", + "| 10 | 1 |", + "| 20 | 4 |", + "| 30 | 9 |", + "| 10 | 1 |", + "| 20 | 4 |", + "| 30 | 9 |", + "+--------+---------+", + ], + &batches + ); + Ok(()) +} + +/// Builds a plan from the crate's types and serializes it. +/// +/// Each type encodes itself through its own `try_to_proto*` method, so the +/// coordinator registers nothing. +fn coordinator(path: &str, file_size: u64) -> Result { + let plan = numbers_crate::scaled_squared_and_repeated(path, file_size)?; + let bytes = physical_plan_to_bytes(Arc::clone(&plan))?; + println!( + "Serialized this plan to {} bytes:\n{}", + bytes.len(), + displayable(plan.as_ref()).indent(true) + ); + Ok(bytes) +} + +/// Decodes the plan and runs it. +/// +/// `register_all` is the only thing that the worker has to know about the +/// crate. +async fn worker(bytes: &[u8]) -> Result> { + let ctx = SessionContext::new(); + numbers_crate::register_all(&ctx)?; + + let plan = physical_plan_from_bytes(bytes, ctx.task_ctx().as_ref())?; + collect(plan, ctx.task_ctx()).await +} + +fn numbers_schema() -> SchemaRef { + Arc::new(Schema::new(vec![Field::new( + "value", + DataType::Int64, + false, + )])) +} + +/// What a crate outside DataFusion would publish. +mod numbers_crate { + use std::fmt::{self, Display, Formatter}; + use std::hash::{Hash, Hasher}; + + use datafusion::arrow::compute::kernels::numeric::mul; + use datafusion::common::config::ConfigOptions; + use datafusion::common::tree_node::TreeNodeRecursion; + use datafusion::common::{exec_datafusion_err, internal_err}; + use datafusion::datasource::file::ExtensionFileSourceFromProto; + use datafusion::datasource::listing::PartitionedFile; + use datafusion::datasource::object_store::ObjectStoreUrl; + use datafusion::datasource::physical_plan::{ + FileGroup, FileOpenFuture, FileOpener, FileScanConfig, FileScanConfigBuilder, + FileSource, + }; + use datafusion::datasource::source::DataSourceExec; + use datafusion::datasource::table_schema::TableSchema; + use datafusion::execution::{SendableRecordBatchStream, TaskContext}; + use datafusion::logical_expr::{ColumnarValue, ScalarUDF, Volatility, create_udf}; + use datafusion::physical_expr::{ + EquivalenceProperties, PhysicalExpr, ScalarFunctionExpr, + }; + use datafusion::physical_plan::expressions::col; + use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet; + use datafusion::physical_plan::projection::ProjectionExec; + use datafusion::physical_plan::proto::{ + ExecutionPlanDecodeCtx, ExecutionPlanEncodeCtx, ExtensionExprFromProto, + ExtensionPlanFromProto, PhysicalExprDecodeCtx, PhysicalExprEncodeCtx, + ProtoDecoderRegistry, extension_expr_node, + }; + use datafusion::physical_plan::stream::RecordBatchStreamAdapter; + use datafusion::physical_plan::{ + ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlanProperties, + PlanProperties, ReplaceChildrenOptions, + }; + use datafusion_proto::protobuf::file_source_node::FileSourceType; + use datafusion_proto::protobuf::physical_expr_node::ExprType; + use datafusion_proto::protobuf::physical_plan_node::PhysicalPlanType; + use datafusion_proto::protobuf::{ + ExtensionFileSourceNode, FileSourceNode, PhysicalExprNode, PhysicalPlanNode, + }; + use futures::{FutureExt, StreamExt}; + use object_store::{ObjectStore, ObjectStoreExt}; + + use super::*; + + /// Registers everything in this crate that a serialized plan can refer + /// to. Call it on each session that decodes plans. + /// + /// It adds to what other crates registered, in any order. + pub fn register_all(ctx: &SessionContext) -> Result<()> { + // A scalar UDF is decoded by name from the session's functions. + ctx.register_udf(square_udf()); + + // The other types are decoded by name from the session's + // `ProtoDecoderRegistry`. One registry holds every kind. + ctx.state_ref().write().config_mut().update_extension( + |registry: &mut ProtoDecoderRegistry| { + ScaleExpr::register_proto(registry)?; + RepeatExec::register_proto(registry)?; + NumbersSource::register_proto(registry) + }, + ) + } + + /// Scans a numbers file, computes `value * 10` and `value * value`, and + /// emits the result twice. + pub fn scaled_squared_and_repeated( + path: &str, + file_size: u64, + ) -> Result> { + let schema = numbers_schema(); + let source = Arc::new(NumbersSource::new(TableSchema::from(&schema))); + let scan = DataSourceExec::from_data_source( + FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), source) + .with_file_groups(vec![FileGroup::new(vec![PartitionedFile::new( + path.to_string(), + file_size, + )])]) + .build(), + ); + let scaled: Arc = Arc::new(ScaleExpr { + child: col("value", &schema)?, + factor: 10, + }); + let squared: Arc = Arc::new(ScalarFunctionExpr::try_new( + Arc::new(square_udf()), + vec![col("value", &schema)?], + &schema, + Arc::new(ConfigOptions::default()), + )?); + let projection = ProjectionExec::try_new( + vec![ + (scaled, "scaled".to_string()), + (squared, "squared".to_string()), + ], + scan, + )?; + Ok(Arc::new(RepeatExec::new(Arc::new(projection), 2))) + } + + // --------------------------------------------------------------------- + // A scalar UDF + // --------------------------------------------------------------------- + + /// `numbers_square(x)` returns `x * x`. + /// + /// It has no serialization code. DataFusion writes the function name, and + /// the decoding session looks the name up. + pub fn square_udf() -> ScalarUDF { + create_udf( + "numbers_square", + vec![DataType::Int64], + DataType::Int64, + Volatility::Immutable, + Arc::new(|args: &[ColumnarValue]| { + let values = ColumnarValue::values_to_arrays(args)?; + Ok(ColumnarValue::Array(mul(&values[0], &values[0])?)) + }), + ) + } + + // --------------------------------------------------------------------- + // A custom PhysicalExpr + // --------------------------------------------------------------------- + + /// Multiplies an `Int64` child by a constant. + #[derive(Debug)] + pub struct ScaleExpr { + child: Arc, + factor: i64, + } + + impl PartialEq for ScaleExpr { + fn eq(&self, other: &Self) -> bool { + self.factor == other.factor && self.child.eq(&other.child) + } + } + + impl Eq for ScaleExpr {} + + impl Hash for ScaleExpr { + fn hash(&self, state: &mut H) { + self.factor.hash(state); + self.child.hash(state); + } + } + + impl Display for ScaleExpr { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "ScaleExpr({}, {})", self.child, self.factor) + } + } + + impl PhysicalExpr for ScaleExpr { + fn data_type(&self, _input_schema: &Schema) -> Result { + Ok(DataType::Int64) + } + + fn nullable(&self, input_schema: &Schema) -> Result { + self.child.nullable(input_schema) + } + + fn evaluate(&self, batch: &RecordBatch) -> Result { + let values = self.child.evaluate(batch)?.into_array(batch.num_rows())?; + let scaled = mul(&values, &Int64Array::new_scalar(self.factor))?; + Ok(ColumnarValue::Array(scaled)) + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.child] + } + + fn with_new_children( + self: Arc, + mut children: Vec>, + ) -> Result> { + Ok(Arc::new(Self { + child: children.remove(0), + factor: self.factor, + })) + } + + fn fmt_sql(&self, f: &mut Formatter<'_>) -> fmt::Result { + Display::fmt(self, f) + } + + /// The payload is the factor. `extension_expr_node` writes + /// `Self::NAME` and encodes the child. + fn try_to_proto( + &self, + ctx: &PhysicalExprEncodeCtx<'_>, + ) -> Result> { + Ok(Some(extension_expr_node::( + ctx, + self.factor.to_le_bytes().to_vec(), + self.children(), + )?)) + } + } + + impl ExtensionExprFromProto for ScaleExpr { + // Prefixed with the crate name, so that the same name in another + // crate is an error at registration and not a wrong decode. + const NAME: &'static str = "numbers_crate.ScaleExpr"; + + fn try_from_proto( + node: &PhysicalExprNode, + ctx: &PhysicalExprDecodeCtx<'_>, + ) -> Result> { + let Some(ExprType::Extension(extension)) = &node.expr_type else { + return internal_err!("ScaleExpr expects an extension node"); + }; + let mut children = ctx.decode_children_expressions(&extension.inputs)?; + if children.len() != 1 { + return internal_err!("ScaleExpr expects exactly one child"); + } + Ok(Arc::new(Self { + child: children.remove(0), + factor: i64::from_le_bytes(payload(&extension.expr)?), + })) + } + } + + // --------------------------------------------------------------------- + // A custom ExecutionPlan + // --------------------------------------------------------------------- + + /// Emits every input batch `times` times. + #[derive(Debug)] + pub struct RepeatExec { + input: Arc, + times: u32, + properties: Arc, + } + + impl RepeatExec { + fn new(input: Arc, times: u32) -> Self { + // Repeating batches keeps the schema and the partitioning, but + // not the ordering. + let properties = PlanProperties::new( + EquivalenceProperties::new(input.schema()), + input.output_partitioning().clone(), + input.pipeline_behavior(), + input.boundedness(), + ); + Self { + input, + times, + properties: Arc::new(properties), + } + } + } + + impl DisplayAs for RepeatExec { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result { + write!(f, "RepeatExec: times={}", self.times) + } + } + + impl ExecutionPlan for RepeatExec { + fn name(&self) -> &str { + "RepeatExec" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + self.replace_children( + children, + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + } + + fn replace_children( + self: Arc, + mut children: Vec>, + _: ReplaceChildrenOptions, + ) -> Result> { + if children.len() != 1 { + return internal_err!("RepeatExec expects exactly one child"); + } + Ok(Arc::new(Self::new(children.remove(0), self.times))) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + let times = self.times; + let repeated = + self.input + .execute(partition, context)? + .flat_map(move |batch| { + let copies: Vec> = match batch { + Ok(batch) => (0..times).map(|_| Ok(batch.clone())).collect(), + Err(e) => vec![Err(e)], + }; + futures::stream::iter(copies) + }); + Ok(Box::pin(RecordBatchStreamAdapter::new( + self.schema(), + repeated, + ))) + } + + /// The payload is the repeat count. `extension_node` writes + /// `Self::NAME` and encodes the child plan. + fn try_to_proto( + &self, + ctx: &ExecutionPlanEncodeCtx<'_>, + ) -> Result> { + Ok(Some(ctx.extension_node::( + self.times.to_le_bytes().to_vec(), + self.children(), + )?)) + } + } + + impl ExtensionPlanFromProto for RepeatExec { + const NAME: &'static str = "numbers_crate.RepeatExec"; + + fn try_from_proto( + node: &PhysicalPlanNode, + ctx: &ExecutionPlanDecodeCtx<'_>, + ) -> Result> { + let Some(PhysicalPlanType::Extension(extension)) = &node.physical_plan_type + else { + return internal_err!("RepeatExec expects an extension node"); + }; + let mut children = ctx.decode_children(&extension.inputs)?; + if children.len() != 1 { + return internal_err!("RepeatExec expects exactly one child"); + } + Ok(Arc::new(Self::new( + children.remove(0), + u32::from_le_bytes(payload(&extension.node)?), + ))) + } + } + + // --------------------------------------------------------------------- + // A custom FileSource + // --------------------------------------------------------------------- + + /// Reads a text file with one `Int64` per line. + /// + /// `FileScanConfig` owns the file list, the projection, the limit and the + /// statistics, and DataFusion serializes them. This type serializes only + /// its own state. + #[derive(Debug, Clone)] + pub struct NumbersSource { + table_schema: TableSchema, + batch_size: Option, + metrics: ExecutionPlanMetricsSet, + } + + impl NumbersSource { + fn new(table_schema: TableSchema) -> Self { + Self { + table_schema, + batch_size: None, + metrics: ExecutionPlanMetricsSet::new(), + } + } + } + + impl FileSource for NumbersSource { + fn create_file_opener( + &self, + object_store: Arc, + _base_config: &FileScanConfig, + _partition: usize, + ) -> Result> { + Ok(Arc::new(NumbersOpener { + object_store, + schema: Arc::clone(self.table_schema.file_schema()), + })) + } + + fn table_schema(&self) -> &TableSchema { + &self.table_schema + } + + fn with_batch_size(&self, batch_size: usize) -> Arc { + Arc::new(Self { + batch_size: Some(batch_size), + ..self.clone() + }) + } + + fn metrics(&self) -> &ExecutionPlanMetricsSet { + &self.metrics + } + + fn file_type(&self) -> &str { + "numbers" + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + + /// Returns the `extension` arm: this type's name and its own state. + /// The payload is the batch size, or empty if none is set. + fn try_to_proto_file_source( + &self, + _ctx: &ExecutionPlanEncodeCtx<'_>, + ) -> Result> { + let payload = match self.batch_size { + Some(batch_size) => (batch_size as u64).to_le_bytes().to_vec(), + None => vec![], + }; + Ok(Some(FileSourceNode { + file_source_type: Some(FileSourceType::Extension( + ExtensionFileSourceNode { + name: Self::NAME.to_string(), + payload, + }, + )), + })) + } + } + + impl ExtensionFileSourceFromProto for NumbersSource { + const NAME: &'static str = "numbers_crate.NumbersSource"; + + /// DataFusion decodes the `FileScanConfig` and passes its table + /// schema. `payload` holds only what `try_to_proto_file_source` wrote. + fn try_from_proto( + bytes: &[u8], + table_schema: &TableSchema, + _ctx: &ExecutionPlanDecodeCtx<'_>, + ) -> Result> { + let batch_size = if bytes.is_empty() { + None + } else { + Some(u64::from_le_bytes(payload(bytes)?) as usize) + }; + Ok(Arc::new(Self { + batch_size, + ..Self::new(table_schema.clone()) + })) + } + } + + struct NumbersOpener { + object_store: Arc, + schema: SchemaRef, + } + + impl FileOpener for NumbersOpener { + fn open(&self, file: PartitionedFile) -> Result { + let object_store = Arc::clone(&self.object_store); + let schema = Arc::clone(&self.schema); + Ok(async move { + let bytes = object_store + .get(&file.object_meta.location) + .await? + .bytes() + .await?; + let text = std::str::from_utf8(&bytes).map_err(|e| { + exec_datafusion_err!("numbers file is not UTF-8: {e}") + })?; + let values = text + .lines() + .map(|line| { + line.trim().parse::().map_err(|e| { + exec_datafusion_err!("invalid number '{line}': {e}") + }) + }) + .collect::>>()?; + let batch = RecordBatch::try_new( + schema, + vec![Arc::new(Int64Array::from(values))], + )?; + Ok(futures::stream::iter([Ok(batch)]).boxed()) + } + .boxed()) + } + } + + /// Reads a fixed-width little-endian payload. + fn payload(bytes: &[u8]) -> Result<[u8; N]> { + bytes.try_into().map_err(|_| { + exec_datafusion_err!("expected a {N}-byte payload, got {}", bytes.len()) + }) + } +} diff --git a/datafusion-examples/examples/proto/main.rs b/datafusion-examples/examples/proto/main.rs index 60696a1128393..97d5598d2d8d9 100644 --- a/datafusion-examples/examples/proto/main.rs +++ b/datafusion-examples/examples/proto/main.rs @@ -4,11 +4,18 @@ //! # Examples demonstrating DataFusion's plan serialization via the `datafusion-proto` crate //! -//! These examples show how to use multiple extension codecs for serialization / deserialization. +//! These examples show how to serialize plans that contain types DataFusion does not define. +//! +//! Start with `extension_crate`. It shows the recommended path: each type +//! serializes itself, and a crate registers all of its types with one function. +//! `extension_plan_registry` uses the same path for plans from two independent +//! crates. `composed_extension_codec` and `expression_deduplication` use a +//! `PhysicalExtensionCodec`, the older path, which also serves types that +//! cannot serialize themselves. //! //! ## Usage //! ```bash -//! cargo run --example proto -- [all|composed_extension_codec|expression_deduplication|extension_plan_registry] +//! cargo run --example proto -- [all|composed_extension_codec|expression_deduplication|extension_crate|extension_plan_registry] //! ``` //! //! Each subcommand runs a corresponding example: @@ -20,11 +27,15 @@ //! - `expression_deduplication` //! (file: expression_deduplication.rs, desc: Example of expression caching/deduplication using the codec decorator pattern) //! +//! - `extension_crate` +//! (file: extension_crate.rs, desc: Recommended path. A crate whose custom expression, plan, file source and UDF serialize, with one function that registers them) +//! //! - `extension_plan_registry` //! (file: extension_plan_registry.rs, desc: Decode two crates' extension plans by name, with no composed codec) mod composed_extension_codec; mod expression_deduplication; +mod extension_crate; mod extension_plan_registry; use datafusion::error::{DataFusionError, Result}; @@ -37,6 +48,7 @@ enum ExampleKind { All, ComposedExtensionCodec, ExpressionDeduplication, + ExtensionCrate, ExtensionPlanRegistry, } @@ -61,6 +73,7 @@ impl ExampleKind { ExampleKind::ExpressionDeduplication => { expression_deduplication::expression_deduplication()? } + ExampleKind::ExtensionCrate => extension_crate::extension_crate().await?, ExampleKind::ExtensionPlanRegistry => { extension_plan_registry::extension_plan_registry()? } diff --git a/datafusion/core/src/datasource/mod.rs b/datafusion/core/src/datasource/mod.rs index f547d7e8d8398..d6f2670469fb3 100644 --- a/datafusion/core/src/datasource/mod.rs +++ b/datafusion/core/src/datasource/mod.rs @@ -29,6 +29,7 @@ pub use datafusion_catalog::empty; pub use datafusion_catalog::memory; pub use datafusion_catalog::stream; pub use datafusion_catalog::view; +pub use datafusion_datasource::file; pub use datafusion_datasource::projection; pub use datafusion_datasource::schema_adapter; pub use datafusion_datasource::sink; diff --git a/datafusion/datasource/src/proto/registry.rs b/datafusion/datasource/src/proto/registry.rs index 13ed95c933f62..6fc1d286b9bbc 100644 --- a/datafusion/datasource/src/proto/registry.rs +++ b/datafusion/datasource/src/proto/registry.rs @@ -141,6 +141,11 @@ pub trait ExtensionDataSourceFromProto: DataSource + Sized { /// let mut config = SessionConfig::new(); /// config.update_extension(MyFormatSource::register_proto)?; /// ``` +/// +/// See the [`extension_crate` example] for a complete crate that registers +/// its expressions, plans and file sources with one function. +/// +/// [`extension_crate` example]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/proto/extension_crate.rs pub trait ExtensionFileSourceFromProto: FileSource + Sized { /// The name this file source type is written and registered under. /// diff --git a/datafusion/physical-expr/src/proto.rs b/datafusion/physical-expr/src/proto.rs index 27ff4e37363a5..d21e72e1e3d0a 100644 --- a/datafusion/physical-expr/src/proto.rs +++ b/datafusion/physical-expr/src/proto.rs @@ -70,6 +70,11 @@ use datafusion_proto_models::protobuf::physical_expr_node::ExprType; /// let mut config = SessionConfig::new(); /// config.update_extension(MyExpr::register_proto)?; /// ``` +/// +/// See the [`extension_crate` example] for a complete crate that registers +/// its expressions, plans and file sources with one function. +/// +/// [`extension_crate` example]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/proto/extension_crate.rs pub trait ExtensionExprFromProto: PhysicalExpr + Sized { /// The name this expression type is written and registered under. /// diff --git a/datafusion/physical-plan/src/proto/registry.rs b/datafusion/physical-plan/src/proto/registry.rs index 8f83622ce14c0..29d24d9ffe0d6 100644 --- a/datafusion/physical-plan/src/proto/registry.rs +++ b/datafusion/physical-plan/src/proto/registry.rs @@ -63,6 +63,11 @@ use crate::proto::ExecutionPlanDecodeCtx; /// } /// } /// ``` +/// +/// See the [`extension_crate` example] for a complete crate that registers +/// its expressions, plans and file sources with one function. +/// +/// [`extension_crate` example]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/proto/extension_crate.rs pub trait ExtensionPlanFromProto: ExecutionPlan + Sized { /// The name this plan type is written and registered under. /// diff --git a/docs/source/library-user-guide/upgrading/index.md b/docs/source/library-user-guide/upgrading/index.md index 465fbd3fd6077..6b922b87f3be1 100644 --- a/docs/source/library-user-guide/upgrading/index.md +++ b/docs/source/library-user-guide/upgrading/index.md @@ -583,8 +583,9 @@ let mut config = SessionConfig::new(); config.update_extension(MySink::register_proto)?; ``` -[Issue #27941](https://github.com/apache/datafusion/issues/27941) tracks the -decoder work. +See the [`extension_crate` example](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/proto/extension_crate.rs) +for a custom expression, plan and file source that serialize, with one +function that registers all of their decoders. ### Missing Parquet null counts from older parquet-rs writers mean zero again