parquet-cli 0.3.0

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
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
//! 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())
}

/// What the footer says about the file as a whole.
#[derive(Clone, Debug)]
pub struct FileFacts {
    /// The path, as it was given.
    pub path: String,
    /// How many bytes the file is.
    pub size_bytes: u64,
    /// How many rows it holds.
    pub rows: i64,
    /// How many row groups it has.
    pub row_groups: usize,
    /// How many leaf columns it has.
    pub columns: usize,
    /// How many rows each row group holds.
    pub row_group_rows: Vec<i64>,
    /// The bytes the column chunks take.
    pub column_bytes: i64,
    /// The bytes after the data: the metadata, the page index, and the
    /// magic. This is what a reader fetches before it can read anything.
    pub footer_bytes: i64,
    /// The bytes the metadata itself takes (the tail of the file).
    pub metadata_bytes: i64,
    /// The bytes each row group takes.
    pub row_group_bytes: Vec<i64>,
    /// What one lookup reads, typically: the footer plus one row group.
    pub lookup_reads_typical: i64,
    /// What one lookup reads at worst: the footer plus the largest row group.
    pub lookup_reads_worst: i64,
    /// Who wrote the file.
    pub created_by: Option<String>,
    /// The Parquet format version.
    pub format_version: i32,
    /// The compressions the columns use.
    pub compressions: Vec<String>,
    /// The encodings the pages use.
    pub encodings: Vec<String>,
    /// The key-value metadata the writer left behind.
    pub key_value_metadata: Vec<Value>,
}

/// What the footer says about one column.
#[derive(Clone, Debug)]
pub struct ColumnFacts {
    /// The name of the leaf column (its path, when it is nested).
    pub name: String,
    /// The type a person reads: the logical type when the file has one, the
    /// Arrow type when it does not but the Arrow schema is there, the physical
    /// type when there is nothing better.
    pub data_type: String,
    /// The physical type (`INT64`, `BYTE_ARRAY`, …).
    pub physical_type: String,
    /// The logical type, when the file carries one.
    pub logical_type: String,
    /// The compression the column was written with.
    pub compression: String,
    /// The encodings its pages use.
    pub encodings: Vec<String>,
    /// How many values there are (nulls included).
    pub num_values: i64,
    /// How many of them are null.
    pub null_count: u64,
    /// The smallest value, when the footer has it.
    pub min: Option<Value>,
    /// The largest value, when the footer has it.
    pub max: Option<Value>,
    /// How many bytes the column takes in the file.
    pub compressed_size: i64,
    /// How many bytes the values take before compression.
    pub uncompressed_size: i64,
    /// The distinct values, when the file was read to count them.
    pub distinct_count: Option<u64>,
    /// The statistics of each row group: what a reader uses to skip one.
    pub row_groups: Vec<GroupStat>,
}

/// What one row group holds of one column.
#[derive(Clone, Debug)]
pub struct GroupStat {
    /// Which row group this is.
    pub index: usize,
    /// How many rows it holds.
    pub rows: i64,
    /// The smallest value in it.
    pub min: Option<Value>,
    /// The largest value in it.
    pub max: Option<Value>,
}

/// File-level facts: size, rows, row groups, who wrote it.
pub fn facts(path: &Path) -> Result<Value> {
    let file = file_facts(path)?;
    Ok(json!({
        "file": file.path,
        "size_bytes": file.size_bytes,
        "rows": file.rows,
        "row_groups": file.row_groups,
        "columns": file.columns,
        "format_version": file.format_version,
        "created_by": file.created_by,
        "bytes_per_row": if file.rows > 0 {
            file.size_bytes as f64 / file.rows as f64
        } else {
            0.0
        },
        "column_bytes": file.column_bytes,
        "footer_bytes": file.footer_bytes,
        "metadata_bytes": file.metadata_bytes,
        "row_group_bytes": file.row_group_bytes,
        "lookup_reads_typical": file.lookup_reads_typical,
        "lookup_reads_worst": file.lookup_reads_worst,
        "rows_per_group": {
            "min": file.row_group_rows.iter().copied().min().unwrap_or(0),
            "max": file.row_group_rows.iter().copied().max().unwrap_or(0),
            "average": if file.row_group_rows.is_empty() {
                0
            } else {
                file.rows / file.row_groups as i64
            },
            "even": file
                .row_group_rows
                .iter()
                .all(|rows| *rows == file.row_group_rows[0]),
        },
        "compressions": file.compressions,
        "encodings": file.encodings,
        "key_value_metadata": file.key_value_metadata,
        "row_group_rows": file.row_group_rows,
    }))
}

