parquet-cli 0.1.7

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
//! pqt — inspect, measure and convert Parquet files.

use std::io::Write;
use std::path::PathBuf;

use anyhow::Result;
use clap::{Parser, Subcommand};
use serde_json::Value;

use parquet_cli::advise;
use parquet_cli::bench;
use parquet_cli::compare;
use parquet_cli::meta;
use parquet_cli::output::{write_aligned, write_table, Format, Table};
use parquet_cli::rows::{self, ConvertFormat};

#[derive(Parser, Debug)]
#[command(
    name = "pqt",
    version,
    about = "A Parquet CLI for AI agents",
    long_about = "Inspect, measure and convert Parquet files.\n\n\
Every command is non-interactive, and every command has a JSON form: pass \
--json and the result is one object on stdout, ready to be read by a program."
)]
struct Cli {
    /// Print JSON instead of a human table.
    #[arg(long, global = true)]
    json: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand, Debug)]
enum Command {
    /// Facts about the file: size, rows, row groups, who wrote it.
    Info {
        /// The Parquet file.
        file: PathBuf,
        /// Also say what one lookup reads: the footer plus one row group.
        #[arg(long)]
        lookup_cost: bool,
        /// Also list the row groups, with their sizes.
        #[arg(long)]
        row_groups: bool,
    },

    /// The schema of the file.
    Schema {
        /// The Parquet file.
        file: PathBuf,
    },

    /// Per-column statistics: values, nulls, bounds, bytes.
    Columns {
        /// The Parquet file.
        file: PathBuf,
        /// Read the data too, so the distinct counts are exact.
        #[arg(long)]
        scan: bool,
    },

    /// The first rows of the file.
    Head {
        /// The Parquet file.
        file: PathBuf,
        /// How many rows to print.
        #[arg(short = 'n', long, default_value_t = 10)]
        rows: usize,
        /// How to print them.
        #[arg(long, value_enum, default_value_t = Format::Table)]
        format: Format,
    },

    /// All the rows of one or more files.
    Cat {
        /// The Parquet files.
        files: Vec<PathBuf>,
        /// How to print them.
        #[arg(long, value_enum, default_value_t = Format::Table)]
        format: Format,
    },

    /// Look at the data and say what could be better.
    Advise {
        /// The Parquet file.
        file: PathBuf,
        /// Read the data too, so the advice can use the distinct values.
        #[arg(long)]
        scan: bool,
        /// Rewrite the largest columns with a constant, to see what their
        /// values cost. The number is how many columns.
        #[arg(long, value_name = "N")]
        contrast: Option<usize>,
    },

    /// Write the file again with other settings, and say what it cost.
    Bench {
        /// The Parquet file.
        file: PathBuf,
        /// A setting to change, in DuckDB's spelling: `compression=zstd`,
        /// `compression_level=19`, `row_group_size=1000`, `dictionary=off`,
        /// `write_bloom_filter=on`, `write_page_index=off`. The short form
        /// works too: `zstd:19`, `row-group:1000`.
        #[arg(long = "with", value_name = "SETTING")]
        settings: Vec<String>,
        /// Try one setting at a time, from the file's own settings.
        #[arg(long)]
        sweep: bool,
        /// Keep the rewritten file at this path.
        #[arg(long = "out")]
        keep: Option<PathBuf>,
    },

    /// Write the file again, sorted by a key.
    Sort {
        /// The Parquet file.
        file: PathBuf,
        /// The column to sort by.
        #[arg(long)]
        by: String,
        /// Sort downwards.
        #[arg(long)]
        descending: bool,
        /// Where to write it.
        #[arg(long)]
        out: PathBuf,
        /// The settings for the new file, in DuckDB's names.
        #[arg(long = "with", value_name = "SETTING")]
        settings: Vec<String>,
    },

    /// Run a Luau script, with the tool's API in it.
    Script {
        /// The script to run.
        script: PathBuf,
        /// Arguments for the script (`arg[1]` and onwards).
        #[arg(
            value_name = "ARGS",
            trailing_var_arg = true,
            allow_hyphen_values = true
        )]
        args: Vec<String>,
    },

    /// Compare several files with each other.
    Compare {
        /// The Parquet files, or the directories holding them.
        files: Vec<PathBuf>,
    },

    /// Check the file's structure.
    Validate {
        /// The Parquet file.
        file: PathBuf,
    },

    /// Write the file out in another form.
    To {
        /// The Parquet file.
        file: PathBuf,
        /// Where to write it.
        #[arg(long)]
        out: PathBuf,
        /// What to write.
        #[arg(long, value_enum, default_value_t = ConvertFormat::Csv)]
        format: ConvertFormat,
        /// Only these columns, comma separated.
        #[arg(long, value_name = "COLUMNS")]
        columns: Option<String>,
    },
}

