datafusion-ducklake 0.8.0

DuckLake query engine for rust, built with datafusion.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
//! Custom execution plan for renaming columns
//!
//! This module implements a DataFusion execution plan that wraps a scan
//! and renames columns from their original Parquet names to current DuckLake names.
//! This is needed when columns have been renamed in DuckLake metadata but the
//! Parquet files still have the original column names.

use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use arrow::datatypes::SchemaRef;
use arrow::record_batch::RecordBatch;
use datafusion::common::config::ConfigOptions;
use datafusion::common::tree_node::TreeNodeRecursion;
use datafusion::common::tree_node::{Transformed, TreeNode};
use datafusion::common::{ScalarValue, Statistics};
use datafusion::error::{DataFusionError, Result as DataFusionResult};
use datafusion::execution::{RecordBatchStream, SendableRecordBatchStream, TaskContext};
use datafusion::physical_expr::EquivalenceProperties;
use datafusion::physical_expr::expressions::Column;
use datafusion::physical_expr::{PhysicalExpr, PhysicalSortExpr};
use datafusion::physical_plan::execution_plan::Boundedness;
use datafusion::physical_plan::filter_pushdown::{
    ChildFilterDescription, FilterDescription, FilterPushdownPhase,
};
use datafusion::physical_plan::sort_pushdown::SortOrderPushdownResult;
use datafusion::physical_plan::statistics::{ChildStats, StatisticsArgs};
use datafusion::physical_plan::{
    DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties,
};
use futures::Stream;

/// Custom execution plan that renames columns from Parquet file names to current DuckLake names
#[derive(Debug)]
pub struct ColumnRenameExec {
    /// The input execution plan (typically ParquetExec)
    input: Arc<dyn ExecutionPlan>,
    /// Output schema with renamed columns
    output_schema: SchemaRef,
    /// Mapping from old (Parquet) column names to new (DuckLake) column names
    name_mapping: HashMap<String, String>,
    /// Reverse mapping: new name -> old name, for looking up input columns
    reverse_mapping: Arc<HashMap<String, String>>,
    /// Per-file values synthesized from Hive path segments.
    constants: Arc<HashMap<String, ScalarValue>>,
    /// Cached plan properties with updated schema
    properties: Arc<PlanProperties>,
}

impl ColumnRenameExec {
    pub fn new(
        input: Arc<dyn ExecutionPlan>,
        output_schema: SchemaRef,
        name_mapping: HashMap<String, String>,
    ) -> Self {
        Self::new_with_constants(input, output_schema, name_mapping, HashMap::new())
    }

    pub fn new_with_constants(
        input: Arc<dyn ExecutionPlan>,
        output_schema: SchemaRef,
        name_mapping: HashMap<String, String>,
        constants: HashMap<String, ScalarValue>,
    ) -> Self {
        // PlanProperties must use output schema for DataFusion schema validation
        let eq_props = EquivalenceProperties::new(Arc::clone(&output_schema));
        let properties = Arc::new(PlanProperties::new(
            eq_props,
            input.output_partitioning().clone(),
            input.pipeline_behavior(),
            Boundedness::Bounded,
        ));

        // Pre-compute reverse mapping once (new_name -> old_name)
        let reverse_mapping: HashMap<String, String> = name_mapping
            .iter()
            .map(|(old, new)| (new.clone(), old.clone()))
            .collect();

        Self {
            input,
            output_schema,
            name_mapping,
            reverse_mapping: Arc::new(reverse_mapping),
            constants: Arc::new(constants),
            properties,
        }
    }

    /// Returns whether this node only renames columns without casting,
    /// projecting, or synthesizing values.
    ///
    /// Nested field metadata is ignored: a read schema describes the file's
    /// nested nodes with the `PARQUET:field_id` the file tags them with, so it
    /// differs from the catalog type by metadata alone even when the values are
    /// identical. Dropping that metadata on the way out is a zero-copy relabel,
    /// not a conversion, so it must not cost the scan its filter and limit
    /// pushdown.
    pub fn is_pure_type_preserving_rename(&self) -> bool {
        let input_schema = self.input.schema();
        self.constants.is_empty()
            && input_schema.fields().len() == self.output_schema.fields().len()
            && input_schema
                .fields()
                .iter()
                .zip(self.output_schema.fields())
                .all(|(input, output)| {
                    types_equal_ignoring_field_metadata(input.data_type(), output.data_type())
                        && self
                            .reverse_mapping
                            .get(output.name())
                            .map(String::as_str)
                            .unwrap_or(output.name())
                            == input.name()
                })
    }

