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::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 {
#[arg(long, global = true)]
json: bool,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand, Debug)]
enum Command {
Info {
file: PathBuf,
},
Schema {
file: PathBuf,
},
Columns {
file: PathBuf,
#[arg(long)]
scan: bool,
},
Head {
file: PathBuf,
#[arg(short = 'n', long, default_value_t = 10)]
rows: usize,
#[arg(long, value_enum, default_value_t = Format::Table)]
format: Format,
},
Cat {
files: Vec<PathBuf>,
#[arg(long, value_enum, default_value_t = Format::Table)]
format: Format,
},
Advise {
file: PathBuf,
#[arg(long)]
scan: bool,
#[arg(long, value_name = "N")]
contrast: Option<usize>,
},
Validate {
file: PathBuf,
},
To {
file: PathBuf,
#[arg(long)]
out: PathBuf,
#[arg(long, value_enum, default_value_t = ConvertFormat::Csv)]
format: ConvertFormat,
},
}
fn main() -> Result<()> {
let cli = Cli::parse();
let mut out = std::io::stdout().lock();
match cli.command {
Command::Info { file } => {
let facts = meta::facts(&file)?;
if cli.json {
writeln!(out, "{}", serde_json::to_string_pretty(&facts)?)?;
} else {
print_facts(&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::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,
} => {
rows::convert(&file, &target, format)?;
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(())
}
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(())
}
fn format_for(json: bool, format: Format) -> Format {
if json && format == Format::Table {
Format::Json
} else {
format
}
}
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",
"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(())
}