fn main() -> Result<()> {
    let cli = Cli::parse();
    let mut out = std::io::stdout().lock();

    match cli.command {
        Command::Info {
            file,
            lookup_cost,
            row_groups,
        } => {
            let facts = meta::facts(&file)?;
            if cli.json {
                writeln!(out, "{}", serde_json::to_string_pretty(&facts)?)?;
            } else {
                print_facts(&mut out, &facts)?;
                if lookup_cost {
                    print_lookup_cost(&mut out, &facts)?;
                }
                if row_groups {
                    print_row_groups(&mut out, &facts)?;
                }
            }
        }
        Command::Schema { file } => {
            let schema = meta::schema(&file)?;
            if cli.json {
                writeln!(out, "{}", serde_json::to_string_pretty(&schema)?)?;
            } else {
                let lines = meta::schema_lines(&file)?;
                let mut table = Table::new(vec!["column".into(), "type".into(), "nullable".into()]);
                for (name, data_type, nullable) in lines {
                    table.push(vec![
                        Value::String(name),
                        Value::String(data_type),
                        Value::Bool(nullable),
                    ]);
                }
                write_aligned(&mut out, &table)?;
            }
        }
        Command::Columns { file, scan } => {
            let columns = meta::columns(&file, scan)?;
            if cli.json {
                writeln!(out, "{}", serde_json::to_string_pretty(&columns)?)?;
            } else {
                let mut table = Table::new(vec![
                    "column".into(),
                    "type".into(),
                    "compression".into(),
                    "values".into(),
                    "nulls".into(),
                    "min".into(),
                    "max".into(),
                    "bytes".into(),
                    "bytes/value".into(),
                ]);
                for column in columns["columns"].as_array().into_iter().flatten() {
                    table.push(vec![
                        column["name"].clone(),
                        column["type"].clone(),
                        column["compression"].clone(),
                        column["num_values"].clone(),
                        column["null_count"].clone(),
                        column["min"].clone(),
                        column["max"].clone(),
                        column["compressed_size"].clone(),
                        column["bytes_per_value"].clone(),
                    ]);
                }
                write_aligned(&mut out, &table)?;
            }
        }
        Command::Head { file, rows, format } => {
            let table = rows::head(&file, rows)?;
            write_table(&mut out, &table, format_for(cli.json, format))?;
        }
        Command::Cat { files, format } => {
            let table = rows::cat(&files)?;
            write_table(&mut out, &table, format_for(cli.json, format))?;
        }
        Command::Advise {
            file,
            scan,
            contrast,
        } => {
            let advice = advise::advise(&file, scan, contrast)?;
            if cli.json {
                writeln!(out, "{}", serde_json::to_string_pretty(&advice.to_json())?)?;
            } else {
                print_advice(&mut out, &advice)?;
            }
        }
        Command::Bench {
            file,
            settings,
            sweep,
            keep,
        } => {
            let mut plan = parquet_cli::plan::Plan::new();
            for option in &settings {
                for (name, value) in parquet_cli::plan::parse_option(option)? {
                    plan.set(&name, &value)?;
                }
            }
            let result = bench::bench(&file, &plan, sweep, keep.as_deref())?;
            if cli.json {
                writeln!(out, "{}", serde_json::to_string_pretty(&result.to_json())?)?;
            } else {
                print_bench(&mut out, &result)?;
            }
        }
        Command::Sort {
            file,
            by,
            descending,
            out: target,
            settings,
        } => {
            let mut plan = parquet_cli::plan::Plan::new();
            for option in &settings {
                for (name, value) in parquet_cli::plan::parse_option(option)? {
                    plan.set(&name, &value)?;
                }
            }
            let bytes = parquet_cli::sort::sort_file(&file, &by, descending, &target, &plan)?;
            writeln!(
                out,
                "{} -> {} ({} bytes)",
                file.display(),
                target.display(),
                bytes
            )?;
        }
        Command::Script { script, args } => {
            parquet_cli::lua::run_file(&script, &args)?;
        }
        Command::Compare { files } => {
            let comparison = compare::compare(&files)?;
            if cli.json {
                writeln!(
                    out,
                    "{}",
                    serde_json::to_string_pretty(&comparison.to_json())?
                )?;
            } else {
                print_comparison(&mut out, &comparison)?;
            }
        }
        Command::Validate { file } => {
            let report = parquet_cli::validate::validate(&file)?;
            if cli.json {
                writeln!(out, "{}", serde_json::to_string_pretty(&report)?)?;
            } else {
                for check in report["checks"].as_array().into_iter().flatten() {
                    let mark = if check["ok"].as_bool().unwrap_or(false) {
                        "ok"
                    } else {
                        "FAIL"
                    };
                    writeln!(
                        out,
                        "{mark:>4}  {:<14} {}",
                        check["name"].as_str().unwrap_or_default(),
                        check["detail"].as_str().unwrap_or_default()
                    )?;
                }
            }
            if !report["ok"].as_bool().unwrap_or(false) {
                std::process::exit(1);
            }
        }
        Command::To {
            file,
            out: target,
            format,
            columns,
        } => {
            let columns: Option<Vec<String>> = columns.map(|names| {
                names
                    .split(',')
                    .map(|name| name.trim().to_string())
                    .filter(|name| !name.is_empty())
                    .collect()
            });
            rows::convert(&file, &target, format, columns.as_deref())?;
            if cli.json {
                writeln!(
                    out,
                    "{}",
                    serde_json::to_string_pretty(&serde_json::json!({
                        "file": file.display().to_string(),
                        "out": target.display().to_string(),
                        "format": format.to_string(),
                    }))?
                )?;
            } else {
                writeln!(out, "{} -> {}", file.display(), target.display())?;
            }
        }
    }
    Ok(())
}