    /// Returns whether every output column is a type-preserving relabel of an
    /// input column, allowing input columns the output does not carry to be
    /// **dropped**.
    ///
    /// Weaker than [`Self::is_pure_type_preserving_rename`], which additionally
    /// requires equal field counts. On a positional scan this node drops the
    /// internal physical-position column, so the counts always differ — yet a
    /// predicate over the columns that *do* survive still means exactly the same
    /// thing on either side of the node, because each is a relabel of one input
    /// column at an unchanged type.
    ///
    /// Sufficient for filter pushdown. NOT used for limit pushdown, which keeps
    /// the stricter predicate: there is no need to widen it, and a `LIMIT` would
    /// stop at `DeleteFilterExec` below regardless.
    pub(crate) fn is_type_preserving_projection(&self) -> bool {
        let input_schema = self.input.schema();
        self.output_schema.fields().iter().all(|output| {
            let input_name = self
                .reverse_mapping
                .get(output.name())
                .map(String::as_str)
                .unwrap_or(output.name());
            input_schema.field_with_name(input_name).is_ok_and(|input| {
                types_equal_ignoring_field_metadata(input.data_type(), output.data_type())
            })
        })
    }

    /// Restate sort keys written against this node's output schema in the
    /// child's column space, or `None` when any key does not land on a
    /// type-preserving input column.
    ///
    /// Unlike [`Self::remap_filter_to_input`], this rewrites the column
    /// **index** as well as the name. A pushed-down filter is re-resolved
    /// against the child schema by name
    /// ([`ChildFilterDescription::from_child`]); a pushed-down sort key is not
    /// re-resolved at all, so an index left in output space would silently sort
    /// the child on whichever column happens to sit at that position.
    ///
    /// A key that reaches a synthesized Hive constant returns `None`: the
    /// constant exists only above this node, so the child cannot order by it.
    fn remap_sort_to_input(
        &self,
        order: &[PhysicalSortExpr],
    ) -> DataFusionResult<Option<Vec<PhysicalSortExpr>>> {
        if !self.is_type_preserving_projection() {
            return Ok(None);
        }

        let input_schema = self.input.schema();
        let mut remapped = Vec::with_capacity(order.len());
        for sort in order {
            let mut valid = true;
            let expr = Arc::clone(&sort.expr)
                .transform_down(|expr| {
                    let Some(column) = expr.downcast_ref::<Column>() else {
                        return Ok(Transformed::no(expr));
                    };
                    if self
                        .output_schema
                        .fields()
                        .get(column.index())
                        .is_none_or(|field| field.name() != column.name())
                    {
                        valid = false;
                        return Ok(Transformed::complete(expr));
                    }
                    let input_name = self
                        .reverse_mapping
                        .get(column.name())
                        .map(String::as_str)
                        .unwrap_or_else(|| column.name());
                    match input_schema.index_of(input_name) {
                        Ok(index) => Ok(Transformed::yes(
                            Arc::new(Column::new(input_name, index)) as Arc<dyn PhysicalExpr>
                        )),
                        Err(_) => {
                            valid = false;
                            Ok(Transformed::complete(expr))
                        },
                    }
                })?
                .data;
            if !valid {
                return Ok(None);
            }
            remapped.push(PhysicalSortExpr::new(expr, sort.options));
        }
        Ok(Some(remapped))
    }