/// The footer, read as facts.
pub fn file_facts(path: &Path) -> Result<FileFacts> {
    let metadata = open(path)?;
    let file = metadata.file_metadata();
    let size_bytes = std::fs::metadata(path)?.len();
    let rows = file.num_rows();

    let mut compressions = BTreeSet::new();
    let mut encodings = BTreeSet::new();
    let mut column_bytes = 0i64;
    let mut row_group_bytes = Vec::new();
    for group in metadata.row_groups() {
        let mut group_bytes = 0i64;
        for chunk in group.columns() {
            compressions.insert(format!("{}", chunk.compression_codec()));
            encodings.extend(chunk.encodings().map(|encoding| format!("{encoding}")));
            group_bytes += chunk.compressed_size();
        }
        column_bytes += group_bytes;
        row_group_bytes.push(group_bytes);
    }

    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 footer_bytes = size_bytes as i64 - column_bytes;
    let metadata_bytes = metadata_size(path).unwrap_or(footer_bytes);
    let typical_group = if row_group_bytes.is_empty() {
        0
    } else {
        row_group_bytes.iter().sum::<i64>() / row_group_bytes.len() as i64
    };
    let largest_group = row_group_bytes.iter().copied().max().unwrap_or(0);

    Ok(FileFacts {
        path: path.display().to_string(),
        size_bytes,
        rows,
        row_groups: metadata.row_groups().len(),
        columns: metadata.file_metadata().schema_descr().num_columns(),
        row_group_rows: metadata
            .row_groups()
            .iter()
            .map(|group| group.num_rows())
            .collect(),
        column_bytes,
        footer_bytes,
        metadata_bytes,
        row_group_bytes,
        lookup_reads_typical: footer_bytes + typical_group,
        lookup_reads_worst: footer_bytes + largest_group,
        created_by: file.created_by().map(|text| text.to_string()),
        format_version: file.version(),
        compressions: compressions.into_iter().collect(),
        encodings: encodings.into_iter().collect(),
        key_value_metadata,
    })
}

/// How many bytes the metadata at the end of the file takes.
///
/// A Parquet file ends with the metadata, its length as four little-endian
/// bytes, and the magic `PAR1`.
fn metadata_size(path: &Path) -> Option<i64> {
    use std::io::{Read, Seek, SeekFrom};
    let mut file = File::open(path).ok()?;
    let size = file.metadata().ok()?.len();
    if size < 8 {
        return None;
    }
    file.seek(SeekFrom::Start(size - 8)).ok()?;
    let mut tail = [0u8; 8];
    file.read_exact(&mut tail).ok()?;
    if &tail[4..8] != b"PAR1" {
        return None;
    }
    let length = u32::from_le_bytes([tail[0], tail[1], tail[2], tail[3]]) as i64;
    Some(length + 8)
}

/// 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 column_facts(path: &Path, scan: bool) -> Result<Vec<ColumnFacts>> {
    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 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(|encoding| format!("{encoding}")));
            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(GroupStat {
                index: group_index,
                rows: group.num_rows(),
                min: if group_min.is_null() {
                    None
                } else {
                    Some(group_min)
                },
                max: if group_max.is_null() {
                    None
                } else {
                    Some(group_max)
                },
            });
        }
    }

    let mut facts = Vec::new();
    for (position, stats) in per_column.iter() {
        let name = leaf_names
            .get(*position)
            .cloned()
            .unwrap_or_else(|| stats.path.clone());
        // The Arrow type reads best (`utf8`, `decimal128(21,1)`); the logical
        // type is the writer's own wording, and the physical type is the
        // fallback when there is no Arrow schema to go by.
        let data_type = arrow_types
            .get(&stats.path)
            .cloned()
            .or_else(|| {
                if stats.logical_type != "-" {
                    Some(stats.logical_type.clone())
                } else {
                    None
                }
            })
            .unwrap_or_else(|| stats.physical_type.clone());
        facts.push(ColumnFacts {
            name,
            data_type,
            physical_type: stats.physical_type.clone(),
            logical_type: stats.logical_type.clone(),
            compression: stats.compression.clone(),
            encodings: stats.encodings.iter().cloned().collect(),
            num_values: stats.num_values,
            null_count: stats.null_count,
            min: stats.min.clone(),
            max: stats.max.clone(),
            compressed_size: stats.compressed_size,
            uncompressed_size: stats.uncompressed_size,
            distinct_count: distinct_counts
                .as_ref()
                .and_then(|sets| sets.get(*position))
                .map(|set| set.len() as u64),
            row_groups: stats.row_groups.clone(),
        });
    }
    Ok(facts)
}

