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
use crate::ArrowResult;
use arrow::io::parquet::read::statistics::{
    deserialize_statistics, PrimitiveStatistics, Statistics, Utf8Statistics,
};
use arrow::io::parquet::read::ColumnChunkMetaData;
use polars_core::prelude::*;

/// The statistics for a column in a Parquet file
/// they typically hold
/// - max value
/// - min value
/// - null_count
#[cfg_attr(debug_assertions, derive(Debug))]
pub struct ColumnStats(Box<dyn Statistics>);

impl ColumnStats {
    pub fn dtype(&self) -> DataType {
        self.0.data_type().into()
    }

    pub fn null_count(&self) -> Option<usize> {
        self.0.null_count().map(|v| v as usize)
    }

    pub fn to_min_max(&self) -> Option<Series> {
        let name = "";
        use DataType::*;
        let s = match self.dtype() {
            Float64 => {
                let stats = self
                    .0
                    .as_any()
                    .downcast_ref::<PrimitiveStatistics<f64>>()
                    .unwrap();
                Series::new(name, [stats.min_value, stats.max_value])
            }
            Float32 => {
                let stats = self
                    .0
                    .as_any()
                    .downcast_ref::<PrimitiveStatistics<f32>>()
                    .unwrap();
                Series::new(name, [stats.min_value, stats.max_value])
            }
            Int64 => {
                let stats = self
                    .0
                    .as_any()
                    .downcast_ref::<PrimitiveStatistics<i64>>()
                    .unwrap();
                Series::new(name, [stats.min_value, stats.max_value])
            }
            Int32 => {
                let stats = self
                    .0
                    .as_any()
                    .downcast_ref::<PrimitiveStatistics<i32>>()
                    .unwrap();
                Series::new(name, [stats.min_value, stats.max_value])
            }
            UInt32 => {
                let stats = self
                    .0
                    .as_any()
                    .downcast_ref::<PrimitiveStatistics<u32>>()
                    .unwrap();
                Series::new(name, [stats.min_value, stats.max_value])
            }
            UInt64 => {
                let stats = self
                    .0
                    .as_any()
                    .downcast_ref::<PrimitiveStatistics<u64>>()
                    .unwrap();
                Series::new(name, [stats.min_value, stats.max_value])
            }
            Utf8 => {
                let stats = self.0.as_any().downcast_ref::<Utf8Statistics>().unwrap();
                Series::new(
                    name,
                    [stats.min_value.as_deref(), stats.max_value.as_deref()],
                )
            }
            _ => return None,
        };
        Some(s)
    }
}

/// A collection of column stats with a known schema.
pub struct BatchStats {
    schema: Schema,
    stats: Vec<ColumnStats>,
}

impl BatchStats {
    pub fn get_stats(&self, column: &str) -> polars_core::error::Result<&ColumnStats> {
        self.schema.try_index_of(column).map(|i| &self.stats[i])
    }

    pub fn schema(&self) -> &Schema {
        &self.schema
    }
}

/// Collect the statistics in a column chunk.
pub(crate) fn collect_statistics(
    md: &[ColumnChunkMetaData],
    arrow_schema: &ArrowSchema,
) -> ArrowResult<Option<BatchStats>> {
    let mut schema = Schema::with_capacity(arrow_schema.fields.len());
    let mut stats = vec![];

    for fld in &arrow_schema.fields {
        for st in deserialize_statistics(fld, md)?.into_iter().flatten() {
            schema.with_column(fld.name.to_string(), (&fld.data_type).into());
            stats.push(ColumnStats(st));
        }
    }

    Ok(if stats.is_empty() {
        None
    } else {
        Some(BatchStats { schema, stats })
    })
}