    /// Remap a predicate over the catalog schema to the physical child schema.
    ///
    /// Rewrites column **names** only. Column indices are left as they are
    /// because [`ChildFilterDescription::from_child`] re-resolves every column
    /// against the child schema by name; the output and input indices differ
    /// whenever this node drops or reorders columns, so rewriting them here
    /// would be both redundant and wrong.
    ///
    /// Available only for a type-preserving projection: pushing predicates
    /// through casts can change errors and comparison semantics, and a filter
    /// referencing a column this node synthesizes has nothing to bind to below.
    pub fn remap_filter_to_input(
        &self,
        filter: Arc<dyn PhysicalExpr>,
    ) -> DataFusionResult<Option<Arc<dyn PhysicalExpr>>> {
        if !self.is_type_preserving_projection() {
            return Ok(None);
        }

        let output_schema = Arc::clone(&self.output_schema);
        let mut valid = true;
        let transformed = filter.transform_down(|expr| {
            let Some(column) = expr.downcast_ref::<Column>() else {
                return Ok(Transformed::no(expr));
            };
            let index = column.index();
            if output_schema
                .fields()
                .get(index)
                .is_none_or(|field| field.name() != column.name())
            {
                valid = false;
                return Ok(Transformed::complete(expr));
            }

            let input_name = self
                .reverse_mapping
                .get(column.name())
                .map(String::as_str)
                .unwrap_or(column.name());
            Ok(Transformed::yes(Arc::new(Column::new(input_name, index))))
        })?;

        Ok(valid.then_some(transformed.data))
    }
}

impl DisplayAs for ColumnRenameExec {
    fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "ColumnRenameExec: renames={}", self.name_mapping.len())?;
        if !self.constants.is_empty() {
            write!(f, ", constants={}", self.constants.len())?;
        }
        Ok(())
    }
}

impl ExecutionPlan for ColumnRenameExec {
    fn apply_expressions(
        &self,
        _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> DataFusionResult<TreeNodeRecursion>,
    ) -> DataFusionResult<TreeNodeRecursion> {
        Ok(TreeNodeRecursion::Continue)
    }

    fn name(&self) -> &str {
        "ColumnRenameExec"
    }

