parquet-cli 0.1.1

A Parquet CLI for AI agents: inspect, measure and convert Parquet files.
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
//! What is in the file: its facts, its schema, and its columns' statistics.

use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fs::File;
use std::path::Path;
use std::sync::Arc;

use anyhow::{Context, Result};
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::data_type::AsBytes;
use parquet::file::metadata::ParquetMetaData;
use parquet::file::statistics::Statistics;
use serde_json::{json, Map, Value};

use crate::value::{data_type_name, field_json};

/// Open a Parquet file and read its footer.
pub fn open(path: &Path) -> Result<Arc<ParquetMetaData>> {
    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
        .with_context(|| format!("read the footer of {}", path.display()))?;
    Ok(builder.metadata().clone())
}

/// File-level facts: size, rows, row groups, who wrote it.
pub fn facts(path: &Path) -> Result<Value> {
    let metadata = open(path)?;
    let file = metadata.file_metadata();
    let size = std::fs::metadata(path)?.len();
    let rows = file.num_rows();

    let mut compressions = BTreeSet::new();
    let mut encodings = BTreeSet::new();
    for group in metadata.row_groups() {
        for chunk in group.columns() {
            compressions.insert(format!("{}", chunk.compression_codec()));
            for encoding in chunk.encodings() {
                encodings.insert(format!("{encoding}"));
            }
        }
    }

    let key_value_metadata: Vec<Value> = file
        .key_value_metadata()
        .map(|entries| {
            entries
                .iter()
                .map(|entry| {
                    json!({
                        "key": entry.key,
                        "value": entry.value,
                    })
                })
                .collect()
        })
        .unwrap_or_default();

    let row_groups: Vec<Value> = metadata
        .row_groups()
        .iter()
        .enumerate()
        .map(|(index, group)| {
            json!({
                "index": index,
                "rows": group.num_rows(),
                "compressed_size": group.compressed_size(),
                "uncompressed_size": group.total_byte_size(),
            })
        })
        .collect();

    Ok(json!({
        "file": path.display().to_string(),
        "size_bytes": size,
        "rows": rows,
        "row_groups": metadata.row_groups().len(),
        "columns": metadata.file_metadata().schema_descr().num_columns(),
        "format_version": file.version(),
        "created_by": file.created_by(),
        "bytes_per_row": if rows > 0 { size as f64 / rows as f64 } else { 0.0 },
        "compressions": compressions.into_iter().collect::<Vec<_>>(),
        "encodings": encodings.into_iter().collect::<Vec<_>>(),
        "key_value_metadata": key_value_metadata,
        "row_group_detail": row_groups,
    }))
}

/// The schema, as Arrow sees it.
pub fn schema(path: &Path) -> Result<Value> {
    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
        .with_context(|| format!("read the footer of {}", path.display()))?;
    let arrow_schema = builder.schema().clone();
    let fields: Vec<Value> = arrow_schema
        .fields()
        .iter()
        .map(|field| field_json(field.as_ref()))
        .collect();
    Ok(json!({
        "file": path.display().to_string(),
        "fields": fields,
    }))
}

/// The schema as flat lines: `name  type  nullable`.
pub fn schema_lines(path: &Path) -> Result<Vec<(String, String, bool)>> {
    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
        .with_context(|| format!("read the footer of {}", path.display()))?;
    let arrow_schema = builder.schema().clone();
    let mut lines = Vec::new();
    for field in arrow_schema.fields().iter() {
        lines.push((
            field.name().clone(),
            data_type_name(field.data_type()),
            field.is_nullable(),
        ));
    }
    Ok(lines)
}