/// Print the bench: what the file weighs, and what it weighs again.
fn print_bench(out: &mut impl Write, result: &bench::Bench) -> Result<()> {
    let mut facts = Table::new(vec!["file".into(), "original_bytes".into()]);
    facts.push(vec![
        Value::String(result.file.clone()),
        Value::from(result.original_bytes),
    ]);
    write_aligned(out, &facts)?;

    for run in &result.runs {
        let difference = run.bytes as i64 - result.original_bytes as i64;
        let share = difference as f64 / result.original_bytes as f64;
        writeln!(out)?;
        writeln!(out, "{}  ({})", run.label, run.settings)?;
        writeln!(out, "  rewritten     {} bytes", run.bytes)?;
        writeln!(
            out,
            "  difference    {difference} bytes ({:+.1}%)",
            share * 100.0
        )?;
    }
    Ok(())
}

/// Print the comparison: the files, then where they disagree.
fn print_comparison(out: &mut impl Write, comparison: &compare::Comparison) -> Result<()> {
    let mut files = Table::new(vec![
        "file".into(),
        "rows".into(),
        "size_bytes".into(),
        "row_groups".into(),
        "columns".into(),
    ]);
    for file in &comparison.files {
        files.push(vec![
            Value::String(file.label.clone()),
            Value::from(file.rows),
            Value::from(file.size_bytes),
            Value::from(file.row_groups),
            Value::from(file.columns.len()),
        ]);
    }
    write_aligned(out, &files)?;

    let bytes = compare::column_bytes(&comparison.files);
    if bytes.len() > 1 || comparison.files.len() > 1 {
        let mut headers = vec!["column".to_string()];
        headers.extend(comparison.files.iter().map(|file| file.label.clone()));
        let mut table = Table::new(headers);
        for (name, sizes) in &bytes {
            let mut row = vec![Value::String(name.clone())];
            row.extend(sizes.iter().map(|size| Value::from(*size)));
            table.push(row);
        }
        write_aligned(out, &table)?;
    }

    if comparison.findings.is_empty() {
        writeln!(out, "\nthe files agree")?;
        return Ok(());
    }
    writeln!(out)?;
    for finding in &comparison.findings {
        let file = match &finding.file {
            Some(file) => format!("{file}: "),
            None => String::new(),
        };
        writeln!(
            out,
            "{:>7}  {:<20} {}{}",
            finding.severity, finding.rule, file, finding.message
        )?;
    }
    Ok(())
}

/// Print the advice: what the file holds, then what could be better.
fn print_advice(out: &mut impl Write, advice: &advise::Advice) -> Result<()> {
    let mut facts = Table::new(vec!["file".into(), "size_bytes".into(), "rows".into()]);
    facts.push(vec![
        Value::String(advice.file.clone()),
        Value::from(advice.size_bytes),
        Value::from(advice.rows),
    ]);
    write_aligned(out, &facts)?;

    let mut columns = Table::new(vec![
        "column".into(),
        "type".into(),
        "bytes".into(),
        "share".into(),
        "distinct".into(),
        "values".into(),
        "shape".into(),
    ]);
    for column in &advice.columns {
        columns.push(vec![
            Value::String(column.name.clone()),
            Value::String(column.data_type.clone()),
            Value::from(column.bytes),
            Value::String(format!("{:.1}%", column.share * 100.0)),
            match column.distinct {
                Some(distinct) => Value::from(distinct),
                None => Value::Null,
            },
            match column.value_bytes {
                Some(bytes) => Value::from(bytes),
                None => Value::Null,
            },
            match column.structure_bytes {
                Some(bytes) => Value::from(bytes),
                None => Value::Null,
            },
        ]);
    }
    write_aligned(out, &columns)?;

    if advice.findings.is_empty() {
        writeln!(out, "\nnothing to complain about")?;
        return Ok(());
    }
    writeln!(out)?;
    for finding in &advice.findings {
        let column = match &finding.column {
            Some(column) => format!("{column}: "),
            None => String::new(),
        };
        writeln!(
            out,
            "{:>7}  {:<20} {}{}",
            finding.severity, finding.rule, column, finding.message
        )?;
    }
    Ok(())
}