    fn properties(&self) -> &Arc<PlanProperties> {
        &self.properties
    }

    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
        vec![&self.input]
    }

    /// The input's ROW COUNT, and nothing else.
    ///
    /// This node maps each input row to exactly one output row, so the count
    /// carries through unchanged — which is what lets an unfiltered `count(*)`
    /// still fold when a scan is wrapped here (a table with deletes unions a
    /// renamed branch in).
    ///
    /// Column statistics are deliberately NOT forwarded. This node renames
    /// columns, can coerce a type, and can materialise partition constants, so an
    /// inherited bound is not guaranteed to describe the output column sitting at
    /// the same index. Row counts need no such correspondence; bounds do.
    fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
        vec![ChildStats::At(partition)]
    }

    fn statistics_from_inputs(
        &self,
        input_stats: &[Arc<Statistics>],
        _args: &StatisticsArgs,
    ) -> DataFusionResult<Arc<Statistics>> {
        let mut statistics = Statistics::new_unknown(&self.schema());
        if let Some(input) = input_stats.first() {
            statistics.num_rows = input.num_rows;
            // Inexact for the same reason the delete filter downgrades it: this
            // node can add constant columns and drops the internal position
            // column, so the input's figure no longer describes the output.
            statistics.total_byte_size = input.total_byte_size.to_inexact();
        }
        Ok(Arc::new(statistics))
    }

    fn with_new_children(
        self: Arc<Self>,
        children: Vec<Arc<dyn ExecutionPlan>>,
    ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
        if children.len() != 1 {
            return Err(DataFusionError::Internal(
                "ColumnRenameExec expects exactly one child".into(),
            ));
        }

        // Must call new() to rebuild properties from new child's partitioning
        Ok(Arc::new(ColumnRenameExec::new_with_constants(
            Arc::clone(&children[0]),
            Arc::clone(&self.output_schema),
            self.name_mapping.clone(),
            self.constants.as_ref().clone(),
        )))
    }

    fn supports_limit_pushdown(&self) -> bool {
        self.is_pure_type_preserving_rename()
    }

    fn gather_filters_for_pushdown(
        &self,
        _phase: FilterPushdownPhase,
        parent_filters: Vec<Arc<dyn PhysicalExpr>>,
        _config: &ConfigOptions,
    ) -> DataFusionResult<FilterDescription> {
        if !self.is_type_preserving_projection() {
            return Ok(FilterDescription::new()
                .with_child(ChildFilterDescription::all_unsupported(&parent_filters)));
        }

        let remapped = parent_filters
            .iter()
            .map(|filter| self.remap_filter_to_input(Arc::clone(filter)))
            .collect::<DataFusionResult<Option<Vec<_>>>>()?;
        let child = match remapped {
            Some(remapped) => ChildFilterDescription::from_child(&remapped, &self.input)?,
            None => ChildFilterDescription::all_unsupported(&parent_filters),
        };
        Ok(FilterDescription::new().with_child(child))
    }

    /// Renaming a column cannot reorder rows, so any ordering the child can
    /// serve survives this node. Delegating matters for `ORDER BY … LIMIT n`:
    /// the scan reads its files in the order the sort asks for, which is what
    /// lets the Top-N boundary tighten early enough to skip the rest.
    ///
    /// Downgraded to `Inexact` even when the child answers `Exact`. `Exact`
    /// licenses the optimizer to delete the `SortExec` outright, which is only
    /// sound from a node that republishes the ordering in its own
    /// `PlanProperties` — and this one builds a fresh, empty
    /// `EquivalenceProperties` over the output schema. `Inexact` keeps the sort
    /// and still gets the file reorder, which is the whole benefit here. Lift
    /// this only together with the equivalence properties.
    fn try_pushdown_sort(
        &self,
        order: &[PhysicalSortExpr],
    ) -> DataFusionResult<SortOrderPushdownResult<Arc<dyn ExecutionPlan>>> {
        let Some(remapped) = self.remap_sort_to_input(order)? else {
            return Ok(SortOrderPushdownResult::Unsupported);
        };
        self.input
            .try_pushdown_sort(&remapped)?
            .into_inexact()
            .try_map(|inner| -> DataFusionResult<Arc<dyn ExecutionPlan>> {
                Ok(Arc::new(ColumnRenameExec::new_with_constants(
                    inner,
                    Arc::clone(&self.output_schema),
                    self.name_mapping.clone(),
                    self.constants.as_ref().clone(),
                )))
            })
    }

    fn execute(
        &self,
        partition: usize,
        context: Arc<TaskContext>,
    ) -> DataFusionResult<SendableRecordBatchStream> {
        let input_stream = self.input.execute(partition, context)?;

        Ok(Box::pin(ColumnRenameStream {
            input: input_stream,
            output_schema: Arc::clone(&self.output_schema),
            reverse_mapping: Arc::clone(&self.reverse_mapping),
            constants: Arc::clone(&self.constants),
        }))
    }
}

/// Stream that renames columns in output batches
struct ColumnRenameStream {
    input: SendableRecordBatchStream,
    output_schema: SchemaRef,
    /// Mapping from output column name -> input column name (for renamed columns only)
    reverse_mapping: Arc<HashMap<String, String>>,
    constants: Arc<HashMap<String, ScalarValue>>,
}

