Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
datafusion-common 48.0.0 - Docs.rs
[go: Go Back, main page]

datafusion-common 48.0.0

Common functionality for DataFusion query engine
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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use arrow::array::{Array, NullArray, UInt64Array};
use arrow::array::{ArrayRef, BooleanArray};
use arrow::datatypes::{FieldRef, Schema, SchemaRef};
use std::collections::HashSet;
use std::sync::Arc;

use crate::error::DataFusionError;
use crate::stats::Precision;
use crate::{Column, Statistics};
use crate::{ColumnStatistics, ScalarValue};

/// A source of runtime statistical information to [`PruningPredicate`]s.
///
/// # Supported Information
///
/// 1. Minimum and maximum values for columns
///
/// 2. Null counts and row counts for columns
///
/// 3. Whether the values in a column are contained in a set of literals
///
/// # Vectorized Interface
///
/// Information for containers / files are returned as Arrow [`ArrayRef`], so
/// the evaluation happens once on a single `RecordBatch`, which amortizes the
/// overhead of evaluating the predicate. This is important when pruning 1000s
/// of containers which often happens in analytic systems that have 1000s of
/// potential files to consider.
///
/// For example, for the following three files with a single column `a`:
/// ```text
/// file1: column a: min=5, max=10
/// file2: column a: No stats
/// file2: column a: min=20, max=30
/// ```
///
/// PruningStatistics would return:
///
/// ```text
/// min_values("a") -> Some([5, Null, 20])
/// max_values("a") -> Some([10, Null, 30])
/// min_values("X") -> None
/// ```
///
/// [`PruningPredicate`]: https://docs.rs/datafusion/latest/datafusion/physical_optimizer/pruning/struct.PruningPredicate.html
pub trait PruningStatistics {
    /// Return the minimum values for the named column, if known.
    ///
    /// If the minimum value for a particular container is not known, the
    /// returned array should have `null` in that row. If the minimum value is
    /// not known for any row, return `None`.
    ///
    /// Note: the returned array must contain [`Self::num_containers`] rows
    fn min_values(&self, column: &Column) -> Option<ArrayRef>;

    /// Return the maximum values for the named column, if known.
    ///
    /// See [`Self::min_values`] for when to return `None` and null values.
    ///
    /// Note: the returned array must contain [`Self::num_containers`] rows
    fn max_values(&self, column: &Column) -> Option<ArrayRef>;

    /// Return the number of containers (e.g. Row Groups) being pruned with
    /// these statistics.
    ///
    /// This value corresponds to the size of the [`ArrayRef`] returned by
    /// [`Self::min_values`], [`Self::max_values`], [`Self::null_counts`],
    /// and [`Self::row_counts`].
    fn num_containers(&self) -> usize;

    /// Return the number of null values for the named column as an
    /// [`UInt64Array`]
    ///
    /// See [`Self::min_values`] for when to return `None` and null values.
    ///
    /// Note: the returned array must contain [`Self::num_containers`] rows
    ///
    /// [`UInt64Array`]: arrow::array::UInt64Array
    fn null_counts(&self, column: &Column) -> Option<ArrayRef>;

    /// Return the number of rows for the named column in each container
    /// as an [`UInt64Array`].
    ///
    /// See [`Self::min_values`] for when to return `None` and null values.
    ///
    /// Note: the returned array must contain [`Self::num_containers`] rows
    ///
    /// [`UInt64Array`]: arrow::array::UInt64Array
    fn row_counts(&self, column: &Column) -> Option<ArrayRef>;

    /// Returns [`BooleanArray`] where each row represents information known
    /// about specific literal `values` in a column.
    ///
    /// For example, Parquet Bloom Filters implement this API to communicate
    /// that `values` are known not to be present in a Row Group.
    ///
    /// The returned array has one row for each container, with the following
    /// meanings:
    /// * `true` if the values in `column`  ONLY contain values from `values`
    /// * `false` if the values in `column` are NOT ANY of `values`
    /// * `null` if the neither of the above holds or is unknown.
    ///
    /// If these statistics can not determine column membership for any
    /// container, return `None` (the default).
    ///
    /// Note: the returned array must contain [`Self::num_containers`] rows
    fn contained(
        &self,
        column: &Column,
        values: &HashSet<ScalarValue>,
    ) -> Option<BooleanArray>;
}

/// Prune files based on their partition values.
///
/// This is used both at planning time and execution time to prune
/// files based on their partition values.
/// This feeds into [`CompositePruningStatistics`] to allow pruning
/// with filters that depend both on partition columns and data columns
/// (e.g. `WHERE partition_col = data_col`).
#[derive(Clone)]
pub struct PartitionPruningStatistics {
    /// Values for each column for each container.
    ///
    /// The outer vectors represent the columns while the inner vectors
    /// represent the containers. The order must match the order of the
    /// partition columns in [`PartitionPruningStatistics::partition_schema`].
    partition_values: Vec<ArrayRef>,
    /// The number of containers.
    ///
    /// Stored since the partition values are column-major and if
    /// there are no columns we wouldn't know the number of containers.
    num_containers: usize,
    /// The schema of the partition columns.
    ///
    /// This must **not** be the schema of the entire file or table: it must
    /// only be the schema of the partition columns, in the same order as the
    /// values in [`PartitionPruningStatistics::partition_values`].
    partition_schema: SchemaRef,
}