/// Per-column statistics, taken from the footer.
///
/// With `scan`, the file is also read so the distinct counts are exact.
pub fn columns(path: &Path, scan: bool) -> Result<Value> {
    let metadata = open(path)?;
    let arrow_types = arrow_leaf_types(path)?;

    let distinct_counts: Option<Vec<HashSet<String>>> = if scan {
        Some(scan_distinct(path)?)
    } else {
        None
    };

    // The columns of the footer are leaves: a struct column shows up as one
    // leaf per field, named by its path.
    let leaf_names: Vec<String> = metadata
        .file_metadata()
        .schema_descr()
        .columns()
        .iter()
        .map(|column| column.path().string())
        .collect();

    let mut out = Vec::new();
    // Gather per column across row groups.
    let mut per_column: BTreeMap<usize, ColumnStats> = BTreeMap::new();
    for (group_index, group) in metadata.row_groups().iter().enumerate() {
        for (position, chunk) in group.columns().iter().enumerate() {
            let stats = per_column.entry(position).or_insert_with(|| ColumnStats {
                path: chunk.column_path().string(),
                physical_type: format!("{}", chunk.column_type()),
                logical_type: chunk
                    .column_descr()
                    .logical_type_ref()
                    .map(|logical| format!("{logical:?}"))
                    .unwrap_or_else(|| "-".into()),
                compression: format!("{}", chunk.compression_codec()),
                encodings: BTreeSet::new(),
                num_values: 0,
                null_count: 0,
                min: None,
                max: None,
                compressed_size: 0,
                uncompressed_size: 0,
                row_groups: Vec::new(),
            });
            stats
                .encodings
                .extend(chunk.encodings().map(|e| format!("{e}")));
            stats.num_values += chunk.num_values();
            stats.compressed_size += chunk.compressed_size();
            stats.uncompressed_size += chunk.uncompressed_size();
            let mut group_min = Value::Null;
            let mut group_max = Value::Null;
            if let Some(statistics) = chunk.statistics() {
                stats.null_count += statistics.null_count_opt().unwrap_or(0);
                let (min, max) = bounds(statistics);
                group_min = min.clone().unwrap_or(Value::Null);
                group_max = max.clone().unwrap_or(Value::Null);
                stats.min = merge_min(stats.min.take(), min);
                stats.max = merge_max(stats.max.take(), max);
            }
            stats.row_groups.push(json!({
                "index": group_index,
                "rows": group.num_rows(),
                "min": group_min,
                "max": group_max,
            }));
        }
    }

    for (position, stats) in per_column.iter() {
        let name = leaf_names
            .get(*position)
            .cloned()
            .unwrap_or_else(|| stats.path.clone());
        let mut object = Map::new();
        object.insert("name".into(), Value::String(name));
        object.insert("path".into(), Value::String(stats.path.clone()));
        object.insert(
            "physical_type".into(),
            Value::String(stats.physical_type.clone()),
        );
        object.insert(
            "logical_type".into(),
            Value::String(stats.logical_type.clone()),
        );
        // The type a person reads: the logical type when the file carries
        // one, the Arrow type when it does not but the Arrow schema is
        // there (DuckDB's writer leaves the logical type out), and the
        // physical type when there is nothing better.
        let readable = if stats.logical_type != "-" {
            stats.logical_type.clone()
        } else {
            arrow_types
                .get(&stats.path)
                .cloned()
                .unwrap_or_else(|| stats.physical_type.clone())
        };
        object.insert("type".into(), Value::String(readable));
        object.insert(
            "compression".into(),
            Value::String(stats.compression.clone()),
        );
        object.insert(
            "encodings".into(),
            Value::Array(
                stats
                    .encodings
                    .iter()
                    .map(|e| Value::String(e.clone()))
                    .collect(),
            ),
        );
        object.insert("num_values".into(), json!(stats.num_values));
        object.insert("null_count".into(), json!(stats.null_count));
        object.insert("min".into(), stats.min.clone().unwrap_or(Value::Null));
        object.insert("max".into(), stats.max.clone().unwrap_or(Value::Null));
        object.insert("compressed_size".into(), json!(stats.compressed_size));
        object.insert("uncompressed_size".into(), json!(stats.uncompressed_size));
        object.insert(
            "ratio".into(),
            json!(if stats.uncompressed_size > 0 {
                stats.compressed_size as f64 / stats.uncompressed_size as f64
            } else {
                0.0
            }),
        );
        object.insert(
            "bytes_per_value".into(),
            json!(if stats.num_values > 0 {
                stats.compressed_size as f64 / stats.num_values as f64
            } else {
                0.0
            }),
        );
        if let Some(distinct) = &distinct_counts {
            object.insert(
                "distinct_count".into(),
                json!(distinct.get(*position).map(|set| set.len()).unwrap_or(0)),
            );
        }
        object.insert("row_groups".into(), Value::Array(stats.row_groups.clone()));
        out.push(Value::Object(object));
    }

    Ok(json!({
        "file": path.display().to_string(),
        "columns": out,
    }))
}

/// The Arrow type of every leaf of a file, keyed by the leaf's path.
///
/// The Arrow schema of a file is a friendlier name for a column than the
/// physical type is: `BYTE_ARRAY` is what the bytes are, `utf8` is what they
/// mean.
fn arrow_leaf_types(path: &Path) -> Result<BTreeMap<String, String>> {
    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
        .with_context(|| format!("read the footer of {}", path.display()))?;
    let arrow_schema = builder.schema().clone();

    let mut types = BTreeMap::new();
    for field in arrow_schema.fields().iter() {
        collect_leaves(field, "", &mut types);
    }
    Ok(types)
}