impl Stream for ColumnRenameStream {
    type Item = DataFusionResult<RecordBatch>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        match Pin::new(&mut self.input).poll_next(cx) {
            Poll::Ready(Some(Ok(batch))) => {
                let result: DataFusionResult<RecordBatch> =
                    if self.output_schema.fields().is_empty() {
                        // Zero OUTPUT columns (e.g. COUNT(*)): preserve the row count
                        // with an empty schema. This must key off the output schema,
                        // not the input: on positional paths the input still carries
                        // the internal `__ducklake_row_pos` column (1 input column),
                        // yet the output is zero columns and the count must survive.
                        use arrow::record_batch::RecordBatchOptions;
                        let options =
                            RecordBatchOptions::new().with_row_count(Some(batch.num_rows()));
                        RecordBatch::try_new_with_options(
                            Arc::clone(&self.output_schema),
                            vec![],
                            &options,
                        )
                        .map_err(|e| DataFusionError::ArrowError(Box::new(e), None))
                    } else {
                        // Build columns by looking up each output field in the input batch
                        let input_schema = batch.schema();
                        let columns: DataFusionResult<Vec<_>> = self
                            .output_schema
                            .fields()
                            .iter()
                            .map(|output_field| {
                                if let Some(value) = self.constants.get(output_field.name()) {
                                    return value.to_array_of_size(batch.num_rows());
                                }
                                // Check if this column was renamed (new_name -> old_name)
                                let input_name = self
                                    .reverse_mapping
                                    .get(output_field.name())
                                    .map(|s| s.as_str())
                                    .unwrap_or_else(|| output_field.name().as_str());

                                let idx = input_schema
                                    .index_of(input_name)
                                    .map_err(|e| DataFusionError::ArrowError(Box::new(e), None))?;
                                // Coerce the column read from the file back to the
                                // catalog (output) type, keeping the provider
                                // self-consistent: it advertises and emits the catalog
                                // schema regardless of the file's physical Arrow type.
                                // Identical types clone cheaply.
                                coerce_column(batch.column(idx), output_field.data_type())
                            })
                            .collect();

                        columns.and_then(|cols| {
                            record_batch_with_schema(Arc::clone(&self.output_schema), cols)
                                .map_err(|e| DataFusionError::ArrowError(Box::new(e), None))
                        })
                    };

                Poll::Ready(Some(result))
            },
            Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e))),
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }
}

impl RecordBatchStream for ColumnRenameStream {
    fn schema(&self) -> SchemaRef {
        Arc::clone(&self.output_schema)
    }
}

/// Compare two Arrow types, ignoring the metadata carried by nested fields.
///
/// Names, nullability and value types still have to match at every level. All
/// nested field metadata is disregarded, not only the `PARQUET:field_id` this
/// exists for: metadata annotates a node, it never decides what its values are,
/// so a difference confined to it is a relabel rather than a conversion. The
/// read path attaches no other nested metadata.
///
/// Types with no nested fields, and the container types the read path never
/// produces (dictionaries, unions, run-end encoding), fall back to strict
/// equality.
pub(crate) fn types_equal_ignoring_field_metadata(
    left: &arrow::datatypes::DataType,
    right: &arrow::datatypes::DataType,
) -> bool {
    use arrow::datatypes::{DataType, Field};

    fn fields_equal(left: &Field, right: &Field) -> bool {
        left.name() == right.name()
            && left.is_nullable() == right.is_nullable()
            && types_equal_ignoring_field_metadata(left.data_type(), right.data_type())
    }

    match (left, right) {
        (DataType::List(left), DataType::List(right))
        | (DataType::LargeList(left), DataType::LargeList(right))
        | (DataType::ListView(left), DataType::ListView(right))
        | (DataType::LargeListView(left), DataType::LargeListView(right)) => {
            fields_equal(left, right)
        },
        (DataType::FixedSizeList(left, left_size), DataType::FixedSizeList(right, right_size)) => {
            left_size == right_size && fields_equal(left, right)
        },
        (DataType::Map(left, left_sorted), DataType::Map(right, right_sorted)) => {
            left_sorted == right_sorted && fields_equal(left, right)
        },
        (DataType::Struct(left), DataType::Struct(right)) => {
            left.len() == right.len()
                && left
                    .iter()
                    .zip(right.iter())
                    .all(|(left, right)| fields_equal(left, right))
        },
        _ => left == right,
    }
}