impl PartitionPruningStatistics {
    /// Create a new instance of [`PartitionPruningStatistics`].
    ///
    /// Args:
    /// * `partition_values`: A vector of vectors of [`ScalarValue`]s.
    ///   The outer vector represents the containers while the inner
    ///   vector represents the partition values for each column.
    ///   Note that this is the **opposite** of the order of the
    ///   partition columns in `PartitionPruningStatistics::partition_schema`.
    /// * `partition_schema`: The schema of the partition columns.
    ///   This must **not** be the schema of the entire file or table:
    ///   instead it must only be the schema of the partition columns,
    ///   in the same order as the values in `partition_values`.
    pub fn try_new(
        partition_values: Vec<Vec<ScalarValue>>,
        partition_fields: Vec<FieldRef>,
    ) -> Result<Self, DataFusionError> {
        let num_containers = partition_values.len();
        let partition_schema = Arc::new(Schema::new(partition_fields));
        let mut partition_values_by_column =
            vec![
                Vec::with_capacity(partition_values.len());
                partition_schema.fields().len()
            ];
        for partition_value in partition_values {
            for (i, value) in partition_value.into_iter().enumerate() {
                partition_values_by_column[i].push(value);
            }
        }
        Ok(Self {
            partition_values: partition_values_by_column
                .into_iter()
                .map(|v| {
                    if v.is_empty() {
                        Ok(Arc::new(NullArray::new(0)) as ArrayRef)
                    } else {
                        ScalarValue::iter_to_array(v)
                    }
                })
                .collect::<Result<Vec<_>, _>>()?,
            num_containers,
            partition_schema,
        })
    }
}

impl PruningStatistics for PartitionPruningStatistics {
    fn min_values(&self, column: &Column) -> Option<ArrayRef> {
        let index = self.partition_schema.index_of(column.name()).ok()?;
        self.partition_values.get(index).and_then(|v| {
            if v.is_empty() || v.null_count() == v.len() {
                // If the array is empty or all nulls, return None
                None
            } else {
                // Otherwise, return the array as is
                Some(Arc::clone(v))
            }
        })
    }

    fn max_values(&self, column: &Column) -> Option<ArrayRef> {
        self.min_values(column)
    }

    fn num_containers(&self) -> usize {
        self.num_containers
    }

    fn null_counts(&self, _column: &Column) -> Option<ArrayRef> {
        None
    }

    fn row_counts(&self, _column: &Column) -> Option<ArrayRef> {
        None
    }

    fn contained(
        &self,
        column: &Column,
        values: &HashSet<ScalarValue>,
    ) -> Option<BooleanArray> {
        let index = self.partition_schema.index_of(column.name()).ok()?;
        let array = self.partition_values.get(index)?;
        let boolean_array = values.iter().try_fold(None, |acc, v| {
            let arrow_value = v.to_scalar().ok()?;
            let eq_result = arrow::compute::kernels::cmp::eq(array, &arrow_value).ok()?;
            match acc {
                None => Some(Some(eq_result)),
                Some(acc_array) => {
                    arrow::compute::kernels::boolean::and(&acc_array, &eq_result)
                        .map(Some)
                        .ok()
                }
            }
        })??;
        // If the boolean array is empty or all null values, return None
        if boolean_array.is_empty() || boolean_array.null_count() == boolean_array.len() {
            None
        } else {
            Some(boolean_array)
        }
    }
}

/// Prune a set of containers represented by their statistics.
///
/// Each [`Statistics`] represents a "container" -- some collection of data
/// that has statistics of its columns.
///
/// It is up to the caller to decide what each container represents. For
/// example, they can come from a file (e.g. [`PartitionedFile`]) or a set of of
/// files (e.g. [`FileGroup`])
///
/// [`PartitionedFile`]: https://docs.rs/datafusion/latest/datafusion/datasource/listing/struct.PartitionedFile.html
/// [`FileGroup`]: https://docs.rs/datafusion/latest/datafusion/datasource/physical_plan/struct.FileGroup.html
#[derive(Clone)]
pub struct PrunableStatistics {
    /// Statistics for each container.
    /// These are taken as a reference since they may be rather large / expensive to clone
    /// and we often won't return all of them as ArrayRefs (we only return the columns the predicate requests).
    statistics: Vec<Arc<Statistics>>,
    /// The schema of the file these statistics are for.
    schema: SchemaRef,
}

