Skip to main content

datafusion_physical_expr/expressions/
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//! Physical column reference: [`Column`]
6
7use std::hash::Hash;
8use std::sync::Arc;
9
10use crate::physical_expr::PhysicalExpr;
11use arrow::datatypes::FieldRef;
12use arrow::{
13    datatypes::{DataType, Schema, SchemaRef},
14    record_batch::RecordBatch,
15};
16use datafusion_common::tree_node::{Transformed, TreeNode};
17use datafusion_common::{Result, internal_err, plan_err};
18use datafusion_expr::ColumnarValue;
19use datafusion_expr_common::placement::ExpressionPlacement;
20
21/// Represents the column at a given index in a RecordBatch
22///
23/// This is a physical expression that represents a column at a given index in an
24/// arrow [`Schema`] / [`RecordBatch`].
25///
26/// Unlike the [logical `Expr::Column`], this expression is always resolved by schema index,
27/// even though it does have a name. This is because the physical plan is always
28/// resolved to a specific schema and there is no concept of "relation"
29///
30/// # Example:
31///  If the schema is `a`, `b`, `c` the `Column` for `b` would be represented by
32///  index 1, since `b` is the second column in the schema.
33///
34/// ```
35/// # use datafusion_physical_expr::expressions::Column;
36/// # use arrow::datatypes::{DataType, Field, Schema};
37/// // Schema with columns a, b, c
38/// let schema = Schema::new(vec![
39///     Field::new("a", DataType::Int32, false),
40///     Field::new("b", DataType::Int32, false),
41///     Field::new("c", DataType::Int32, false),
42/// ]);
43///
44/// // reference to column b is index 1
45/// let column_b = Column::new_with_schema("b", &schema).unwrap();
46/// assert_eq!(column_b.index(), 1);
47///
48/// // reference to column c is index 2
49/// let column_c = Column::new_with_schema("c", &schema).unwrap();
50/// assert_eq!(column_c.index(), 2);
51/// ```
52/// [logical `Expr::Column`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/enum.Expr.html#variant.Column
53#[derive(Debug, Hash, PartialEq, Eq, Clone)]
54pub struct Column {
55    /// The name of the column (used for debugging and display purposes)
56    name: String,
57    /// The index of the column in its schema
58    index: usize,
59}
60
61impl Column {
62    /// Create a new column expression which references the
63    /// column with the given index in the schema.
64    pub fn new(name: &str, index: usize) -> Self {
65        Self {
66            name: name.to_owned(),
67            index,
68        }
69    }
70
71    /// Create a new column expression which references the
72    /// column with the given name in the schema
73    pub fn new_with_schema(name: &str, schema: &Schema) -> Result<Self> {
74        Ok(Column::new(name, schema.index_of(name)?))
75    }
76
77    /// Get the column's name
78    pub fn name(&self) -> &str {
79        &self.name
80    }
81
82    /// Get the column's schema index
83    pub fn index(&self) -> usize {
84        self.index
85    }
86}
87
88impl std::fmt::Display for Column {
89    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
90        write!(f, "{}@{}", self.name, self.index)
91    }
92}
93
94impl PhysicalExpr for Column {
95    /// Get the data type of this expression, given the schema of the input
96    fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
97        self.bounds_check(input_schema)?;
98        Ok(input_schema.field(self.index).data_type().clone())
99    }
100
101    /// Decide whether this expression is nullable, given the schema of the input
102    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
103        self.bounds_check(input_schema)?;
104        Ok(input_schema.field(self.index).is_nullable())
105    }
106
107    /// Evaluate the expression
108    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
109        self.bounds_check(batch.schema().as_ref())?;
110        Ok(ColumnarValue::Array(Arc::clone(batch.column(self.index))))
111    }
112
113    fn return_field(&self, input_schema: &Schema) -> Result<FieldRef> {
114        self.bounds_check(input_schema)?;
115        Ok(input_schema.field(self.index).clone().into())
116    }
117
118    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
119        vec![]
120    }
121
122    fn with_new_children(
123        self: Arc<Self>,
124        _children: Vec<Arc<dyn PhysicalExpr>>,
125    ) -> Result<Arc<dyn PhysicalExpr>> {
126        Ok(self)
127    }
128
129    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        write!(f, "{}", self.name)
131    }
132
133    fn placement(&self) -> ExpressionPlacement {
134        ExpressionPlacement::Column
135    }
136
137    #[cfg(feature = "proto")]
138    fn try_to_proto(
139        &self,
140        _ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
141    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
142        use datafusion_proto_models::protobuf;
143        let Self { name, index } = self;
144        Ok(Some(protobuf::PhysicalExprNode {
145            expr_id: None,
146            expr_type: Some(protobuf::physical_expr_node::ExprType::Column(
147                protobuf::PhysicalColumn {
148                    name: name.clone(),
149                    index: *index as u32,
150                },
151            )),
152        }))
153    }
154}
155
156#[cfg(feature = "proto")]
157impl From<&datafusion_proto_models::protobuf::PhysicalColumn> for Column {
158    fn from(c: &datafusion_proto_models::protobuf::PhysicalColumn) -> Self {
159        let datafusion_proto_models::protobuf::PhysicalColumn { name, index } = c;
160        Column::new(name, *index as usize)
161    }
162}
163
164#[cfg(feature = "proto")]
165impl From<&Column> for datafusion_proto_models::protobuf::PhysicalColumn {
166    fn from(c: &Column) -> Self {
167        let Column { name, index } = c;
168        Self {
169            name: name.clone(),
170            index: *index as u32,
171        }
172    }
173}
174
175#[cfg(feature = "proto")]
176impl Column {
177    /// Reconstruct a [`Column`] from its protobuf representation.
178    ///
179    /// Takes the whole [`PhysicalExprNode`] — the exact inverse of what
180    /// [`PhysicalExpr::try_to_proto`] produces — so every expression's
181    /// `try_from_proto` shares one signature. The decode context is currently
182    /// unused, but is threaded through so that future expressions with child
183    /// sub-expressions can recurse via [`PhysicalExprDecodeCtx::decode`].
184    ///
185    /// [`PhysicalExprNode`]: datafusion_proto_models::protobuf::PhysicalExprNode
186    /// [`PhysicalExpr::try_to_proto`]: datafusion_physical_expr_common::physical_expr::PhysicalExpr::try_to_proto
187    /// [`PhysicalExprDecodeCtx::decode`]: datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx::decode
188    pub fn try_from_proto(
189        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
190        _ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
191    ) -> Result<Arc<dyn PhysicalExpr>> {
192        use datafusion_physical_expr_common::expect_expr_variant;
193        use datafusion_proto_models::protobuf;
194        let protobuf::PhysicalColumn { name, index } = expect_expr_variant!(
195            node,
196            protobuf::physical_expr_node::ExprType::Column,
197            "Column",
198        );
199        Ok(Arc::new(Column::new(name, *index as usize)))
200    }
201}
202
203impl Column {
204    fn bounds_check(&self, input_schema: &Schema) -> Result<()> {
205        if self.index < input_schema.fields.len() {
206            Ok(())
207        } else {
208            internal_err!(
209                "PhysicalExpr Column references column '{}' at index {} (zero-based) but input schema only has {} columns: {:?}",
210                self.name,
211                self.index,
212                input_schema.fields.len(),
213                input_schema
214                    .fields()
215                    .iter()
216                    .map(|f| f.name())
217                    .collect::<Vec<_>>()
218            )
219        }
220    }
221}
222
223/// Create a column expression
224pub fn col(name: &str, schema: &Schema) -> Result<Arc<dyn PhysicalExpr>> {
225    Ok(Arc::new(Column::new_with_schema(name, schema)?))
226}
227
228/// Rewrites an expression according to new schema; i.e. changes the columns it
229/// refers to with the column at corresponding index in the new schema. Returns
230/// an error if the given schema has fewer columns than the original schema.
231/// Note that the resulting expression may not be valid if data types in the
232/// new schema is incompatible with expression nodes.
233pub fn with_new_schema(
234    expr: Arc<dyn PhysicalExpr>,
235    schema: &SchemaRef,
236) -> Result<Arc<dyn PhysicalExpr>> {
237    Ok(expr
238        .transform_up(|expr| {
239            if let Some(col) = expr.downcast_ref::<Column>() {
240                let idx = col.index();
241                let Some(field) = schema.fields().get(idx) else {
242                    return plan_err!(
243                        "New schema has fewer columns than original schema"
244                    );
245                };
246                let new_col = Column::new(field.name(), idx);
247                Ok(Transformed::yes(Arc::new(new_col) as _))
248            } else {
249                Ok(Transformed::no(expr))
250            }
251        })?
252        .data)
253}
254
255#[cfg(test)]
256mod test {
257    use super::Column;
258    use crate::physical_expr::PhysicalExpr;
259
260    use arrow::array::StringArray;
261    use arrow::datatypes::{DataType, Field, Schema};
262    use arrow::record_batch::RecordBatch;
263
264    use std::sync::Arc;
265
266    #[test]
267    fn out_of_bounds_data_type() {
268        let schema = Schema::new(vec![Field::new("foo", DataType::Utf8, true)]);
269        let col = Column::new("id", 9);
270        let error = col.data_type(&schema).expect_err("error").strip_backtrace();
271        assert!("Internal error: PhysicalExpr Column references column 'id' at index 9 (zero-based) \
272             but input schema only has 1 columns: [\"foo\"].\nThis issue was likely caused by a bug \
273             in DataFusion's code. Please help us to resolve this by filing a bug report \
274             in our issue tracker: https://github.com/apache/datafusion/issues".starts_with(&error))
275    }
276
277    #[test]
278    fn out_of_bounds_nullable() {
279        let schema = Schema::new(vec![Field::new("foo", DataType::Utf8, true)]);
280        let col = Column::new("id", 9);
281        let error = col.nullable(&schema).expect_err("error").strip_backtrace();
282        assert!("Internal error: PhysicalExpr Column references column 'id' at index 9 (zero-based) \
283             but input schema only has 1 columns: [\"foo\"].\nThis issue was likely caused by a bug \
284             in DataFusion's code. Please help us to resolve this by filing a bug report \
285             in our issue tracker: https://github.com/apache/datafusion/issues".starts_with(&error));
286    }
287
288    #[test]
289    fn out_of_bounds_evaluate() {
290        let schema = Schema::new(vec![Field::new("foo", DataType::Utf8, true)]);
291        let data: StringArray = vec!["data"].into();
292        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(data)]).unwrap();
293        let col = Column::new("id", 9);
294        let error = col.evaluate(&batch).expect_err("error").strip_backtrace();
295        assert!("Internal error: PhysicalExpr Column references column 'id' at index 9 (zero-based) \
296             but input schema only has 1 columns: [\"foo\"].\nThis issue was likely caused by a bug \
297             in DataFusion's code. Please help us to resolve this by filing a bug report \
298             in our issue tracker: https://github.com/apache/datafusion/issues".starts_with(&error));
299    }
300}