/// Coerce a column read from a parquet file to the catalog's declared type.
///
/// The physical Arrow type in a file can differ from the catalog type for list
/// columns: a DuckDB `ARRAY` may materialise as `FixedSizeList(N)` while the
/// catalog declares a variable `List`, and externally-written files often carry
/// an empty list child field name (`""`) where the catalog uses `"item"`.
///
/// `arrow::compute::cast` handles the structural value conversion
/// (`FixedSizeList` ↔ `List`, element-type changes) but leaves the list child
/// **field name** as-is, so a pure child-name difference round-trips unchanged
/// and would fail `RecordBatch::try_new`. After casting we therefore re-stamp the
/// array's `DataType` to the target when only nested field metadata differs —
/// the buffer layout is identical, so this is a zero-copy metadata swap.
pub(crate) fn coerce_column(
    col: &arrow::array::ArrayRef,
    target: &arrow::datatypes::DataType,
) -> DataFusionResult<arrow::array::ArrayRef> {
    use arrow::array::Array;

    let is_nested = matches!(
        target,
        arrow::datatypes::DataType::List(_)
            | arrow::datatypes::DataType::LargeList(_)
            | arrow::datatypes::DataType::FixedSizeList(_, _)
            | arrow::datatypes::DataType::Map(_, _)
            | arrow::datatypes::DataType::Struct(_)
    );
    if col.data_type() == target && !is_nested {
        return Ok(Arc::clone(col));
    }

    let casted = if col.data_type() == target {
        Arc::clone(col)
    } else {
        arrow::compute::cast(col, target)
            .map_err(|e| DataFusionError::ArrowError(Box::new(e), None))?
    };
    if casted.data_type() == target && !is_nested {
        return Ok(casted);
    }

    array_with_data_type(&casted, target)
        .map_err(|e| DataFusionError::ArrowError(Box::new(e), None))
}

pub(crate) fn array_with_data_type(
    array: &arrow::array::ArrayRef,
    data_type: &arrow::datatypes::DataType,
) -> Result<arrow::array::ArrayRef, arrow::error::ArrowError> {
    use arrow::array::{Array, ArrayData, make_array};
    use arrow::datatypes::DataType;
    use arrow::error::ArrowError;

    fn rewrite(data: &ArrayData, data_type: &DataType) -> Result<ArrayData, ArrowError> {
        let is_nested = matches!(
            data_type,
            DataType::List(_)
                | DataType::LargeList(_)
                | DataType::FixedSizeList(_, _)
                | DataType::Map(_, _)
                | DataType::Struct(_)
        );
        if data.data_type() == data_type && !is_nested {
            return Ok(data.clone());
        }
        let child_types = match data_type {
            DataType::List(field)
            | DataType::LargeList(field)
            | DataType::FixedSizeList(field, _)
            | DataType::Map(field, _) => vec![field.data_type()],
            DataType::Struct(fields) => fields.iter().map(|field| field.data_type()).collect(),
            _ => {
                return Err(ArrowError::InvalidArgumentError(format!(
                    "cannot apply array type {:?} as {data_type:?}",
                    data.data_type(),
                )));
            },
        };
        if child_types.len() != data.child_data().len() {
            return Err(ArrowError::InvalidArgumentError(format!(
                "array type {:?} has {} children, expected {} for {data_type:?}",
                data.data_type(),
                data.child_data().len(),
                child_types.len(),
            )));
        }
        let children = data
            .child_data()
            .iter()
            .zip(child_types)
            .map(|(child, child_type)| rewrite(child, child_type))
            .collect::<Result<Vec<_>, _>>()?;
        data.clone()
            .into_builder()
            .data_type(data_type.clone())
            .child_data(children)
            .build()
    }

    Ok(make_array(rewrite(&array.to_data(), data_type)?))
}