/// Walk a field down to its leaves.
fn collect_leaves(field: &arrow_schema::Field, prefix: &str, types: &mut BTreeMap<String, String>) {
    let path = if prefix.is_empty() {
        field.name().clone()
    } else {
        format!("{prefix}.{}", field.name())
    };
    match field.data_type() {
        arrow_schema::DataType::Struct(fields) => {
            for inner in fields.iter() {
                collect_leaves(inner, &path, types);
            }
        }
        arrow_schema::DataType::List(inner)
        | arrow_schema::DataType::LargeList(inner)
        | arrow_schema::DataType::FixedSizeList(inner, _)
        | arrow_schema::DataType::Map(inner, _) => collect_leaves(inner, &path, types),
        other => {
            types.insert(path, data_type_name(other));
        }
    }
}

struct ColumnStats {
    path: String,
    physical_type: String,
    logical_type: String,
    compression: String,
    encodings: BTreeSet<String>,
    num_values: i64,
    null_count: u64,
    min: Option<Value>,
    max: Option<Value>,
    compressed_size: i64,
    uncompressed_size: i64,
    row_groups: Vec<Value>,
}

/// Read the file and count the distinct values of every column.
fn scan_distinct(path: &Path) -> Result<Vec<HashSet<String>>> {
    let file = File::open(path)?;
    let reader = ParquetRecordBatchReaderBuilder::try_new(file)?
        .with_batch_size(8192)
        .build()?;
    let mut sets: Vec<HashSet<String>> = Vec::new();
    for batch in reader {
        let batch = batch?;
        if sets.is_empty() {
            sets = (0..batch.num_columns()).map(|_| HashSet::new()).collect();
        }
        for (index, column) in batch.columns().iter().enumerate() {
            let set = &mut sets[index];
            for row in 0..batch.num_rows() {
                let value = crate::value::cell(column, row);
                set.insert(value.to_string());
            }
        }
    }
    Ok(sets)
}

/// The smallest of two bounds, comparing as JSON numbers when possible.
fn merge_min(left: Option<Value>, right: Option<Value>) -> Option<Value> {
    match (left, right) {
        (None, other) | (other, None) => other,
        (Some(a), Some(b)) => {
            let take_a = match (&a, &b) {
                (Value::Number(x), Value::Number(y)) => {
                    x.as_f64().unwrap_or(f64::MAX) <= y.as_f64().unwrap_or(f64::MAX)
                }
                _ => {
                    let (a, b) = (a.to_string(), b.to_string());
                    a <= b
                }
            };
            Some(if take_a { a } else { b })
        }
    }
}

/// The largest of two bounds, comparing as JSON numbers when possible.
fn merge_max(left: Option<Value>, right: Option<Value>) -> Option<Value> {
    match (left, right) {
        (None, other) | (other, None) => other,
        (Some(a), Some(b)) => {
            let take_a = match (&a, &b) {
                (Value::Number(x), Value::Number(y)) => {
                    x.as_f64().unwrap_or(f64::MIN) >= y.as_f64().unwrap_or(f64::MIN)
                }
                _ => {
                    let (a, b) = (a.to_string(), b.to_string());
                    a >= b
                }
            };
            Some(if take_a { a } else { b })
        }
    }
}

/// The min and max of a column's statistics.
fn bounds(statistics: &Statistics) -> (Option<Value>, Option<Value>) {
    match statistics {
        Statistics::Boolean(values) => (
            values.min_opt().map(|v| Value::Bool(*v)),
            values.max_opt().map(|v| Value::Bool(*v)),
        ),
        Statistics::Int32(values) => (
            values.min_opt().map(|v| json!(v)),
            values.max_opt().map(|v| json!(v)),
        ),
        Statistics::Int64(values) => (
            values.min_opt().map(|v| json!(v)),
            values.max_opt().map(|v| json!(v)),
        ),
        Statistics::Int96(values) => (
            values.min_opt().map(|v| json!(v.to_string())),
            values.max_opt().map(|v| json!(v.to_string())),
        ),
        Statistics::Float(values) => (
            values.min_opt().map(|v| json!(v)),
            values.max_opt().map(|v| json!(v)),
        ),
        Statistics::Double(values) => (
            values.min_opt().map(|v| json!(v)),
            values.max_opt().map(|v| json!(v)),
        ),
        Statistics::ByteArray(values) => (
            values.min_opt().map(|v| bytes_value(v.as_bytes())),
            values.max_opt().map(|v| bytes_value(v.as_bytes())),
        ),
        Statistics::FixedLenByteArray(values) => (
            values.min_opt().map(|v| bytes_value(v.as_bytes())),
            values.max_opt().map(|v| bytes_value(v.as_bytes())),
        ),
    }
}

/// Bytes as text when they are text, as hex when they are not.
fn bytes_value(bytes: &[u8]) -> Value {
    match std::str::from_utf8(bytes) {
        Ok(text) => Value::String(text.to_string()),
        Err(_) => Value::String(bytes.iter().map(|b| format!("{b:02x}")).collect()),
    }
}