Skip to main content

parquet_cli/
meta.rs

1//! What is in the file: its facts, its schema, and its columns' statistics.
2
3use std::collections::{BTreeMap, BTreeSet, HashSet};
4use std::fs::File;
5use std::path::Path;
6use std::sync::Arc;
7
8use anyhow::{Context, Result};
9use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
10use parquet::data_type::AsBytes;
11use parquet::file::metadata::ParquetMetaData;
12use parquet::file::statistics::Statistics;
13use serde_json::{json, Map, Value};
14
15use crate::value::{data_type_name, field_json};
16
17/// Open a Parquet file and read its footer.
18pub fn open(path: &Path) -> Result<Arc<ParquetMetaData>> {
19    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
20    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
21        .with_context(|| format!("read the footer of {}", path.display()))?;
22    Ok(builder.metadata().clone())
23}
24
25/// What the footer says about the file as a whole.
26#[derive(Clone, Debug)]
27pub struct FileFacts {
28    /// The path, as it was given.
29    pub path: String,
30    /// How many bytes the file is.
31    pub size_bytes: u64,
32    /// How many rows it holds.
33    pub rows: i64,
34    /// How many row groups it has.
35    pub row_groups: usize,
36    /// How many leaf columns it has.
37    pub columns: usize,
38    /// How many rows each row group holds.
39    pub row_group_rows: Vec<i64>,
40    /// The bytes the column chunks take.
41    pub column_bytes: i64,
42    /// The bytes the footer takes (the file minus the column chunks).
43    pub footer_bytes: i64,
44    /// Who wrote the file.
45    pub created_by: Option<String>,
46    /// The Parquet format version.
47    pub format_version: i32,
48    /// The compressions the columns use.
49    pub compressions: Vec<String>,
50    /// The encodings the pages use.
51    pub encodings: Vec<String>,
52    /// The key-value metadata the writer left behind.
53    pub key_value_metadata: Vec<Value>,
54}
55
56/// What the footer says about one column.
57#[derive(Clone, Debug)]
58pub struct ColumnFacts {
59    /// The name of the leaf column (its path, when it is nested).
60    pub name: String,
61    /// The type a person reads: the logical type when the file has one, the
62    /// Arrow type when it does not but the Arrow schema is there, the physical
63    /// type when there is nothing better.
64    pub data_type: String,
65    /// The physical type (`INT64`, `BYTE_ARRAY`, …).
66    pub physical_type: String,
67    /// The logical type, when the file carries one.
68    pub logical_type: String,
69    /// The compression the column was written with.
70    pub compression: String,
71    /// The encodings its pages use.
72    pub encodings: Vec<String>,
73    /// How many values there are (nulls included).
74    pub num_values: i64,
75    /// How many of them are null.
76    pub null_count: u64,
77    /// The smallest value, when the footer has it.
78    pub min: Option<Value>,
79    /// The largest value, when the footer has it.
80    pub max: Option<Value>,
81    /// How many bytes the column takes in the file.
82    pub compressed_size: i64,
83    /// How many bytes the values take before compression.
84    pub uncompressed_size: i64,
85    /// The distinct values, when the file was read to count them.
86    pub distinct_count: Option<u64>,
87}
88
89/// File-level facts: size, rows, row groups, who wrote it.
90pub fn facts(path: &Path) -> Result<Value> {
91    let file = file_facts(path)?;
92    Ok(json!({
93        "file": file.path,
94        "size_bytes": file.size_bytes,
95        "rows": file.rows,
96        "row_groups": file.row_groups,
97        "columns": file.columns,
98        "format_version": file.format_version,
99        "created_by": file.created_by,
100        "bytes_per_row": if file.rows > 0 {
101            file.size_bytes as f64 / file.rows as f64
102        } else {
103            0.0
104        },
105        "column_bytes": file.column_bytes,
106        "footer_bytes": file.footer_bytes,
107        "compressions": file.compressions,
108        "encodings": file.encodings,
109        "key_value_metadata": file.key_value_metadata,
110        "row_group_rows": file.row_group_rows,
111    }))
112}
113
114/// The footer, read as facts.
115pub fn file_facts(path: &Path) -> Result<FileFacts> {
116    let metadata = open(path)?;
117    let file = metadata.file_metadata();
118    let size_bytes = std::fs::metadata(path)?.len();
119    let rows = file.num_rows();
120
121    let mut compressions = BTreeSet::new();
122    let mut encodings = BTreeSet::new();
123    let mut column_bytes = 0i64;
124    for group in metadata.row_groups() {
125        for chunk in group.columns() {
126            compressions.insert(format!("{}", chunk.compression_codec()));
127            encodings.extend(chunk.encodings().map(|encoding| format!("{encoding}")));
128            column_bytes += chunk.compressed_size();
129        }
130    }
131
132    let key_value_metadata: Vec<Value> = file
133        .key_value_metadata()
134        .map(|entries| {
135            entries
136                .iter()
137                .map(|entry| {
138                    json!({
139                        "key": entry.key,
140                        "value": entry.value,
141                    })
142                })
143                .collect()
144        })
145        .unwrap_or_default();
146
147    Ok(FileFacts {
148        path: path.display().to_string(),
149        size_bytes,
150        rows,
151        row_groups: metadata.row_groups().len(),
152        columns: metadata.file_metadata().schema_descr().num_columns(),
153        row_group_rows: metadata
154            .row_groups()
155            .iter()
156            .map(|group| group.num_rows())
157            .collect(),
158        column_bytes,
159        footer_bytes: size_bytes as i64 - column_bytes,
160        created_by: file.created_by().map(|text| text.to_string()),
161        format_version: file.version(),
162        compressions: compressions.into_iter().collect(),
163        encodings: encodings.into_iter().collect(),
164        key_value_metadata,
165    })
166}
167
168/// The schema, as Arrow sees it.
169pub fn schema(path: &Path) -> Result<Value> {
170    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
171    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
172        .with_context(|| format!("read the footer of {}", path.display()))?;
173    let arrow_schema = builder.schema().clone();
174    let fields: Vec<Value> = arrow_schema
175        .fields()
176        .iter()
177        .map(|field| field_json(field.as_ref()))
178        .collect();
179    Ok(json!({
180        "file": path.display().to_string(),
181        "fields": fields,
182    }))
183}
184
185/// The schema as flat lines: `name  type  nullable`.
186pub fn schema_lines(path: &Path) -> Result<Vec<(String, String, bool)>> {
187    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
188    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
189        .with_context(|| format!("read the footer of {}", path.display()))?;
190    let arrow_schema = builder.schema().clone();
191    let mut lines = Vec::new();
192    for field in arrow_schema.fields().iter() {
193        lines.push((
194            field.name().clone(),
195            data_type_name(field.data_type()),
196            field.is_nullable(),
197        ));
198    }
199    Ok(lines)
200}
201
202/// Per-column statistics, taken from the footer.
203///
204/// With `scan`, the file is also read so the distinct counts are exact.
205pub fn column_facts(path: &Path, scan: bool) -> Result<Vec<ColumnFacts>> {
206    let metadata = open(path)?;
207    let arrow_types = arrow_leaf_types(path)?;
208
209    let distinct_counts: Option<Vec<HashSet<String>>> = if scan {
210        Some(scan_distinct(path)?)
211    } else {
212        None
213    };
214
215    // The columns of the footer are leaves: a struct column shows up as one
216    // leaf per field, named by its path.
217    let leaf_names: Vec<String> = metadata
218        .file_metadata()
219        .schema_descr()
220        .columns()
221        .iter()
222        .map(|column| column.path().string())
223        .collect();
224
225    let mut per_column: BTreeMap<usize, ColumnStats> = BTreeMap::new();
226    for group in metadata.row_groups() {
227        for (position, chunk) in group.columns().iter().enumerate() {
228            let stats = per_column.entry(position).or_insert_with(|| ColumnStats {
229                path: chunk.column_path().string(),
230                physical_type: format!("{}", chunk.column_type()),
231                logical_type: chunk
232                    .column_descr()
233                    .logical_type_ref()
234                    .map(|logical| format!("{logical:?}"))
235                    .unwrap_or_else(|| "-".into()),
236                compression: format!("{}", chunk.compression_codec()),
237                encodings: BTreeSet::new(),
238                num_values: 0,
239                null_count: 0,
240                min: None,
241                max: None,
242                compressed_size: 0,
243                uncompressed_size: 0,
244            });
245            stats
246                .encodings
247                .extend(chunk.encodings().map(|encoding| format!("{encoding}")));
248            stats.num_values += chunk.num_values();
249            stats.compressed_size += chunk.compressed_size();
250            stats.uncompressed_size += chunk.uncompressed_size();
251            if let Some(statistics) = chunk.statistics() {
252                stats.null_count += statistics.null_count_opt().unwrap_or(0);
253                let (min, max) = bounds(statistics);
254                stats.min = merge_min(stats.min.take(), min);
255                stats.max = merge_max(stats.max.take(), max);
256            }
257        }
258    }
259
260    let mut facts = Vec::new();
261    for (position, stats) in per_column.iter() {
262        let name = leaf_names
263            .get(*position)
264            .cloned()
265            .unwrap_or_else(|| stats.path.clone());
266        // The Arrow type reads best (`utf8`, `decimal128(21,1)`); the logical
267        // type is the writer's own wording, and the physical type is the
268        // fallback when there is no Arrow schema to go by.
269        let data_type = arrow_types
270            .get(&stats.path)
271            .cloned()
272            .or_else(|| {
273                if stats.logical_type != "-" {
274                    Some(stats.logical_type.clone())
275                } else {
276                    None
277                }
278            })
279            .unwrap_or_else(|| stats.physical_type.clone());
280        facts.push(ColumnFacts {
281            name,
282            data_type,
283            physical_type: stats.physical_type.clone(),
284            logical_type: stats.logical_type.clone(),
285            compression: stats.compression.clone(),
286            encodings: stats.encodings.iter().cloned().collect(),
287            num_values: stats.num_values,
288            null_count: stats.null_count,
289            min: stats.min.clone(),
290            max: stats.max.clone(),
291            compressed_size: stats.compressed_size,
292            uncompressed_size: stats.uncompressed_size,
293            distinct_count: distinct_counts
294                .as_ref()
295                .and_then(|sets| sets.get(*position))
296                .map(|set| set.len() as u64),
297        });
298    }
299    Ok(facts)
300}
301
302/// Per-column statistics as JSON.
303pub fn columns(path: &Path, scan: bool) -> Result<Value> {
304    let file = file_facts(path)?;
305    let facts = column_facts(path, scan)?;
306
307    let mut out = Vec::new();
308    for column in facts {
309        let mut object = Map::new();
310        object.insert("name".into(), Value::String(column.name.clone()));
311        object.insert("type".into(), Value::String(column.data_type.clone()));
312        object.insert(
313            "physical_type".into(),
314            Value::String(column.physical_type.clone()),
315        );
316        object.insert(
317            "logical_type".into(),
318            Value::String(column.logical_type.clone()),
319        );
320        object.insert(
321            "compression".into(),
322            Value::String(column.compression.clone()),
323        );
324        object.insert(
325            "encodings".into(),
326            Value::Array(
327                column
328                    .encodings
329                    .iter()
330                    .map(|encoding| Value::String(encoding.clone()))
331                    .collect(),
332            ),
333        );
334        object.insert("num_values".into(), json!(column.num_values));
335        object.insert("null_count".into(), json!(column.null_count));
336        object.insert("min".into(), column.min.clone().unwrap_or(Value::Null));
337        object.insert("max".into(), column.max.clone().unwrap_or(Value::Null));
338        object.insert("compressed_size".into(), json!(column.compressed_size));
339        object.insert("uncompressed_size".into(), json!(column.uncompressed_size));
340        object.insert(
341            "share".into(),
342            json!(if file.size_bytes > 0 {
343                column.compressed_size as f64 / file.size_bytes as f64
344            } else {
345                0.0
346            }),
347        );
348        object.insert(
349            "ratio".into(),
350            json!(if column.uncompressed_size > 0 {
351                column.compressed_size as f64 / column.uncompressed_size as f64
352            } else {
353                0.0
354            }),
355        );
356        object.insert(
357            "bytes_per_value".into(),
358            json!(if column.num_values > 0 {
359                column.compressed_size as f64 / column.num_values as f64
360            } else {
361                0.0
362            }),
363        );
364        if let Some(distinct) = column.distinct_count {
365            object.insert("distinct_count".into(), json!(distinct));
366        }
367        out.push(Value::Object(object));
368    }
369
370    Ok(json!({
371        "file": path.display().to_string(),
372        "size_bytes": file.size_bytes,
373        "column_bytes": file.column_bytes,
374        "footer_bytes": file.footer_bytes,
375        "columns": out,
376    }))
377}
378
379/// The Arrow type of every leaf of a file, keyed by the leaf's path.
380///
381/// The Arrow schema of a file is a friendlier name for a column than the
382/// physical type is: `BYTE_ARRAY` is what the bytes are, `utf8` is what they
383/// mean.
384fn arrow_leaf_types(path: &Path) -> Result<BTreeMap<String, String>> {
385    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
386    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
387        .with_context(|| format!("read the footer of {}", path.display()))?;
388    let arrow_schema = builder.schema().clone();
389
390    let mut types = BTreeMap::new();
391    for field in arrow_schema.fields().iter() {
392        collect_leaves(field, "", &mut types);
393    }
394    Ok(types)
395}
396
397/// Walk a field down to its leaves.
398fn collect_leaves(field: &arrow_schema::Field, prefix: &str, types: &mut BTreeMap<String, String>) {
399    let path = if prefix.is_empty() {
400        field.name().clone()
401    } else {
402        format!("{prefix}.{}", field.name())
403    };
404    match field.data_type() {
405        arrow_schema::DataType::Struct(fields) => {
406            for inner in fields.iter() {
407                collect_leaves(inner, &path, types);
408            }
409        }
410        arrow_schema::DataType::List(inner)
411        | arrow_schema::DataType::LargeList(inner)
412        | arrow_schema::DataType::FixedSizeList(inner, _)
413        | arrow_schema::DataType::Map(inner, _) => collect_leaves(inner, &path, types),
414        other => {
415            types.insert(path, data_type_name(other));
416        }
417    }
418}
419
420struct ColumnStats {
421    path: String,
422    physical_type: String,
423    logical_type: String,
424    compression: String,
425    encodings: BTreeSet<String>,
426    num_values: i64,
427    null_count: u64,
428    min: Option<Value>,
429    max: Option<Value>,
430    compressed_size: i64,
431    uncompressed_size: i64,
432}
433
434/// Read the file and count the distinct values of every column.
435pub fn scan_distinct(path: &Path) -> Result<Vec<HashSet<String>>> {
436    let file = File::open(path)?;
437    let reader = ParquetRecordBatchReaderBuilder::try_new(file)?
438        .with_batch_size(8192)
439        .build()?;
440    let mut sets: Vec<HashSet<String>> = Vec::new();
441    for batch in reader {
442        let batch = batch?;
443        if sets.is_empty() {
444            sets = (0..batch.num_columns()).map(|_| HashSet::new()).collect();
445        }
446        for (index, column) in batch.columns().iter().enumerate() {
447            let set = &mut sets[index];
448            for row in 0..batch.num_rows() {
449                let value = crate::value::cell(column, row);
450                set.insert(value.to_string());
451            }
452        }
453    }
454    Ok(sets)
455}
456
457/// The smallest of two bounds, comparing as JSON numbers when possible.
458fn merge_min(left: Option<Value>, right: Option<Value>) -> Option<Value> {
459    match (left, right) {
460        (None, other) | (other, None) => other,
461        (Some(a), Some(b)) => {
462            let take_a = match (&a, &b) {
463                (Value::Number(x), Value::Number(y)) => {
464                    x.as_f64().unwrap_or(f64::MAX) <= y.as_f64().unwrap_or(f64::MAX)
465                }
466                _ => {
467                    let (a, b) = (a.to_string(), b.to_string());
468                    a <= b
469                }
470            };
471            Some(if take_a { a } else { b })
472        }
473    }
474}
475
476/// The largest of two bounds, comparing as JSON numbers when possible.
477fn merge_max(left: Option<Value>, right: Option<Value>) -> Option<Value> {
478    match (left, right) {
479        (None, other) | (other, None) => other,
480        (Some(a), Some(b)) => {
481            let take_a = match (&a, &b) {
482                (Value::Number(x), Value::Number(y)) => {
483                    x.as_f64().unwrap_or(f64::MIN) >= y.as_f64().unwrap_or(f64::MIN)
484                }
485                _ => {
486                    let (a, b) = (a.to_string(), b.to_string());
487                    a >= b
488                }
489            };
490            Some(if take_a { a } else { b })
491        }
492    }
493}
494
495/// The min and max of a column's statistics.
496fn bounds(statistics: &Statistics) -> (Option<Value>, Option<Value>) {
497    match statistics {
498        Statistics::Boolean(values) => (
499            values.min_opt().map(|v| Value::Bool(*v)),
500            values.max_opt().map(|v| Value::Bool(*v)),
501        ),
502        Statistics::Int32(values) => (
503            values.min_opt().map(|v| json!(v)),
504            values.max_opt().map(|v| json!(v)),
505        ),
506        Statistics::Int64(values) => (
507            values.min_opt().map(|v| json!(v)),
508            values.max_opt().map(|v| json!(v)),
509        ),
510        Statistics::Int96(values) => (
511            values.min_opt().map(|v| json!(v.to_string())),
512            values.max_opt().map(|v| json!(v.to_string())),
513        ),
514        Statistics::Float(values) => (
515            values.min_opt().map(|v| json!(v)),
516            values.max_opt().map(|v| json!(v)),
517        ),
518        Statistics::Double(values) => (
519            values.min_opt().map(|v| json!(v)),
520            values.max_opt().map(|v| json!(v)),
521        ),
522        Statistics::ByteArray(values) => (
523            values.min_opt().map(|v| bytes_value(v.as_bytes())),
524            values.max_opt().map(|v| bytes_value(v.as_bytes())),
525        ),
526        Statistics::FixedLenByteArray(values) => (
527            values.min_opt().map(|v| bytes_value(v.as_bytes())),
528            values.max_opt().map(|v| bytes_value(v.as_bytes())),
529        ),
530    }
531}
532
533/// Bytes as text when they are text, as hex when they are not.
534fn bytes_value(bytes: &[u8]) -> Value {
535    match std::str::from_utf8(bytes) {
536        Ok(text) => Value::String(text.to_string()),
537        Err(_) => Value::String(bytes.iter().map(|b| format!("{b:02x}")).collect()),
538    }
539}