Skip to main content

datafusion_physical_expr/
proto.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! The `PhysicalExpr` face of the session-scoped [`ProtoDecoderRegistry`],
6//! which routes extension expressions to their decoders by name:
7//! [`ExtensionExprFromProto::register_proto`] and [`physical_expr_names`], all keyed on `dyn PhysicalExpr`. The store itself
8//! is shared with every other extension kind, so a session carries one
9//! registry.
10
11use std::sync::Arc;
12
13use datafusion_common::Result;
14use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
15pub use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
16pub use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
17pub use datafusion_proto_models::ProtoDecoderRegistry;
18use datafusion_proto_models::protobuf::PhysicalExprNode;
19use datafusion_proto_models::protobuf::physical_expr_node::ExprType;
20
21/// The wire name of an extension [`PhysicalExpr`], and the constructor that
22/// rebuilds it.
23///
24/// Only extension expressions implement this. A built-in expression has an
25/// `ExprType` variant of its own, keeps the inherent `try_from_proto`
26/// dispatched from that variant, and has no wire name to be registered under —
27/// so it has no [`register`](Self::register_proto) method.
28///
29/// One impl block says what the expression is called and how it decodes; its
30/// `try_to_proto` on [`PhysicalExpr`] writes the matching node with
31/// [`extension_expr_node`]:
32///
33/// ```ignore
34/// impl PhysicalExpr for MyExpr {
35///     // ...
36///     fn try_to_proto(
37///         &self,
38///         ctx: &PhysicalExprEncodeCtx<'_>,
39///     ) -> Result<Option<PhysicalExprNode>> {
40///         // Stamps `Self::NAME`, so the encoded name and the registry key
41///         // cannot drift apart.
42///         Ok(Some(extension_expr_node::<Self>(
43///             ctx,
44///             self.state.to_bytes()?,
45///             self.children(),
46///         )?))
47///     }
48/// }
49///
50/// impl ExtensionExprFromProto for MyExpr {
51///     // Namespace the name with the owning crate, so a collision with
52///     // another crate is an error at registration and not a wrong decode.
53///     const NAME: &'static str = "my_crate.MyExpr";
54///
55///     fn try_from_proto(
56///         node: &PhysicalExprNode,
57///         ctx: &PhysicalExprDecodeCtx<'_>,
58///     ) -> Result<Arc<dyn PhysicalExpr>> {
59///         let extension = expect_expr_variant!(
60///             node,
61///             physical_expr_node::ExprType::Extension,
62///             "Extension",
63///         );
64///         let state = MyState::from_bytes(&extension.expr)?;
65///         let children = ctx.decode_children_expressions(&extension.inputs)?;
66///         Ok(Arc::new(MyExpr::new(state, children)))
67///     }
68/// }
69///
70/// let mut config = SessionConfig::new();
71/// config.update_extension(MyExpr::register_proto)?;
72/// ```
73pub trait ExtensionExprFromProto: PhysicalExpr + Sized {
74    /// The name this expression type is written and registered under.
75    ///
76    /// Namespace it with the owning crate — `"my_crate.MyExpr"`, not
77    /// `"MyExpr"` — so that two independent crates registering into the same
78    /// session collide at registration time instead of silently decoding each
79    /// other's nodes. Never write it by hand on the wire:
80    /// [`extension_expr_node`] stamps it for you.
81    const NAME: &'static str;
82
83    /// Rebuild the expression from the `PhysicalExprNode` its
84    /// [`PhysicalExpr::try_to_proto`] wrote.
85    ///
86    /// Takes the whole node — the exact inverse of what `try_to_proto`
87    /// returns — so the constructor can also see outer-node fields such as
88    /// `expr_id`. `ctx.session::<TaskContext>()` gives the session, for
89    /// resolving UDFs by name or reading configuration.
90    fn try_from_proto(
91        node: &PhysicalExprNode,
92        ctx: &PhysicalExprDecodeCtx<'_>,
93    ) -> Result<Arc<dyn PhysicalExpr>>;
94
95    /// Register this expression's decoder in `registry`, under [`Self::NAME`].
96    ///
97    /// Registering the same type twice is a no-op. A *different* type under a
98    /// name that is already taken is an error, so a collision shows here and
99    /// not as a wrong decode. The name is scoped to `dyn PhysicalExpr`, so a
100    /// plan or a data source can use the same name in the same registry.
101    ///
102    /// Add it to the session's registry with
103    /// `config.update_extension(MyExpr::register_proto)?`, which keeps the decoders
104    /// that other libraries added. One registry holds every kind, so a library
105    /// registers its plans and its expressions into the same registry.
106    ///
107    /// A built-in expression keeps an inherent `try_from_proto`, dispatched
108    /// from its own `ExprType` variant:
109    ///
110    /// ```
111    /// use datafusion_physical_expr::expressions::Column;
112    /// #[allow(unused_imports)]
113    /// use datafusion_physical_expr::proto::ExtensionExprFromProto;
114    ///
115    /// let _ = Column::try_from_proto;
116    /// ```
117    ///
118    /// but it does not implement this trait, so it cannot be registered:
119    ///
120    /// ```compile_fail
121    /// use datafusion_physical_expr::expressions::Column;
122    /// use datafusion_physical_expr::proto::ExtensionExprFromProto;
123    /// use datafusion_proto_models::ProtoDecoderRegistry;
124    ///
125    /// let mut registry = ProtoDecoderRegistry::new();
126    /// Column::register_proto(&mut registry).unwrap();
127    /// ```
128    fn register_proto(registry: &mut ProtoDecoderRegistry) -> Result<()> {
129        registry.register_decoder::<dyn PhysicalExpr, Self, PhysicalExprDecoder>(
130            Self::NAME,
131            Self::try_from_proto,
132        )
133    }
134}
135
136/// Build the `PhysicalExprNode` for an extension expression `T`: an
137/// `Extension` variant carrying `payload`, the encoded `children`, and `T`'s
138/// [`NAME`](ExtensionExprFromProto::NAME).
139///
140/// The one supported way for an extension expression to write itself. It is a
141/// free function rather than a method on [`PhysicalExprEncodeCtx`] because the
142/// context lives in `datafusion-physical-expr-common`, below the crate that
143/// can name [`ExtensionExprFromProto`].
144pub fn extension_expr_node<T: ExtensionExprFromProto>(
145    ctx: &PhysicalExprEncodeCtx<'_>,
146    payload: Vec<u8>,
147    children: Vec<&Arc<dyn PhysicalExpr>>,
148) -> Result<PhysicalExprNode> {
149    Ok(PhysicalExprNode {
150        expr_type: Some(ExprType::Extension(
151            datafusion_proto_models::protobuf::PhysicalExtensionExprNode {
152                expr: payload,
153                inputs: ctx.encode_children_expressions(children)?,
154                expr_name: Some(T::NAME.to_string()),
155            },
156        )),
157        ..Default::default()
158    })
159}
160
161/// How this facade stores a decoder in the shared registry: a function pointer
162/// to the monomorphized [`ExtensionExprFromProto::try_from_proto`].
163///
164/// Deliberately private, and the same type on both the
165/// [`ExtensionExprFromProto::register_proto`] and the [`decode_physical_expr`] side.
166/// [`ExtensionExprFromProto`] is the public contract and
167/// [`decode_physical_expr`] (hidden, internal to DataFusion) is the only way
168/// to invoke one, so the storage
169/// can change later without a breaking change.
170type PhysicalExprDecoder =
171    fn(&PhysicalExprNode, &PhysicalExprDecodeCtx<'_>) -> Result<Arc<dyn PhysicalExpr>>;
172
173/// Decode `node` with the extension expression decoder registered under the
174/// name `node` carries.
175///
176/// The name is read from the node's `Extension` variant rather than passed in,
177/// so a caller cannot pair a node with a name it does not carry.
178///
179/// `None` means "this node names no extension expression decoder of ours": it
180/// is not an extension node, it carries no name, or no registered name matches.
181/// The caller then falls back to the `PhysicalExtensionCodec` chain.
182/// `Some(Err(..))` means the decoder that *does* own the name failed, which is
183/// fatal: falling back there would let a codec decode the payload wrongly, the
184/// very thing the name exists to prevent.
185///
186/// Not intended as public API: `datafusion-proto` drives decoding and is the
187/// only intended caller. It is `pub` only because that call crosses a crate
188/// boundary, so it is hidden from the docs and may change without notice.
189#[doc(hidden)]
190pub fn decode_physical_expr(
191    registry: &ProtoDecoderRegistry,
192    node: &PhysicalExprNode,
193    ctx: &PhysicalExprDecodeCtx<'_>,
194) -> Option<Result<Arc<dyn PhysicalExpr>>> {
195    let name = expr_name(node)?;
196    let decoder = registry.decoder::<dyn PhysicalExpr, PhysicalExprDecoder>(name)?;
197    Some(decoder(node, ctx))
198}
199
200/// Every extension expression name registered in `registry`, in arbitrary
201/// order.
202///
203/// Names registered for another kind are not included.
204pub fn physical_expr_names(
205    registry: &ProtoDecoderRegistry,
206) -> impl Iterator<Item = &str> {
207    registry.names::<dyn PhysicalExpr>()
208}
209
210/// The registry name `node` was written with, if it is an extension node that
211/// carries one.
212fn expr_name(node: &PhysicalExprNode) -> Option<&str> {
213    match node.expr_type.as_ref()? {
214        ExprType::Extension(extension) => extension.expr_name.as_deref(),
215        _ => None,
216    }
217}