impl PrunableStatistics {
    /// Create a new instance of [`PrunableStatistics`].
    /// Each [`Statistics`] represents a container (e.g. a file or a partition of files).
    /// The `schema` is the schema of the data in the containers and should apply to all files.
    pub fn new(statistics: Vec<Arc<Statistics>>, schema: SchemaRef) -> Self {
        Self { statistics, schema }
    }

    fn get_exact_column_statistics(
        &self,
        column: &Column,
        get_stat: impl Fn(&ColumnStatistics) -> &Precision<ScalarValue>,
    ) -> Option<ArrayRef> {
        let index = self.schema.index_of(column.name()).ok()?;
        let mut has_value = false;
        match ScalarValue::iter_to_array(self.statistics.iter().map(|s| {
            s.column_statistics
                .get(index)
                .and_then(|stat| {
                    if let Precision::Exact(min) = get_stat(stat) {
                        has_value = true;
                        Some(min.clone())
                    } else {
                        None
                    }
                })
                .unwrap_or(ScalarValue::Null)
        })) {
            // If there is any non-null value and no errors, return the array
            Ok(array) => has_value.then_some(array),
            Err(_) => {
                log::warn!(
                    "Failed to convert min values to array for column {}",
                    column.name()
                );
                None
            }
        }
    }
}

impl PruningStatistics for PrunableStatistics {
    fn min_values(&self, column: &Column) -> Option<ArrayRef> {
        self.get_exact_column_statistics(column, |stat| &stat.min_value)
    }

    fn max_values(&self, column: &Column) -> Option<ArrayRef> {
        self.get_exact_column_statistics(column, |stat| &stat.max_value)
    }

    fn num_containers(&self) -> usize {
        self.statistics.len()
    }

    fn null_counts(&self, column: &Column) -> Option<ArrayRef> {
        let index = self.schema.index_of(column.name()).ok()?;
        if self.statistics.iter().any(|s| {
            s.column_statistics
                .get(index)
                .is_some_and(|stat| stat.null_count.is_exact().unwrap_or(false))
        }) {
            Some(Arc::new(
                self.statistics
                    .iter()
                    .map(|s| {
                        s.column_statistics.get(index).and_then(|stat| {
                            if let Precision::Exact(null_count) = &stat.null_count {
                                u64::try_from(*null_count).ok()
                            } else {
                                None
                            }
                        })
                    })
                    .collect::<UInt64Array>(),
            ))
        } else {
            None
        }
    }

    fn row_counts(&self, column: &Column) -> Option<ArrayRef> {
        // If the column does not exist in the schema, return None
        if self.schema.index_of(column.name()).is_err() {
            return None;
        }
        if self
            .statistics
            .iter()
            .any(|s| s.num_rows.is_exact().unwrap_or(false))
        {
            Some(Arc::new(
                self.statistics
                    .iter()
                    .map(|s| {
                        if let Precision::Exact(row_count) = &s.num_rows {
                            u64::try_from(*row_count).ok()
                        } else {
                            None
                        }
                    })
                    .collect::<UInt64Array>(),
            ))
        } else {
            None
        }
    }

    fn contained(
        &self,
        _column: &Column,
        _values: &HashSet<ScalarValue>,
    ) -> Option<BooleanArray> {
        None
    }
}

/// Combine multiple [`PruningStatistics`] into a single
/// [`CompositePruningStatistics`].
/// This can be used to combine statistics from different sources,
/// for example partition values and file statistics.
/// This allows pruning with filters that depend on multiple sources of statistics,
/// such as `WHERE partition_col = data_col`.
/// This is done by iterating over the statistics and returning the first
/// one that has information for the requested column.
/// If multiple statistics have information for the same column,
/// the first one is returned without any regard for completeness or accuracy.
/// That is: if the first statistics has information for a column, even if it is incomplete,
/// that is returned even if a later statistics has more complete information.
pub struct CompositePruningStatistics {
    pub statistics: Vec<Box<dyn PruningStatistics>>,
}

impl CompositePruningStatistics {
    /// Create a new instance of [`CompositePruningStatistics`] from
    /// a vector of [`PruningStatistics`].
    pub fn new(statistics: Vec<Box<dyn PruningStatistics>>) -> Self {
        assert!(!statistics.is_empty());
        // Check that all statistics have the same number of containers
        let num_containers = statistics[0].num_containers();
        for stats in &statistics {
            assert_eq!(num_containers, stats.num_containers());
        }
        Self { statistics }
    }
}

impl PruningStatistics for CompositePruningStatistics {
    fn min_values(&self, column: &Column) -> Option<ArrayRef> {
        for stats in &self.statistics {
            if let Some(array) = stats.min_values(column) {
                return Some(array);
            }
        }
        None
    }

