datafusion_physical_expr/expressions/
column.rs1use 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#[derive(Debug, Hash, PartialEq, Eq, Clone)]
54pub struct Column {
55 name: String,
57 index: usize,
59}
60
61impl Column {
62 pub fn new(name: &str, index: usize) -> Self {
65 Self {
66 name: name.to_owned(),
67 index,
68 }
69 }
70
71 pub fn new_with_schema(name: &str, schema: &Schema) -> Result<Self> {
74 Ok(Column::new(name, schema.index_of(name)?))
75 }
76
77 pub fn name(&self) -> &str {
79 &self.name
80 }
81
82 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 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 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 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 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
223pub fn col(name: &str, schema: &Schema) -> Result<Arc<dyn PhysicalExpr>> {
225 Ok(Arc::new(Column::new_with_schema(name, schema)?))
226}
227
228pub 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}