/// Per-column statistics as JSON.
pub fn columns(path: &Path, scan: bool) -> Result<Value> {
    let file = file_facts(path)?;
    let facts = column_facts(path, scan)?;

    let mut out = Vec::new();
    for column in facts {
        let mut object = Map::new();
        object.insert("name".into(), Value::String(column.name.clone()));
        object.insert("type".into(), Value::String(column.data_type.clone()));
        object.insert(
            "physical_type".into(),
            Value::String(column.physical_type.clone()),
        );
        object.insert(
            "logical_type".into(),
            Value::String(column.logical_type.clone()),
        );
        object.insert(
            "compression".into(),
            Value::String(column.compression.clone()),
        );
        object.insert(
            "encodings".into(),
            Value::Array(
                column
                    .encodings
                    .iter()
                    .map(|encoding| Value::String(encoding.clone()))
                    .collect(),
            ),
        );
        object.insert("num_values".into(), json!(column.num_values));
        object.insert("null_count".into(), json!(column.null_count));
        object.insert("min".into(), column.min.clone().unwrap_or(Value::Null));
        object.insert("max".into(), column.max.clone().unwrap_or(Value::Null));
        object.insert("compressed_size".into(), json!(column.compressed_size));
        // The same number, under the name a script would reach for.
        object.insert("bytes".into(), json!(column.compressed_size));
        object.insert("uncompressed_size".into(), json!(column.uncompressed_size));
        object.insert(
            "share".into(),
            json!(if file.size_bytes > 0 {
                column.compressed_size as f64 / file.size_bytes as f64
            } else {
                0.0
            }),
        );
        object.insert(
            "ratio".into(),
            json!(if column.uncompressed_size > 0 {
                column.compressed_size as f64 / column.uncompressed_size as f64
            } else {
                0.0
            }),
        );
        object.insert(
            "bytes_per_value".into(),
            json!(if column.num_values > 0 {
                column.compressed_size as f64 / column.num_values as f64
            } else {
                0.0
            }),
        );
        if let Some(distinct) = column.distinct_count {
            object.insert("distinct_count".into(), json!(distinct));
        }
        let row_groups: Vec<Value> = column
            .row_groups
            .iter()
            .map(|group| {
                json!({
                    "index": group.index,
                    "rows": group.rows,
                    "min": group.min.clone().unwrap_or(Value::Null),
                    "max": group.max.clone().unwrap_or(Value::Null),
                })
            })
            .collect();
        object.insert("row_groups".into(), Value::Array(row_groups));
        out.push(Value::Object(object));
    }

    Ok(json!({
        "file": path.display().to_string(),
        "size_bytes": file.size_bytes,
        "column_bytes": file.column_bytes,
        "footer_bytes": file.footer_bytes,
        "metadata_bytes": file.metadata_bytes,
        "row_group_bytes": file.row_group_bytes,
        "lookup_reads_typical": file.lookup_reads_typical,
        "lookup_reads_worst": file.lookup_reads_worst,
        "rows_per_group": {
            "min": file.row_group_rows.iter().copied().min().unwrap_or(0),
            "max": file.row_group_rows.iter().copied().max().unwrap_or(0),
            "average": if file.row_group_rows.is_empty() {
                0
            } else {
                file.rows / file.row_groups as i64
            },
            "even": file
                .row_group_rows
                .iter()
                .all(|rows| *rows == file.row_group_rows[0]),
        },
        "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<GroupStat>,
}

/// Read the file and count the distinct values of every column.
pub 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()),
    }
}