datafusion_physical_expr/expressions/
column.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Physical column reference: [`Column`]
19
20use std::any::Any;
21use std::hash::Hash;
22use std::sync::Arc;
23
24use crate::physical_expr::PhysicalExpr;
25use arrow::datatypes::FieldRef;
26use arrow::{
27    datatypes::{DataType, Schema, SchemaRef},
28    record_batch::RecordBatch,
29};
30use datafusion_common::tree_node::{Transformed, TreeNode};
31use datafusion_common::{internal_err, plan_err, Result};
32use datafusion_expr::ColumnarValue;
33
34/// Represents the column at a given index in a RecordBatch
35///
36/// This is a physical expression that represents a column at a given index in an
37/// arrow [`Schema`] / [`RecordBatch`].
38///
39/// Unlike the [logical `Expr::Column`], this expression is always resolved by schema index,
40/// even though it does have a name. This is because the physical plan is always
41/// resolved to a specific schema and there is no concept of "relation"
42///
43/// # Example:
44///  If the schema is `a`, `b`, `c` the `Column` for `b` would be represented by
45///  index 1, since `b` is the second column in the schema.
46///
47/// ```
48/// # use datafusion_physical_expr::expressions::Column;
49/// # use arrow::datatypes::{DataType, Field, Schema};
50/// // Schema with columns a, b, c
51/// let schema = Schema::new(vec![
52///    Field::new("a", DataType::Int32, false),
53///    Field::new("b", DataType::Int32, false),
54///    Field::new("c", DataType::Int32, false),
55/// ]);
56///
57/// // reference to column b is index 1
58/// let column_b = Column::new_with_schema("b", &schema).unwrap();
59/// assert_eq!(column_b.index(), 1);
60///
61/// // reference to column c is index 2
62/// let column_c = Column::new_with_schema("c", &schema).unwrap();
63/// assert_eq!(column_c.index(), 2);
64/// ```
65/// [logical `Expr::Column`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/enum.Expr.html#variant.Column
66#[derive(Debug, Hash, PartialEq, Eq, Clone)]
67pub struct Column {
68    /// The name of the column (used for debugging and display purposes)
69    name: String,
70    /// The index of the column in its schema
71    index: usize,
72}
73
74impl Column {
75    /// Create a new column expression which references the
76    /// column with the given index in the schema.
77    pub fn new(name: &str, index: usize) -> Self {
78        Self {
79            name: name.to_owned(),
80            index,
81        }
82    }
83
84    /// Create a new column expression which references the
85    /// column with the given name in the schema
86    pub fn new_with_schema(name: &str, schema: &Schema) -> Result<Self> {
87        Ok(Column::new(name, schema.index_of(name)?))
88    }
89
90    /// Get the column's name
91    pub fn name(&self) -> &str {
92        &self.name
93    }
94
95    /// Get the column's schema index
96    pub fn index(&self) -> usize {
97        self.index
98    }
99}
100
101impl std::fmt::Display for Column {
102    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
103        write!(f, "{}@{}", self.name, self.index)
104    }
105}
106
107impl PhysicalExpr for Column {
108    /// Return a reference to Any that can be used for downcasting
109    fn as_any(&self) -> &dyn Any {
110        self
111    }
112
113    /// Get the data type of this expression, given the schema of the input
114    fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
115        self.bounds_check(input_schema)?;
116        Ok(input_schema.field(self.index).data_type().clone())
117    }
118
119    /// Decide whether this expression is nullable, given the schema of the input
120    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
121        self.bounds_check(input_schema)?;
122        Ok(input_schema.field(self.index).is_nullable())
123    }
124
125    /// Evaluate the expression
126    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
127        self.bounds_check(batch.schema().as_ref())?;
128        Ok(ColumnarValue::Array(Arc::clone(batch.column(self.index))))
129    }
130
131    fn return_field(&self, input_schema: &Schema) -> Result<FieldRef> {
132        Ok(input_schema.field(self.index).clone().into())
133    }
134
135    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
136        vec![]
137    }
138
139    fn with_new_children(
140        self: Arc<Self>,
141        _children: Vec<Arc<dyn PhysicalExpr>>,
142    ) -> Result<Arc<dyn PhysicalExpr>> {
143        Ok(self)
144    }
145
146    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        write!(f, "{}", self.name)
148    }
149}
150
151impl Column {
152    fn bounds_check(&self, input_schema: &Schema) -> Result<()> {
153        if self.index < input_schema.fields.len() {
154            Ok(())
155        } else {
156            internal_err!(
157                "PhysicalExpr Column references column '{}' at index {} (zero-based) but input schema only has {} columns: {:?}",
158                self.name,
159                self.index,
160                input_schema.fields.len(),
161                input_schema.fields().iter().map(|f| f.name()).collect::<Vec<_>>()
162            )
163        }
164    }
165}
166
167/// Create a column expression
168pub fn col(name: &str, schema: &Schema) -> Result<Arc<dyn PhysicalExpr>> {
169    Ok(Arc::new(Column::new_with_schema(name, schema)?))
170}
171
172/// Rewrites an expression according to new schema; i.e. changes the columns it
173/// refers to with the column at corresponding index in the new schema. Returns
174/// an error if the given schema has fewer columns than the original schema.
175/// Note that the resulting expression may not be valid if data types in the
176/// new schema is incompatible with expression nodes.
177pub fn with_new_schema(
178    expr: Arc<dyn PhysicalExpr>,
179    schema: &SchemaRef,
180) -> Result<Arc<dyn PhysicalExpr>> {
181    Ok(expr
182        .transform_up(|expr| {
183            if let Some(col) = expr.as_any().downcast_ref::<Column>() {
184                let idx = col.index();
185                let Some(field) = schema.fields().get(idx) else {
186                    return plan_err!(
187                        "New schema has fewer columns than original schema"
188                    );
189                };
190                let new_col = Column::new(field.name(), idx);
191                Ok(Transformed::yes(Arc::new(new_col) as _))
192            } else {
193                Ok(Transformed::no(expr))
194            }
195        })?
196        .data)
197}
198
199#[cfg(test)]
200mod test {
201    use super::Column;
202    use crate::physical_expr::PhysicalExpr;
203
204    use arrow::array::StringArray;
205    use arrow::datatypes::{DataType, Field, Schema};
206    use arrow::record_batch::RecordBatch;
207
208    use std::sync::Arc;
209
210    #[test]
211    fn out_of_bounds_data_type() {
212        let schema = Schema::new(vec![Field::new("foo", DataType::Utf8, true)]);
213        let col = Column::new("id", 9);
214        let error = col.data_type(&schema).expect_err("error").strip_backtrace();
215        assert!("Internal error: PhysicalExpr Column references column 'id' at index 9 (zero-based) \
216             but input schema only has 1 columns: [\"foo\"].\nThis issue was likely caused by a bug \
217             in DataFusion's code. Please help us to resolve this by filing a bug report \
218             in our issue tracker: https://github.com/apache/datafusion/issues".starts_with(&error))
219    }
220
221    #[test]
222    fn out_of_bounds_nullable() {
223        let schema = Schema::new(vec![Field::new("foo", DataType::Utf8, true)]);
224        let col = Column::new("id", 9);
225        let error = col.nullable(&schema).expect_err("error").strip_backtrace();
226        assert!("Internal error: PhysicalExpr Column references column 'id' at index 9 (zero-based) \
227             but input schema only has 1 columns: [\"foo\"].\nThis issue was likely caused by a bug \
228             in DataFusion's code. Please help us to resolve this by filing a bug report \
229             in our issue tracker: https://github.com/apache/datafusion/issues".starts_with(&error));
230    }
231
232    #[test]
233    fn out_of_bounds_evaluate() {
234        let schema = Schema::new(vec![Field::new("foo", DataType::Utf8, true)]);
235        let data: StringArray = vec!["data"].into();
236        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(data)]).unwrap();
237        let col = Column::new("id", 9);
238        let error = col.evaluate(&batch).expect_err("error").strip_backtrace();
239        assert!("Internal error: PhysicalExpr Column references column 'id' at index 9 (zero-based) \
240             but input schema only has 1 columns: [\"foo\"].\nThis issue was likely caused by a bug \
241             in DataFusion's code. Please help us to resolve this by filing a bug report \
242             in our issue tracker: https://github.com/apache/datafusion/issues".starts_with(&error));
243    }
244}