/// `--json` wins over the format, so that every command has one JSON form.
fn format_for(json: bool, format: Format) -> Format {
    if json && format == Format::Table {
        Format::Json
    } else {
        format
    }
}

/// Print what one lookup reads: the footer, plus one row group.
fn print_lookup_cost(out: &mut impl Write, facts: &Value) -> Result<()> {
    let groups: Vec<i64> = facts["row_group_bytes"]
        .as_array()
        .map(|values| values.iter().filter_map(|value| value.as_i64()).collect())
        .unwrap_or_default();
    let typical = groups.iter().copied().sum::<i64>() / groups.len().max(1) as i64;
    let largest = groups.iter().copied().max().unwrap_or(0);

    writeln!(out)?;
    writeln!(out, "what one lookup reads:")?;
    writeln!(
        out,
        "  the footer      {} bytes (every reader pays this first)",
        facts["footer_bytes"]
    )?;
    writeln!(
        out,
        "  one row group   {typical} bytes (average), {largest} bytes (largest)"
    )?;
    writeln!(
        out,
        "  ⇒ typical       {} bytes, worst {} bytes",
        facts["lookup_reads_typical"], facts["lookup_reads_worst"]
    )?;
    let rows = &facts["rows_per_group"];
    writeln!(
        out,
        "  rows per group  {} (average), {} to {} ({})",
        rows["average"],
        rows["min"],
        rows["max"],
        if rows["even"] == true {
            "even"
        } else {
            "not even"
        }
    )?;
    Ok(())
}

/// Print the row groups, with their sizes.
fn print_row_groups(out: &mut impl Write, facts: &Value) -> Result<()> {
    let rows: Vec<i64> = facts["row_group_rows"]
        .as_array()
        .map(|values| values.iter().filter_map(|value| value.as_i64()).collect())
        .unwrap_or_default();
    let bytes: Vec<i64> = facts["row_group_bytes"]
        .as_array()
        .map(|values| values.iter().filter_map(|value| value.as_i64()).collect())
        .unwrap_or_default();
    if rows.is_empty() {
        return Ok(());
    }
    let mut table = Table::new(vec!["row_group".into(), "rows".into(), "bytes".into()]);
    for (index, rows) in rows.iter().enumerate() {
        table.push(vec![
            Value::from(index),
            Value::from(*rows),
            Value::from(bytes.get(index).copied().unwrap_or(0)),
        ]);
    }
    writeln!(out)?;
    write_aligned(out, &table)?;
    if rows.len() > 50 {
        writeln!(out, "… {} more row groups", rows.len() - 50)?;
    }
    Ok(())
}

/// Print the file's facts as `key: value` lines.
fn print_facts(out: &mut impl Write, facts: &Value) -> Result<()> {
    let mut pairs: Vec<(String, Value)> = Vec::new();
    for key in [
        "file",
        "size_bytes",
        "rows",
        "row_groups",
        "columns",
        "footer_bytes",
        "metadata_bytes",
        "format_version",
        "created_by",
        "bytes_per_row",
    ] {
        if let Some(value) = facts.get(key) {
            pairs.push((key.to_string(), value.clone()));
        }
    }
    for key in ["compressions", "encodings"] {
        if let Some(value) = facts.get(key) {
            let list: Vec<String> = value
                .as_array()
                .map(|items| {
                    items
                        .iter()
                        .map(|item| item.as_str().unwrap_or_default().to_string())
                        .collect()
                })
                .unwrap_or_default();
            pairs.push((key.to_string(), Value::String(list.join(", "))));
        }
    }
    let width = pairs.iter().map(|(key, _)| key.len()).max().unwrap_or(0);
    for (key, value) in pairs {
        let text = match value {
            Value::String(s) => s,
            other => other.to_string(),
        };
        writeln!(out, "{key:<width$}  {text}")?;
    }
    Ok(())
}