    fn max_values(&self, column: &Column) -> Option<ArrayRef> {
        for stats in &self.statistics {
            if let Some(array) = stats.max_values(column) {
                return Some(array);
            }
        }
        None
    }

    fn num_containers(&self) -> usize {
        self.statistics[0].num_containers()
    }

    fn null_counts(&self, column: &Column) -> Option<ArrayRef> {
        for stats in &self.statistics {
            if let Some(array) = stats.null_counts(column) {
                return Some(array);
            }
        }
        None
    }

    fn row_counts(&self, column: &Column) -> Option<ArrayRef> {
        for stats in &self.statistics {
            if let Some(array) = stats.row_counts(column) {
                return Some(array);
            }
        }
        None
    }

    fn contained(
        &self,
        column: &Column,
        values: &HashSet<ScalarValue>,
    ) -> Option<BooleanArray> {
        for stats in &self.statistics {
            if let Some(array) = stats.contained(column, values) {
                return Some(array);
            }
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        cast::{as_int32_array, as_uint64_array},
        ColumnStatistics,
    };

    use super::*;
    use arrow::datatypes::{DataType, Field};
    use std::sync::Arc;

    #[test]
    fn test_partition_pruning_statistics() {
        let partition_values = vec![
            vec![ScalarValue::from(1i32), ScalarValue::from(2i32)],
            vec![ScalarValue::from(3i32), ScalarValue::from(4i32)],
        ];
        let partition_fields = vec![
            Arc::new(Field::new("a", DataType::Int32, false)),
            Arc::new(Field::new("b", DataType::Int32, false)),
        ];
        let partition_stats =
            PartitionPruningStatistics::try_new(partition_values, partition_fields)
                .unwrap();

        let column_a = Column::new_unqualified("a");
        let column_b = Column::new_unqualified("b");

        // Partition values don't know anything about nulls or row counts
        assert!(partition_stats.null_counts(&column_a).is_none());
        assert!(partition_stats.row_counts(&column_a).is_none());
        assert!(partition_stats.null_counts(&column_b).is_none());
        assert!(partition_stats.row_counts(&column_b).is_none());

        // Min/max values are the same as the partition values
        let min_values_a =
            as_int32_array(&partition_stats.min_values(&column_a).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_values_a = vec![Some(1), Some(3)];
        assert_eq!(min_values_a, expected_values_a);
        let max_values_a =
            as_int32_array(&partition_stats.max_values(&column_a).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_values_a = vec![Some(1), Some(3)];
        assert_eq!(max_values_a, expected_values_a);

        let min_values_b =
            as_int32_array(&partition_stats.min_values(&column_b).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_values_b = vec![Some(2), Some(4)];
        assert_eq!(min_values_b, expected_values_b);
        let max_values_b =
            as_int32_array(&partition_stats.max_values(&column_b).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_values_b = vec![Some(2), Some(4)];
        assert_eq!(max_values_b, expected_values_b);

        // Contained values are only true for the partition values
        let values = HashSet::from([ScalarValue::from(1i32)]);
        let contained_a = partition_stats.contained(&column_a, &values).unwrap();
        let expected_contained_a = BooleanArray::from(vec![true, false]);
        assert_eq!(contained_a, expected_contained_a);
        let contained_b = partition_stats.contained(&column_b, &values).unwrap();
        let expected_contained_b = BooleanArray::from(vec![false, false]);
        assert_eq!(contained_b, expected_contained_b);

        // The number of containers is the length of the partition values
        assert_eq!(partition_stats.num_containers(), 2);
    }

    #[test]
    fn test_partition_pruning_statistics_empty() {
        let partition_values = vec![];
        let partition_fields = vec![
            Arc::new(Field::new("a", DataType::Int32, false)),
            Arc::new(Field::new("b", DataType::Int32, false)),
        ];
        let partition_stats =
            PartitionPruningStatistics::try_new(partition_values, partition_fields)
                .unwrap();

        let column_a = Column::new_unqualified("a");
        let column_b = Column::new_unqualified("b");

        // Partition values don't know anything about nulls or row counts
        assert!(partition_stats.null_counts(&column_a).is_none());
        assert!(partition_stats.row_counts(&column_a).is_none());
        assert!(partition_stats.null_counts(&column_b).is_none());
        assert!(partition_stats.row_counts(&column_b).is_none());

        // Min/max values are all missing
        assert!(partition_stats.min_values(&column_a).is_none());
        assert!(partition_stats.max_values(&column_a).is_none());
        assert!(partition_stats.min_values(&column_b).is_none());
        assert!(partition_stats.max_values(&column_b).is_none());

        // Contained values are all empty
        let values = HashSet::from([ScalarValue::from(1i32)]);
        assert!(partition_stats.contained(&column_a, &values).is_none());
    }

    #[test]
    fn test_statistics_pruning_statistics() {
        let statistics = vec![
            Arc::new(
                Statistics::default()
                    .add_column_statistics(
                        ColumnStatistics::new_unknown()
                            .with_min_value(Precision::Exact(ScalarValue::from(0i32)))
                            .with_max_value(Precision::Exact(ScalarValue::from(100i32)))
                            .with_null_count(Precision::Exact(0)),
                    )
                    .add_column_statistics(
                        ColumnStatistics::new_unknown()
                            .with_min_value(Precision::Exact(ScalarValue::from(100i32)))
                            .with_max_value(Precision::Exact(ScalarValue::from(200i32)))
                            .with_null_count(Precision::Exact(5)),
                    )
                    .with_num_rows(Precision::Exact(100)),
            ),
            Arc::new(
                Statistics::default()
                    .add_column_statistics(
                        ColumnStatistics::new_unknown()
                            .with_min_value(Precision::Exact(ScalarValue::from(50i32)))
                            .with_max_value(Precision::Exact(ScalarValue::from(300i32)))
                            .with_null_count(Precision::Exact(10)),
                    )
                    .add_column_statistics(
                        ColumnStatistics::new_unknown()
                            .with_min_value(Precision::Exact(ScalarValue::from(200i32)))
                            .with_max_value(Precision::Exact(ScalarValue::from(400i32)))
                            .with_null_count(Precision::Exact(0)),
                    )
                    .with_num_rows(Precision::Exact(200)),
            ),
        ];

        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
            Field::new("c", DataType::Int32, false),
        ]));
        let pruning_stats = PrunableStatistics::new(statistics, schema);

        let column_a = Column::new_unqualified("a");
        let column_b = Column::new_unqualified("b");

        // Min/max values are the same as the statistics
        let min_values_a = as_int32_array(&pruning_stats.min_values(&column_a).unwrap())
            .unwrap()
            .into_iter()
            .collect::<Vec<_>>();
        let expected_values_a = vec![Some(0), Some(50)];
        assert_eq!(min_values_a, expected_values_a);
        let max_values_a = as_int32_array(&pruning_stats.max_values(&column_a).unwrap())
            .unwrap()
            .into_iter()
            .collect::<Vec<_>>();
        let expected_values_a = vec![Some(100), Some(300)];
        assert_eq!(max_values_a, expected_values_a);
        let min_values_b = as_int32_array(&pruning_stats.min_values(&column_b).unwrap())
            .unwrap()
            .into_iter()
            .collect::<Vec<_>>();
        let expected_values_b = vec![Some(100), Some(200)];
        assert_eq!(min_values_b, expected_values_b);
        let max_values_b = as_int32_array(&pruning_stats.max_values(&column_b).unwrap())
            .unwrap()
            .into_iter()
            .collect::<Vec<_>>();
        let expected_values_b = vec![Some(200), Some(400)];
        assert_eq!(max_values_b, expected_values_b);

        // Null counts are the same as the statistics
        let null_counts_a =
            as_uint64_array(&pruning_stats.null_counts(&column_a).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_null_counts_a = vec![Some(0), Some(10)];
        assert_eq!(null_counts_a, expected_null_counts_a);
        let null_counts_b =
            as_uint64_array(&pruning_stats.null_counts(&column_b).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_null_counts_b = vec![Some(5), Some(0)];
        assert_eq!(null_counts_b, expected_null_counts_b);

        // Row counts are the same as the statistics
        let row_counts_a = as_uint64_array(&pruning_stats.row_counts(&column_a).unwrap())
            .unwrap()
            .into_iter()
            .collect::<Vec<_>>();
        let expected_row_counts_a = vec![Some(100), Some(200)];
        assert_eq!(row_counts_a, expected_row_counts_a);
        let row_counts_b = as_uint64_array(&pruning_stats.row_counts(&column_b).unwrap())
            .unwrap()
            .into_iter()
            .collect::<Vec<_>>();
        let expected_row_counts_b = vec![Some(100), Some(200)];
        assert_eq!(row_counts_b, expected_row_counts_b);

        // Contained values are all null/missing (we can't know this just from statistics)
        let values = HashSet::from([ScalarValue::from(0i32)]);
        assert!(pruning_stats.contained(&column_a, &values).is_none());
        assert!(pruning_stats.contained(&column_b, &values).is_none());

        // The number of containers is the length of the statistics
        assert_eq!(pruning_stats.num_containers(), 2);

        // Test with a column that has no statistics
        let column_c = Column::new_unqualified("c");
        assert!(pruning_stats.min_values(&column_c).is_none());
        assert!(pruning_stats.max_values(&column_c).is_none());
        assert!(pruning_stats.null_counts(&column_c).is_none());
        // Since row counts uses the first column that has row counts we get them back even
        // if this columns does not have them set.
        // This is debatable, personally I think `row_count` should not take a `Column` as an argument
        // at all since all columns should have the same number of rows.
        // But for now we just document the current behavior in this test.
        let row_counts_c = as_uint64_array(&pruning_stats.row_counts(&column_c).unwrap())
            .unwrap()
            .into_iter()
            .collect::<Vec<_>>();
        let expected_row_counts_c = vec![Some(100), Some(200)];
        assert_eq!(row_counts_c, expected_row_counts_c);
        assert!(pruning_stats.contained(&column_c, &values).is_none());

        // Test with a column that doesn't exist
        let column_d = Column::new_unqualified("d");
        assert!(pruning_stats.min_values(&column_d).is_none());
        assert!(pruning_stats.max_values(&column_d).is_none());
        assert!(pruning_stats.null_counts(&column_d).is_none());
        assert!(pruning_stats.row_counts(&column_d).is_none());
        assert!(pruning_stats.contained(&column_d, &values).is_none());
    }

    #[test]
    fn test_statistics_pruning_statistics_empty() {
        let statistics = vec![];
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
            Field::new("c", DataType::Int32, false),
        ]));
        let pruning_stats = PrunableStatistics::new(statistics, schema);

        let column_a = Column::new_unqualified("a");
        let column_b = Column::new_unqualified("b");

        // Min/max values are all missing
        assert!(pruning_stats.min_values(&column_a).is_none());
        assert!(pruning_stats.max_values(&column_a).is_none());
        assert!(pruning_stats.min_values(&column_b).is_none());
        assert!(pruning_stats.max_values(&column_b).is_none());

        // Null counts are all missing
        assert!(pruning_stats.null_counts(&column_a).is_none());
        assert!(pruning_stats.null_counts(&column_b).is_none());

        // Row counts are all missing
        assert!(pruning_stats.row_counts(&column_a).is_none());
        assert!(pruning_stats.row_counts(&column_b).is_none());

        // Contained values are all empty
        let values = HashSet::from([ScalarValue::from(1i32)]);
        assert!(pruning_stats.contained(&column_a, &values).is_none());
    }

    #[test]
    fn test_composite_pruning_statistics_partition_and_file() {
        // Create partition statistics
        let partition_values = vec![
            vec![ScalarValue::from(1i32), ScalarValue::from(10i32)],
            vec![ScalarValue::from(2i32), ScalarValue::from(20i32)],
        ];
        let partition_fields = vec![
            Arc::new(Field::new("part_a", DataType::Int32, false)),
            Arc::new(Field::new("part_b", DataType::Int32, false)),
        ];
        let partition_stats =
            PartitionPruningStatistics::try_new(partition_values, partition_fields)
                .unwrap();

        // Create file statistics
        let file_statistics = vec![
            Arc::new(
                Statistics::default()
                    .add_column_statistics(
                        ColumnStatistics::new_unknown()
                            .with_min_value(Precision::Exact(ScalarValue::from(100i32)))
                            .with_max_value(Precision::Exact(ScalarValue::from(200i32)))
                            .with_null_count(Precision::Exact(0)),
                    )
                    .add_column_statistics(
                        ColumnStatistics::new_unknown()
                            .with_min_value(Precision::Exact(ScalarValue::from(300i32)))
                            .with_max_value(Precision::Exact(ScalarValue::from(400i32)))
                            .with_null_count(Precision::Exact(5)),
                    )
                    .with_num_rows(Precision::Exact(100)),
            ),
            Arc::new(
                Statistics::default()
                    .add_column_statistics(
                        ColumnStatistics::new_unknown()
                            .with_min_value(Precision::Exact(ScalarValue::from(500i32)))
                            .with_max_value(Precision::Exact(ScalarValue::from(600i32)))
                            .with_null_count(Precision::Exact(10)),
                    )
                    .add_column_statistics(
                        ColumnStatistics::new_unknown()
                            .with_min_value(Precision::Exact(ScalarValue::from(700i32)))
                            .with_max_value(Precision::Exact(ScalarValue::from(800i32)))
                            .with_null_count(Precision::Exact(0)),
                    )
                    .with_num_rows(Precision::Exact(200)),
            ),
        ];

        let file_schema = Arc::new(Schema::new(vec![
            Field::new("col_x", DataType::Int32, false),
            Field::new("col_y", DataType::Int32, false),
        ]));
        let file_stats = PrunableStatistics::new(file_statistics, file_schema);

        // Create composite statistics
        let composite_stats = CompositePruningStatistics::new(vec![
            Box::new(partition_stats),
            Box::new(file_stats),
        ]);

        // Test accessing columns that are only in partition statistics
        let part_a = Column::new_unqualified("part_a");
        let part_b = Column::new_unqualified("part_b");

        // Test accessing columns that are only in file statistics
        let col_x = Column::new_unqualified("col_x");
        let col_y = Column::new_unqualified("col_y");

        // For partition columns, should get values from partition statistics
        let min_values_part_a =
            as_int32_array(&composite_stats.min_values(&part_a).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_values_part_a = vec![Some(1), Some(2)];
        assert_eq!(min_values_part_a, expected_values_part_a);

        let max_values_part_a =
            as_int32_array(&composite_stats.max_values(&part_a).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        // For partition values, min and max are the same
        assert_eq!(max_values_part_a, expected_values_part_a);

        let min_values_part_b =
            as_int32_array(&composite_stats.min_values(&part_b).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_values_part_b = vec![Some(10), Some(20)];
        assert_eq!(min_values_part_b, expected_values_part_b);

        // For file columns, should get values from file statistics
        let min_values_col_x =
            as_int32_array(&composite_stats.min_values(&col_x).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_values_col_x = vec![Some(100), Some(500)];
        assert_eq!(min_values_col_x, expected_values_col_x);

        let max_values_col_x =
            as_int32_array(&composite_stats.max_values(&col_x).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_max_values_col_x = vec![Some(200), Some(600)];
        assert_eq!(max_values_col_x, expected_max_values_col_x);

        let min_values_col_y =
            as_int32_array(&composite_stats.min_values(&col_y).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_values_col_y = vec![Some(300), Some(700)];
        assert_eq!(min_values_col_y, expected_values_col_y);

        // Test null counts - only available from file statistics
        assert!(composite_stats.null_counts(&part_a).is_none());
        assert!(composite_stats.null_counts(&part_b).is_none());

        let null_counts_col_x =
            as_uint64_array(&composite_stats.null_counts(&col_x).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_null_counts_col_x = vec![Some(0), Some(10)];
        assert_eq!(null_counts_col_x, expected_null_counts_col_x);

        // Test row counts - only available from file statistics
        assert!(composite_stats.row_counts(&part_a).is_none());
        let row_counts_col_x =
            as_uint64_array(&composite_stats.row_counts(&col_x).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_row_counts = vec![Some(100), Some(200)];
        assert_eq!(row_counts_col_x, expected_row_counts);

        // Test contained values - only available from partition statistics
        let values = HashSet::from([ScalarValue::from(1i32)]);
        let contained_part_a = composite_stats.contained(&part_a, &values).unwrap();
        let expected_contained_part_a = BooleanArray::from(vec![true, false]);
        assert_eq!(contained_part_a, expected_contained_part_a);

        // File statistics don't implement contained
        assert!(composite_stats.contained(&col_x, &values).is_none());

        // Non-existent column should return None for everything
        let non_existent = Column::new_unqualified("non_existent");
        assert!(composite_stats.min_values(&non_existent).is_none());
        assert!(composite_stats.max_values(&non_existent).is_none());
        assert!(composite_stats.null_counts(&non_existent).is_none());
        assert!(composite_stats.row_counts(&non_existent).is_none());
        assert!(composite_stats.contained(&non_existent, &values).is_none());

        // Verify num_containers matches
        assert_eq!(composite_stats.num_containers(), 2);
    }

    #[test]
    fn test_composite_pruning_statistics_priority() {
        // Create two sets of file statistics with the same column names
        // but different values to test that the first one gets priority

        // First set of statistics
        let first_statistics = vec![
            Arc::new(
                Statistics::default()
                    .add_column_statistics(
                        ColumnStatistics::new_unknown()
                            .with_min_value(Precision::Exact(ScalarValue::from(100i32)))
                            .with_max_value(Precision::Exact(ScalarValue::from(200i32)))
                            .with_null_count(Precision::Exact(0)),
                    )
                    .with_num_rows(Precision::Exact(100)),
            ),
            Arc::new(
                Statistics::default()
                    .add_column_statistics(
                        ColumnStatistics::new_unknown()
                            .with_min_value(Precision::Exact(ScalarValue::from(300i32)))
                            .with_max_value(Precision::Exact(ScalarValue::from(400i32)))
                            .with_null_count(Precision::Exact(5)),
                    )
                    .with_num_rows(Precision::Exact(200)),
            ),
        ];

        let first_schema = Arc::new(Schema::new(vec![Field::new(
            "col_a",
            DataType::Int32,
            false,
        )]));
        let first_stats = PrunableStatistics::new(first_statistics, first_schema);

        // Second set of statistics with the same column name but different values
        let second_statistics = vec![
            Arc::new(
                Statistics::default()
                    .add_column_statistics(
                        ColumnStatistics::new_unknown()
                            .with_min_value(Precision::Exact(ScalarValue::from(1000i32)))
                            .with_max_value(Precision::Exact(ScalarValue::from(2000i32)))
                            .with_null_count(Precision::Exact(10)),
                    )
                    .with_num_rows(Precision::Exact(1000)),
            ),
            Arc::new(
                Statistics::default()
                    .add_column_statistics(
                        ColumnStatistics::new_unknown()
                            .with_min_value(Precision::Exact(ScalarValue::from(3000i32)))
                            .with_max_value(Precision::Exact(ScalarValue::from(4000i32)))
                            .with_null_count(Precision::Exact(20)),
                    )
                    .with_num_rows(Precision::Exact(2000)),
            ),
        ];

        let second_schema = Arc::new(Schema::new(vec![Field::new(
            "col_a",
            DataType::Int32,
            false,
        )]));
        let second_stats = PrunableStatistics::new(second_statistics, second_schema);

        // Create composite statistics with first stats having priority
        let composite_stats = CompositePruningStatistics::new(vec![
            Box::new(first_stats.clone()),
            Box::new(second_stats.clone()),
        ]);

        let col_a = Column::new_unqualified("col_a");

        // Should get values from first statistics since it has priority
        let min_values = as_int32_array(&composite_stats.min_values(&col_a).unwrap())
            .unwrap()
            .into_iter()
            .collect::<Vec<_>>();
        let expected_min_values = vec![Some(100), Some(300)];
        assert_eq!(min_values, expected_min_values);

        let max_values = as_int32_array(&composite_stats.max_values(&col_a).unwrap())
            .unwrap()
            .into_iter()
            .collect::<Vec<_>>();
        let expected_max_values = vec![Some(200), Some(400)];
        assert_eq!(max_values, expected_max_values);

        let null_counts = as_uint64_array(&composite_stats.null_counts(&col_a).unwrap())
            .unwrap()
            .into_iter()
            .collect::<Vec<_>>();
        let expected_null_counts = vec![Some(0), Some(5)];
        assert_eq!(null_counts, expected_null_counts);

        let row_counts = as_uint64_array(&composite_stats.row_counts(&col_a).unwrap())
            .unwrap()
            .into_iter()
            .collect::<Vec<_>>();
        let expected_row_counts = vec![Some(100), Some(200)];
        assert_eq!(row_counts, expected_row_counts);

        // Create composite statistics with second stats having priority
        // Now that we've added Clone trait to PrunableStatistics, we can just clone them

        let composite_stats_reversed = CompositePruningStatistics::new(vec![
            Box::new(second_stats.clone()),
            Box::new(first_stats.clone()),
        ]);

        // Should get values from second statistics since it now has priority
        let min_values =
            as_int32_array(&composite_stats_reversed.min_values(&col_a).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_min_values = vec![Some(1000), Some(3000)];
        assert_eq!(min_values, expected_min_values);

        let max_values =
            as_int32_array(&composite_stats_reversed.max_values(&col_a).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_max_values = vec![Some(2000), Some(4000)];
        assert_eq!(max_values, expected_max_values);

        let null_counts =
            as_uint64_array(&composite_stats_reversed.null_counts(&col_a).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_null_counts = vec![Some(10), Some(20)];
        assert_eq!(null_counts, expected_null_counts);

        let row_counts =
            as_uint64_array(&composite_stats_reversed.row_counts(&col_a).unwrap())
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>();
        let expected_row_counts = vec![Some(1000), Some(2000)];
        assert_eq!(row_counts, expected_row_counts);
    }

    #[test]
    fn test_composite_pruning_statistics_empty_and_mismatched_containers() {
        // Test with empty statistics vector
        // This should never happen, so we panic instead of returning a Result which would burned callers
        let result = std::panic::catch_unwind(|| {
            CompositePruningStatistics::new(vec![]);
        });
        assert!(result.is_err());

        // We should panic here because the number of containers is different
        let result = std::panic::catch_unwind(|| {
            // Create statistics with different number of containers
            // Use partition stats for the test
            let partition_values_1 = vec![
                vec![ScalarValue::from(1i32), ScalarValue::from(10i32)],
                vec![ScalarValue::from(2i32), ScalarValue::from(20i32)],
            ];
            let partition_fields_1 = vec![
                Arc::new(Field::new("part_a", DataType::Int32, false)),
                Arc::new(Field::new("part_b", DataType::Int32, false)),
            ];
            let partition_stats_1 = PartitionPruningStatistics::try_new(
                partition_values_1,
                partition_fields_1,
            )
            .unwrap();
            let partition_values_2 = vec![
                vec![ScalarValue::from(3i32), ScalarValue::from(30i32)],
                vec![ScalarValue::from(4i32), ScalarValue::from(40i32)],
                vec![ScalarValue::from(5i32), ScalarValue::from(50i32)],
            ];
            let partition_fields_2 = vec![
                Arc::new(Field::new("part_x", DataType::Int32, false)),
                Arc::new(Field::new("part_y", DataType::Int32, false)),
            ];
            let partition_stats_2 = PartitionPruningStatistics::try_new(
                partition_values_2,
                partition_fields_2,
            )
            .unwrap();

            CompositePruningStatistics::new(vec![
                Box::new(partition_stats_1),
                Box::new(partition_stats_2),
            ]);
        });
        assert!(result.is_err());
    }
}