pub(crate) fn record_batch_with_schema(
    schema: arrow::datatypes::SchemaRef,
    columns: Vec<arrow::array::ArrayRef>,
) -> Result<arrow::record_batch::RecordBatch, arrow::error::ArrowError> {
    use arrow::datatypes::{Field, Schema};
    use arrow::record_batch::RecordBatch;

    let fields = schema
        .fields()
        .iter()
        .zip(&columns)
        .map(|(field, column)| {
            Field::new(
                field.name(),
                column.data_type().clone(),
                field.is_nullable(),
            )
            .with_metadata(field.metadata().clone())
        })
        .collect::<Vec<_>>();
    let actual_schema = Arc::new(Schema::new_with_metadata(fields, schema.metadata().clone()));
    RecordBatch::try_new(actual_schema, columns)?.with_schema(schema)
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow::datatypes::{DataType, Field, Schema};
    use datafusion::physical_plan::EmptyRecordBatchStream;
    use datafusion::physical_plan::empty::EmptyExec;
    use datafusion::physical_plan::filter_pushdown::PushedDown;

    #[test]
    fn test_column_rename_stream_schema() {
        let input_schema = Arc::new(Schema::new(vec![Field::new(
            "old_col",
            DataType::Int32,
            false,
        )]));

        let output_schema = Arc::new(Schema::new(vec![Field::new(
            "new_col",
            DataType::Int32,
            false,
        )]));

        let mut reverse_mapping = HashMap::new();
        reverse_mapping.insert("new_col".to_string(), "old_col".to_string());

        let stream = ColumnRenameStream {
            input: Box::pin(EmptyRecordBatchStream::new(input_schema)),
            output_schema: Arc::clone(&output_schema),
            reverse_mapping: Arc::new(reverse_mapping),
            constants: Arc::new(HashMap::new()),
        };

        // The stream should report the output schema
        assert_eq!(stream.schema().field(0).name(), "new_col");
    }

    #[test]
    fn coerce_column_restamps_nested_field_metadata() {
        use arrow::{
            array::{ArrayRef, Int32Array, RecordBatch, StructArray},
            datatypes::Fields,
        };

        let source_fields =
            Fields::from(vec![Arc::new(Field::new("value", DataType::Int32, false))]);
        let source: ArrayRef = Arc::new(StructArray::new(
            source_fields,
            vec![Arc::new(Int32Array::from(vec![1, 2]))],
            None,
        ));
        let target_field = Arc::new(Field::new("value", DataType::Int32, false).with_metadata(
            HashMap::from([("PARQUET:field_id".to_string(), "2".to_string())]),
        ));
        let target = DataType::Struct(Fields::from(vec![target_field]));

        let coerced = coerce_column(&source, &target).unwrap();
        let schema = Arc::new(Schema::new(vec![Field::new(
            "nested",
            target.clone(),
            false,
        )]));
        let batch = RecordBatch::try_new(schema, vec![coerced]).unwrap();

        let DataType::Struct(fields) = batch.column(0).data_type() else {
            panic!("expected struct");
        };
        assert_eq!(
            fields[0].metadata().get("PARQUET:field_id"),
            Some(&"2".to_string())
        );
    }

    #[test]
    fn pure_rename_remaps_filters_and_allows_limit_pushdown() {
        let input_schema = Arc::new(Schema::new(vec![Field::new(
            "old_col",
            DataType::Int32,
            false,
        )]));
        let output_schema = Arc::new(Schema::new(vec![Field::new(
            "new_col",
            DataType::Int32,
            false,
        )]));
        let input: Arc<dyn ExecutionPlan> = Arc::new(EmptyExec::new(input_schema));
        let exec = ColumnRenameExec::new(
            input,
            output_schema,
            HashMap::from([("old_col".to_string(), "new_col".to_string())]),
        );
        let filter: Arc<dyn PhysicalExpr> = Arc::new(Column::new("new_col", 0));

        assert!(exec.is_pure_type_preserving_rename());
        assert!(exec.supports_limit_pushdown());
        let remapped = exec
            .remap_filter_to_input(Arc::clone(&filter))
            .unwrap()
            .unwrap();
        let column = remapped.downcast_ref::<Column>().unwrap();
        assert_eq!(column.name(), "old_col");
        assert_eq!(column.index(), 0);

        let description = exec
            .gather_filters_for_pushdown(
                FilterPushdownPhase::Pre,
                vec![filter],
                &ConfigOptions::new(),
            )
            .unwrap();
        let pushed = description.parent_filters();
        assert!(matches!(pushed[0][0].discriminant, PushedDown::Yes));
        let column = pushed[0][0].predicate.downcast_ref::<Column>().unwrap();
        assert_eq!(column.name(), "old_col");
        assert_eq!(column.index(), 0);
    }

    /// A read schema tags a nested column's children with the field ids the file
    /// records; the catalog schema does not. Stripping that metadata on the way
    /// out is a relabel, not a cast, so the scan keeps its pushdown.
    #[test]
    fn nested_field_metadata_alone_still_allows_pushdown() {
        let element = |metadata: Option<(&str, &str)>| {
            let field = Field::new("element", DataType::Float32, true);
            match metadata {
                Some((key, value)) => {
                    field.with_metadata(HashMap::from([(key.to_string(), value.to_string())]))
                },
                None => field,
            }
        };
        let input_schema = Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int32, true),
            Field::new(
                "v",
                DataType::List(Arc::new(element(Some(("PARQUET:field_id", "3"))))),
                true,
            ),
        ]));
        let output_schema = Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int32, true),
            Field::new("v", DataType::List(Arc::new(element(None))), true),
        ]));
        let input: Arc<dyn ExecutionPlan> = Arc::new(EmptyExec::new(input_schema));
        let exec = ColumnRenameExec::new(input, output_schema, HashMap::new());
        let filter: Arc<dyn PhysicalExpr> = Arc::new(Column::new("id", 0));

        assert!(exec.is_pure_type_preserving_rename());
        assert!(exec.supports_limit_pushdown());
        let description = exec
            .gather_filters_for_pushdown(
                FilterPushdownPhase::Pre,
                vec![filter],
                &ConfigOptions::new(),
            )
            .unwrap();
        assert!(matches!(
            description.parent_filters()[0][0].discriminant,
            PushedDown::Yes
        ));
    }

    /// The relaxation is metadata-only: a nested child renamed or retyped is
    /// still a real conversion and must block pushdown.
    #[test]
    fn nested_child_name_or_type_difference_blocks_pushdown() {
        let list = |child: Field| DataType::List(Arc::new(child));
        let cases = [
            (
                list(Field::new("element", DataType::Float32, true)),
                list(Field::new("item", DataType::Float32, true)),
            ),
            (
                list(Field::new("element", DataType::Float32, true)),
                list(Field::new("element", DataType::Float64, true)),
            ),
            (
                list(Field::new("element", DataType::Float32, false)),
                list(Field::new("element", DataType::Float32, true)),
            ),
        ];

        for (input_type, output_type) in cases {
            let input: Arc<dyn ExecutionPlan> = Arc::new(EmptyExec::new(Arc::new(Schema::new(
                vec![Field::new("v", input_type.clone(), true)],
            ))));
            let exec = ColumnRenameExec::new(
                input,
                Arc::new(Schema::new(vec![Field::new(
                    "v",
                    output_type.clone(),
                    true,
                )])),
                HashMap::new(),
            );
            assert!(
                !exec.is_pure_type_preserving_rename(),
                "{input_type:?} -> {output_type:?} is a conversion, not a relabel"
            );
        }
    }

    #[test]
    fn casts_do_not_allow_filter_or_limit_pushdown() {
        let input_schema = Arc::new(Schema::new(vec![Field::new(
            "old_col",
            DataType::Int32,
            false,
        )]));
        let output_schema = Arc::new(Schema::new(vec![Field::new(
            "new_col",
            DataType::Int64,
            false,
        )]));
        let input: Arc<dyn ExecutionPlan> = Arc::new(EmptyExec::new(input_schema));
        let exec = ColumnRenameExec::new(
            input,
            output_schema,
            HashMap::from([("old_col".to_string(), "new_col".to_string())]),
        );
        let filter: Arc<dyn PhysicalExpr> = Arc::new(Column::new("new_col", 0));

        assert!(!exec.is_pure_type_preserving_rename());
        assert!(!exec.supports_limit_pushdown());
        assert!(
            exec.remap_filter_to_input(Arc::clone(&filter))
                .unwrap()
                .is_none()
        );
        let description = exec
            .gather_filters_for_pushdown(
                FilterPushdownPhase::Pre,
                vec![filter],
                &ConfigOptions::new(),
            )
            .unwrap();
        assert!(matches!(
            description.parent_filters()[0][0].discriminant,
            PushedDown::No
        ));
    }
}