|
| 1 | +//! Custom execution plan for renaming columns |
| 2 | +//! |
| 3 | +//! This module implements a DataFusion execution plan that wraps a scan |
| 4 | +//! and renames columns from their original Parquet names to current DuckLake names. |
| 5 | +//! This is needed when columns have been renamed in DuckLake metadata but the |
| 6 | +//! Parquet files still have the original column names. |
| 7 | +
|
| 8 | +use std::any::Any; |
| 9 | +use std::collections::HashMap; |
| 10 | +use std::pin::Pin; |
| 11 | +use std::sync::Arc; |
| 12 | +use std::task::{Context, Poll}; |
| 13 | + |
| 14 | +use arrow::datatypes::SchemaRef; |
| 15 | +use arrow::record_batch::RecordBatch; |
| 16 | +use datafusion::error::{DataFusionError, Result as DataFusionResult}; |
| 17 | +use datafusion::execution::{RecordBatchStream, SendableRecordBatchStream, TaskContext}; |
| 18 | +use datafusion::physical_expr::EquivalenceProperties; |
| 19 | +use datafusion::physical_plan::execution_plan::Boundedness; |
| 20 | +use datafusion::physical_plan::{ |
| 21 | + DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, |
| 22 | +}; |
| 23 | +use futures::Stream; |
| 24 | + |
| 25 | +/// Custom execution plan that renames columns from Parquet file names to current DuckLake names |
| 26 | +#[derive(Debug)] |
| 27 | +pub struct ColumnRenameExec { |
| 28 | + /// The input execution plan (typically ParquetExec) |
| 29 | + input: Arc<dyn ExecutionPlan>, |
| 30 | + /// Output schema with renamed columns |
| 31 | + output_schema: SchemaRef, |
| 32 | + /// Mapping from old (Parquet) column names to new (DuckLake) column names |
| 33 | + name_mapping: HashMap<String, String>, |
| 34 | + /// Reverse mapping: new name -> old name, for looking up input columns |
| 35 | + reverse_mapping: Arc<HashMap<String, String>>, |
| 36 | + /// Cached plan properties with updated schema |
| 37 | + properties: PlanProperties, |
| 38 | +} |
| 39 | + |
| 40 | +impl ColumnRenameExec { |
| 41 | + pub fn new( |
| 42 | + input: Arc<dyn ExecutionPlan>, |
| 43 | + output_schema: SchemaRef, |
| 44 | + name_mapping: HashMap<String, String>, |
| 45 | + ) -> Self { |
| 46 | + // PlanProperties must use output schema for DataFusion schema validation |
| 47 | + let eq_props = EquivalenceProperties::new(Arc::clone(&output_schema)); |
| 48 | + let properties = PlanProperties::new( |
| 49 | + eq_props, |
| 50 | + input.output_partitioning().clone(), |
| 51 | + input.pipeline_behavior(), |
| 52 | + Boundedness::Bounded, |
| 53 | + ); |
| 54 | + |
| 55 | + // Pre-compute reverse mapping once (new_name -> old_name) |
| 56 | + let reverse_mapping: HashMap<String, String> = name_mapping |
| 57 | + .iter() |
| 58 | + .map(|(old, new)| (new.clone(), old.clone())) |
| 59 | + .collect(); |
| 60 | + |
| 61 | + Self { |
| 62 | + input, |
| 63 | + output_schema, |
| 64 | + name_mapping, |
| 65 | + reverse_mapping: Arc::new(reverse_mapping), |
| 66 | + properties, |
| 67 | + } |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +impl DisplayAs for ColumnRenameExec { |
| 72 | + fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result { |
| 73 | + write!(f, "ColumnRenameExec: renames={}", self.name_mapping.len()) |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +impl ExecutionPlan for ColumnRenameExec { |
| 78 | + fn name(&self) -> &str { |
| 79 | + "ColumnRenameExec" |
| 80 | + } |
| 81 | + |
| 82 | + fn as_any(&self) -> &dyn Any { |
| 83 | + self |
| 84 | + } |
| 85 | + |
| 86 | + fn properties(&self) -> &PlanProperties { |
| 87 | + &self.properties |
| 88 | + } |
| 89 | + |
| 90 | + fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> { |
| 91 | + vec![&self.input] |
| 92 | + } |
| 93 | + |
| 94 | + fn with_new_children( |
| 95 | + self: Arc<Self>, |
| 96 | + children: Vec<Arc<dyn ExecutionPlan>>, |
| 97 | + ) -> DataFusionResult<Arc<dyn ExecutionPlan>> { |
| 98 | + if children.len() != 1 { |
| 99 | + return Err(DataFusionError::Internal( |
| 100 | + "ColumnRenameExec expects exactly one child".into(), |
| 101 | + )); |
| 102 | + } |
| 103 | + |
| 104 | + // Must call new() to rebuild properties from new child's partitioning |
| 105 | + Ok(Arc::new(ColumnRenameExec::new( |
| 106 | + Arc::clone(&children[0]), |
| 107 | + Arc::clone(&self.output_schema), |
| 108 | + self.name_mapping.clone(), |
| 109 | + ))) |
| 110 | + } |
| 111 | + |
| 112 | + fn execute( |
| 113 | + &self, |
| 114 | + partition: usize, |
| 115 | + context: Arc<TaskContext>, |
| 116 | + ) -> DataFusionResult<SendableRecordBatchStream> { |
| 117 | + let input_stream = self.input.execute(partition, context)?; |
| 118 | + |
| 119 | + Ok(Box::pin(ColumnRenameStream { |
| 120 | + input: input_stream, |
| 121 | + output_schema: Arc::clone(&self.output_schema), |
| 122 | + reverse_mapping: Arc::clone(&self.reverse_mapping), |
| 123 | + })) |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +/// Stream that renames columns in output batches |
| 128 | +struct ColumnRenameStream { |
| 129 | + input: SendableRecordBatchStream, |
| 130 | + output_schema: SchemaRef, |
| 131 | + /// Mapping from output column name -> input column name (for renamed columns only) |
| 132 | + reverse_mapping: Arc<HashMap<String, String>>, |
| 133 | +} |
| 134 | + |
| 135 | +impl Stream for ColumnRenameStream { |
| 136 | + type Item = DataFusionResult<RecordBatch>; |
| 137 | + |
| 138 | + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 139 | + match Pin::new(&mut self.input).poll_next(cx) { |
| 140 | + Poll::Ready(Some(Ok(batch))) => { |
| 141 | + let result = if batch.num_columns() == 0 { |
| 142 | + // COUNT(*) case: preserve row count with empty schema |
| 143 | + use arrow::record_batch::RecordBatchOptions; |
| 144 | + let options = RecordBatchOptions::new().with_row_count(Some(batch.num_rows())); |
| 145 | + RecordBatch::try_new_with_options( |
| 146 | + Arc::clone(&self.output_schema), |
| 147 | + vec![], |
| 148 | + &options, |
| 149 | + ) |
| 150 | + } else { |
| 151 | + // Build columns by looking up each output field in the input batch |
| 152 | + let input_schema = batch.schema(); |
| 153 | + let columns: Result<Vec<_>, _> = self |
| 154 | + .output_schema |
| 155 | + .fields() |
| 156 | + .iter() |
| 157 | + .map(|output_field| { |
| 158 | + // Check if this column was renamed (new_name -> old_name) |
| 159 | + let input_name = self |
| 160 | + .reverse_mapping |
| 161 | + .get(output_field.name()) |
| 162 | + .map(|s| s.as_str()) |
| 163 | + .unwrap_or_else(|| output_field.name().as_str()); |
| 164 | + |
| 165 | + input_schema |
| 166 | + .index_of(input_name) |
| 167 | + .map(|idx| batch.column(idx).clone()) |
| 168 | + }) |
| 169 | + .collect(); |
| 170 | + |
| 171 | + match columns { |
| 172 | + Ok(cols) => RecordBatch::try_new(Arc::clone(&self.output_schema), cols), |
| 173 | + Err(e) => Err(e), |
| 174 | + } |
| 175 | + }; |
| 176 | + |
| 177 | + match result { |
| 178 | + Ok(renamed_batch) => Poll::Ready(Some(Ok(renamed_batch))), |
| 179 | + Err(e) => { |
| 180 | + Poll::Ready(Some(Err(DataFusionError::ArrowError(Box::new(e), None)))) |
| 181 | + }, |
| 182 | + } |
| 183 | + }, |
| 184 | + Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e))), |
| 185 | + Poll::Ready(None) => Poll::Ready(None), |
| 186 | + Poll::Pending => Poll::Pending, |
| 187 | + } |
| 188 | + } |
| 189 | +} |
| 190 | + |
| 191 | +impl RecordBatchStream for ColumnRenameStream { |
| 192 | + fn schema(&self) -> SchemaRef { |
| 193 | + Arc::clone(&self.output_schema) |
| 194 | + } |
| 195 | +} |
| 196 | + |
| 197 | +#[cfg(test)] |
| 198 | +mod tests { |
| 199 | + use super::*; |
| 200 | + use arrow::datatypes::{DataType, Field, Schema}; |
| 201 | + use datafusion::physical_plan::EmptyRecordBatchStream; |
| 202 | + |
| 203 | + #[test] |
| 204 | + fn test_column_rename_stream_schema() { |
| 205 | + let input_schema = Arc::new(Schema::new(vec![Field::new( |
| 206 | + "old_col", |
| 207 | + DataType::Int32, |
| 208 | + false, |
| 209 | + )])); |
| 210 | + |
| 211 | + let output_schema = Arc::new(Schema::new(vec![Field::new( |
| 212 | + "new_col", |
| 213 | + DataType::Int32, |
| 214 | + false, |
| 215 | + )])); |
| 216 | + |
| 217 | + let mut reverse_mapping = HashMap::new(); |
| 218 | + reverse_mapping.insert("new_col".to_string(), "old_col".to_string()); |
| 219 | + |
| 220 | + let stream = ColumnRenameStream { |
| 221 | + input: Box::pin(EmptyRecordBatchStream::new(input_schema)), |
| 222 | + output_schema: Arc::clone(&output_schema), |
| 223 | + reverse_mapping: Arc::new(reverse_mapping), |
| 224 | + }; |
| 225 | + |
| 226 | + // The stream should report the output schema |
| 227 | + assert_eq!(stream.schema().field(0).name(), "new_col"); |
| 228 | + } |
| 229 | +} |
0 commit comments