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};
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())
}
#[derive(Clone, Debug)]
pub struct FileFacts {
pub path: String,
pub size_bytes: u64,
pub rows: i64,
pub row_groups: usize,
pub columns: usize,
pub row_group_rows: Vec<i64>,
pub column_bytes: i64,
pub footer_bytes: i64,
pub metadata_bytes: i64,
pub row_group_bytes: Vec<i64>,
pub lookup_reads_typical: i64,
pub lookup_reads_worst: i64,
pub created_by: Option<String>,
pub format_version: i32,
pub compressions: Vec<String>,
pub encodings: Vec<String>,
pub key_value_metadata: Vec<Value>,
}
#[derive(Clone, Debug)]
pub struct ColumnFacts {
pub name: String,
pub data_type: String,
pub physical_type: String,
pub logical_type: String,
pub compression: String,
pub encodings: Vec<String>,
pub num_values: i64,
pub null_count: u64,
pub min: Option<Value>,
pub max: Option<Value>,
pub compressed_size: i64,
pub uncompressed_size: i64,
pub distinct_count: Option<u64>,
pub row_groups: Vec<GroupStat>,
}
#[derive(Clone, Debug)]
pub struct GroupStat {
pub index: usize,
pub rows: i64,
pub min: Option<Value>,
pub max: Option<Value>,
}
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,
}))
}
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,
})
}
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)
}
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,
}))
}
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)
}
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
};
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());
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)
}
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));
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,
}))
}
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)
}
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>,
}
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)
}
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 })
}
}
}
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 })
}
}
}
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())),
),
}
}
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()),
}
}