Skip to main content

datafusion_physical_expr/expressions/
unknown_column.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//! UnKnownColumn expression
6
7use std::hash::{Hash, Hasher};
8use std::sync::Arc;
9
10use crate::PhysicalExpr;
11
12use arrow::{
13    datatypes::{DataType, Schema},
14    record_batch::RecordBatch,
15};
16use datafusion_common::{Result, internal_err};
17
18use datafusion_expr::ColumnarValue;
19
20#[derive(Debug, Clone, Eq)]
21pub struct UnKnownColumn {
22    name: String,
23}
24
25impl UnKnownColumn {
26    /// Create a new unknown column expression
27    pub fn new(name: &str) -> Self {
28        Self {
29            name: name.to_owned(),
30        }
31    }
32
33    /// Get the column name
34    pub fn name(&self) -> &str {
35        &self.name
36    }
37}
38
39impl std::fmt::Display for UnKnownColumn {
40    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
41        write!(f, "{}", self.name)
42    }
43}
44
45impl PhysicalExpr for UnKnownColumn {
46    /// Get the data type of this expression, given the schema of the input
47    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
48        Ok(DataType::Null)
49    }
50
51    /// Decide whether this expression is nullable, given the schema of the input
52    fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
53        Ok(true)
54    }
55
56    /// Evaluate the expression
57    fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {
58        internal_err!("UnKnownColumn::evaluate() should not be called")
59    }
60
61    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
62        vec![]
63    }
64
65    fn with_new_children(
66        self: Arc<Self>,
67        _children: Vec<Arc<dyn PhysicalExpr>>,
68    ) -> Result<Arc<dyn PhysicalExpr>> {
69        Ok(self)
70    }
71
72    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        std::fmt::Display::fmt(self, f)
74    }
75
76    #[cfg(feature = "proto")]
77    fn try_to_proto(
78        &self,
79        _ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
80    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
81        use datafusion_proto_models::protobuf;
82
83        let Self { name } = self;
84        Ok(Some(protobuf::PhysicalExprNode {
85            expr_id: None,
86            expr_type: Some(protobuf::physical_expr_node::ExprType::UnknownColumn(
87                protobuf::UnknownColumn { name: name.clone() },
88            )),
89        }))
90    }
91}
92
93#[cfg(feature = "proto")]
94impl UnKnownColumn {
95    /// Reconstruct an [`UnKnownColumn`] from its protobuf representation.
96    pub fn try_from_proto(
97        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
98        _ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
99    ) -> Result<Arc<dyn PhysicalExpr>> {
100        use datafusion_physical_expr_common::expect_expr_variant;
101        use datafusion_proto_models::protobuf;
102
103        let protobuf::UnknownColumn { name } = expect_expr_variant!(
104            node,
105            protobuf::physical_expr_node::ExprType::UnknownColumn,
106            "UnKnownColumn",
107        );
108        Ok(Arc::new(UnKnownColumn::new(name)))
109    }
110}
111
112impl Hash for UnKnownColumn {
113    fn hash<H: Hasher>(&self, state: &mut H) {
114        self.name.hash(state);
115    }
116}
117
118impl PartialEq for UnKnownColumn {
119    fn eq(&self, _other: &Self) -> bool {
120        // UnknownColumn is not a valid expression, so it should not be equal to any other expression.
121        // See https://github.com/apache/datafusion/pull/11536
122        false
123    }
124}
125
126/// Tests for the `try_to_proto` / `try_from_proto` hooks.
127#[cfg(all(test, feature = "proto"))]
128mod proto_tests {
129    use super::*;
130    use crate::proto_test_util::{StubEncoder, UnreachableDecoder, column_node};
131    use arrow::datatypes::Schema;
132    use datafusion_common::DataFusionError;
133    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
134    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
135    use datafusion_proto_models::protobuf::{self, physical_expr_node};
136
137    // ── try_to_proto ─────────────────────────────────────────────────────────
138
139    #[test]
140    fn try_to_proto_encodes_unknown_column() {
141        let expr = UnKnownColumn::new("my_col");
142        let encoder = StubEncoder::ok();
143        let ctx = PhysicalExprEncodeCtx::new(&encoder);
144
145        let node = expr
146            .try_to_proto(&ctx)
147            .unwrap()
148            .expect("UnKnownColumn should encode to Some(node)");
149
150        // Built-in exprs never set expr_id; only dynamic filters do.
151        assert!(node.expr_id.is_none());
152
153        // Verify the encoded name matches the original.
154        let protobuf::UnknownColumn { name } = match node.expr_type {
155            Some(physical_expr_node::ExprType::UnknownColumn(c)) => c,
156            other => panic!("expected UnknownColumn proto node, got {other:?}"),
157        };
158        assert_eq!(name, "my_col");
159    }
160
161    // ── try_from_proto ───────────────────────────────────────────────────────
162
163    #[test]
164    fn try_from_proto_decodes_name() {
165        let node = protobuf::PhysicalExprNode {
166            expr_id: None,
167            expr_type: Some(physical_expr_node::ExprType::UnknownColumn(
168                protobuf::UnknownColumn {
169                    name: "my_col".to_string(),
170                },
171            )),
172        };
173        let schema = Schema::empty();
174        // UnKnownColumn has no child exprs so the decoder is never called.
175        let decoder = UnreachableDecoder;
176        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
177
178        let decoded = UnKnownColumn::try_from_proto(&node, &ctx).unwrap();
179        let col = decoded
180            .downcast_ref::<UnKnownColumn>()
181            .expect("decoded expr should be an UnKnownColumn");
182        assert_eq!(col.name(), "my_col");
183    }
184
185    #[test]
186    fn try_from_proto_rejects_non_unknown_column_node() {
187        // column_node produces an ExprType::Column node, not UnknownColumn.
188        let node = column_node("a");
189        let schema = Schema::empty();
190        let decoder = UnreachableDecoder;
191        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
192        let err = UnKnownColumn::try_from_proto(&node, &ctx).unwrap_err();
193        assert!(matches!(
194            err,
195            DataFusionError::Internal(ref msg)
196                if msg.contains("PhysicalExprNode is not a UnKnownColumn")
197        ));
198    }
199
200    // ── roundtrip ────────────────────────────────────────────────────────────
201
202    #[test]
203    fn unknown_column_proto_roundtrip() {
204        let expr = UnKnownColumn::new("col_b");
205        let encoder = StubEncoder::ok();
206        let enc_ctx = PhysicalExprEncodeCtx::new(&encoder);
207
208        let node = expr
209            .try_to_proto(&enc_ctx)
210            .unwrap()
211            .expect("UnKnownColumn should encode to Some(node)");
212
213        let schema = Schema::empty();
214        // UnKnownColumn has no child exprs so the decoder is never called.
215        let decoder = UnreachableDecoder;
216        let dec_ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
217
218        let decoded = UnKnownColumn::try_from_proto(&node, &dec_ctx).unwrap();
219        let col = decoded
220            .downcast_ref::<UnKnownColumn>()
221            .expect("decoded expr should be an UnKnownColumn");
222        assert_eq!(col.name(), "col_b");
223    }
224}