1use std::collections::{BTreeMap, BTreeSet, HashSet};
4use std::fs::File;
5use std::path::Path;
6use std::sync::Arc;
7
8use anyhow::{Context, Result};
9use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
10use parquet::data_type::AsBytes;
11use parquet::file::metadata::ParquetMetaData;
12use parquet::file::statistics::Statistics;
13use serde_json::{json, Map, Value};
14
15use crate::value::{data_type_name, field_json};
16
17pub fn open(path: &Path) -> Result<Arc<ParquetMetaData>> {
19 let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
20 let builder = ParquetRecordBatchReaderBuilder::try_new(file)
21 .with_context(|| format!("read the footer of {}", path.display()))?;
22 Ok(builder.metadata().clone())
23}
24
25#[derive(Clone, Debug)]
27pub struct FileFacts {
28 pub path: String,
30 pub size_bytes: u64,
32 pub rows: i64,
34 pub row_groups: usize,
36 pub columns: usize,
38 pub row_group_rows: Vec<i64>,
40 pub column_bytes: i64,
42 pub footer_bytes: i64,
45 pub metadata_bytes: i64,
47 pub row_group_bytes: Vec<i64>,
49 pub lookup_reads_typical: i64,
51 pub lookup_reads_worst: i64,
53 pub created_by: Option<String>,
55 pub format_version: i32,
57 pub compressions: Vec<String>,
59 pub encodings: Vec<String>,
61 pub key_value_metadata: Vec<Value>,
63}
64
65#[derive(Clone, Debug)]
67pub struct ColumnFacts {
68 pub name: String,
70 pub data_type: String,
74 pub physical_type: String,
76 pub logical_type: String,
78 pub compression: String,
80 pub encodings: Vec<String>,
82 pub num_values: i64,
84 pub null_count: u64,
86 pub min: Option<Value>,
88 pub max: Option<Value>,
90 pub compressed_size: i64,
92 pub uncompressed_size: i64,
94 pub distinct_count: Option<u64>,
96 pub row_groups: Vec<GroupStat>,
98}
99
100#[derive(Clone, Debug)]
102pub struct GroupStat {
103 pub index: usize,
105 pub rows: i64,
107 pub min: Option<Value>,
109 pub max: Option<Value>,
111}
112
113pub fn facts(path: &Path) -> Result<Value> {
115 let file = file_facts(path)?;
116 Ok(json!({
117 "file": file.path,
118 "size_bytes": file.size_bytes,
119 "rows": file.rows,
120 "row_groups": file.row_groups,
121 "columns": file.columns,
122 "format_version": file.format_version,
123 "created_by": file.created_by,
124 "bytes_per_row": if file.rows > 0 {
125 file.size_bytes as f64 / file.rows as f64
126 } else {
127 0.0
128 },
129 "column_bytes": file.column_bytes,
130 "footer_bytes": file.footer_bytes,
131 "metadata_bytes": file.metadata_bytes,
132 "row_group_bytes": file.row_group_bytes,
133 "lookup_reads_typical": file.lookup_reads_typical,
134 "lookup_reads_worst": file.lookup_reads_worst,
135 "rows_per_group": {
136 "min": file.row_group_rows.iter().copied().min().unwrap_or(0),
137 "max": file.row_group_rows.iter().copied().max().unwrap_or(0),
138 "average": if file.row_group_rows.is_empty() {
139 0
140 } else {
141 file.rows / file.row_groups as i64
142 },
143 "even": file
144 .row_group_rows
145 .iter()
146 .all(|rows| *rows == file.row_group_rows[0]),
147 },
148 "compressions": file.compressions,
149 "encodings": file.encodings,
150 "key_value_metadata": file.key_value_metadata,
151 "row_group_rows": file.row_group_rows,
152 }))
153}
154
155pub fn file_facts(path: &Path) -> Result<FileFacts> {
157 let metadata = open(path)?;
158 let file = metadata.file_metadata();
159 let size_bytes = std::fs::metadata(path)?.len();
160 let rows = file.num_rows();
161
162 let mut compressions = BTreeSet::new();
163 let mut encodings = BTreeSet::new();
164 let mut column_bytes = 0i64;
165 let mut row_group_bytes = Vec::new();
166 for group in metadata.row_groups() {
167 let mut group_bytes = 0i64;
168 for chunk in group.columns() {
169 compressions.insert(format!("{}", chunk.compression_codec()));
170 encodings.extend(chunk.encodings().map(|encoding| format!("{encoding}")));
171 group_bytes += chunk.compressed_size();
172 }
173 column_bytes += group_bytes;
174 row_group_bytes.push(group_bytes);
175 }
176
177 let key_value_metadata: Vec<Value> = file
178 .key_value_metadata()
179 .map(|entries| {
180 entries
181 .iter()
182 .map(|entry| {
183 json!({
184 "key": entry.key,
185 "value": entry.value,
186 })
187 })
188 .collect()
189 })
190 .unwrap_or_default();
191
192 let footer_bytes = size_bytes as i64 - column_bytes;
193 let metadata_bytes = metadata_size(path).unwrap_or(footer_bytes);
194 let typical_group = if row_group_bytes.is_empty() {
195 0
196 } else {
197 row_group_bytes.iter().sum::<i64>() / row_group_bytes.len() as i64
198 };
199 let largest_group = row_group_bytes.iter().copied().max().unwrap_or(0);
200
201 Ok(FileFacts {
202 path: path.display().to_string(),
203 size_bytes,
204 rows,
205 row_groups: metadata.row_groups().len(),
206 columns: metadata.file_metadata().schema_descr().num_columns(),
207 row_group_rows: metadata
208 .row_groups()
209 .iter()
210 .map(|group| group.num_rows())
211 .collect(),
212 column_bytes,
213 footer_bytes,
214 metadata_bytes,
215 row_group_bytes,
216 lookup_reads_typical: footer_bytes + typical_group,
217 lookup_reads_worst: footer_bytes + largest_group,
218 created_by: file.created_by().map(|text| text.to_string()),
219 format_version: file.version(),
220 compressions: compressions.into_iter().collect(),
221 encodings: encodings.into_iter().collect(),
222 key_value_metadata,
223 })
224}
225
226fn metadata_size(path: &Path) -> Option<i64> {
231 use std::io::{Read, Seek, SeekFrom};
232 let mut file = File::open(path).ok()?;
233 let size = file.metadata().ok()?.len();
234 if size < 8 {
235 return None;
236 }
237 file.seek(SeekFrom::Start(size - 8)).ok()?;
238 let mut tail = [0u8; 8];
239 file.read_exact(&mut tail).ok()?;
240 if &tail[4..8] != b"PAR1" {
241 return None;
242 }
243 let length = u32::from_le_bytes([tail[0], tail[1], tail[2], tail[3]]) as i64;
244 Some(length + 8)
245}
246
247pub fn schema(path: &Path) -> Result<Value> {
249 let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
250 let builder = ParquetRecordBatchReaderBuilder::try_new(file)
251 .with_context(|| format!("read the footer of {}", path.display()))?;
252 let arrow_schema = builder.schema().clone();
253 let fields: Vec<Value> = arrow_schema
254 .fields()
255 .iter()
256 .map(|field| field_json(field.as_ref()))
257 .collect();
258 Ok(json!({
259 "file": path.display().to_string(),
260 "fields": fields,
261 }))
262}
263
264pub fn schema_lines(path: &Path) -> Result<Vec<(String, String, bool)>> {
266 let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
267 let builder = ParquetRecordBatchReaderBuilder::try_new(file)
268 .with_context(|| format!("read the footer of {}", path.display()))?;
269 let arrow_schema = builder.schema().clone();
270 let mut lines = Vec::new();
271 for field in arrow_schema.fields().iter() {
272 lines.push((
273 field.name().clone(),
274 data_type_name(field.data_type()),
275 field.is_nullable(),
276 ));
277 }
278 Ok(lines)
279}
280
281pub fn column_facts(path: &Path, scan: bool) -> Result<Vec<ColumnFacts>> {
285 let metadata = open(path)?;
286 let arrow_types = arrow_leaf_types(path)?;
287
288 let distinct_counts: Option<Vec<HashSet<String>>> = if scan {
289 Some(scan_distinct(path)?)
290 } else {
291 None
292 };
293
294 let leaf_names: Vec<String> = metadata
297 .file_metadata()
298 .schema_descr()
299 .columns()
300 .iter()
301 .map(|column| column.path().string())
302 .collect();
303
304 let mut per_column: BTreeMap<usize, ColumnStats> = BTreeMap::new();
305 for (group_index, group) in metadata.row_groups().iter().enumerate() {
306 for (position, chunk) in group.columns().iter().enumerate() {
307 let stats = per_column.entry(position).or_insert_with(|| ColumnStats {
308 path: chunk.column_path().string(),
309 physical_type: format!("{}", chunk.column_type()),
310 logical_type: chunk
311 .column_descr()
312 .logical_type_ref()
313 .map(|logical| format!("{logical:?}"))
314 .unwrap_or_else(|| "-".into()),
315 compression: format!("{}", chunk.compression_codec()),
316 encodings: BTreeSet::new(),
317 num_values: 0,
318 null_count: 0,
319 min: None,
320 max: None,
321 compressed_size: 0,
322 uncompressed_size: 0,
323 row_groups: Vec::new(),
324 });
325 stats
326 .encodings
327 .extend(chunk.encodings().map(|encoding| format!("{encoding}")));
328 stats.num_values += chunk.num_values();
329 stats.compressed_size += chunk.compressed_size();
330 stats.uncompressed_size += chunk.uncompressed_size();
331 let mut group_min = Value::Null;
332 let mut group_max = Value::Null;
333 if let Some(statistics) = chunk.statistics() {
334 stats.null_count += statistics.null_count_opt().unwrap_or(0);
335 let (min, max) = bounds(statistics);
336 group_min = min.clone().unwrap_or(Value::Null);
337 group_max = max.clone().unwrap_or(Value::Null);
338 stats.min = merge_min(stats.min.take(), min);
339 stats.max = merge_max(stats.max.take(), max);
340 }
341 stats.row_groups.push(GroupStat {
342 index: group_index,
343 rows: group.num_rows(),
344 min: if group_min.is_null() {
345 None
346 } else {
347 Some(group_min)
348 },
349 max: if group_max.is_null() {
350 None
351 } else {
352 Some(group_max)
353 },
354 });
355 }
356 }
357
358 let mut facts = Vec::new();
359 for (position, stats) in per_column.iter() {
360 let name = leaf_names
361 .get(*position)
362 .cloned()
363 .unwrap_or_else(|| stats.path.clone());
364 let data_type = arrow_types
368 .get(&stats.path)
369 .cloned()
370 .or_else(|| {
371 if stats.logical_type != "-" {
372 Some(stats.logical_type.clone())
373 } else {
374 None
375 }
376 })
377 .unwrap_or_else(|| stats.physical_type.clone());
378 facts.push(ColumnFacts {
379 name,
380 data_type,
381 physical_type: stats.physical_type.clone(),
382 logical_type: stats.logical_type.clone(),
383 compression: stats.compression.clone(),
384 encodings: stats.encodings.iter().cloned().collect(),
385 num_values: stats.num_values,
386 null_count: stats.null_count,
387 min: stats.min.clone(),
388 max: stats.max.clone(),
389 compressed_size: stats.compressed_size,
390 uncompressed_size: stats.uncompressed_size,
391 distinct_count: distinct_counts
392 .as_ref()
393 .and_then(|sets| sets.get(*position))
394 .map(|set| set.len() as u64),
395 row_groups: stats.row_groups.clone(),
396 });
397 }
398 Ok(facts)
399}
400
401pub fn columns(path: &Path, scan: bool) -> Result<Value> {
403 let file = file_facts(path)?;
404 let facts = column_facts(path, scan)?;
405
406 let mut out = Vec::new();
407 for column in facts {
408 let mut object = Map::new();
409 object.insert("name".into(), Value::String(column.name.clone()));
410 object.insert("type".into(), Value::String(column.data_type.clone()));
411 object.insert(
412 "physical_type".into(),
413 Value::String(column.physical_type.clone()),
414 );
415 object.insert(
416 "logical_type".into(),
417 Value::String(column.logical_type.clone()),
418 );
419 object.insert(
420 "compression".into(),
421 Value::String(column.compression.clone()),
422 );
423 object.insert(
424 "encodings".into(),
425 Value::Array(
426 column
427 .encodings
428 .iter()
429 .map(|encoding| Value::String(encoding.clone()))
430 .collect(),
431 ),
432 );
433 object.insert("num_values".into(), json!(column.num_values));
434 object.insert("null_count".into(), json!(column.null_count));
435 object.insert("min".into(), column.min.clone().unwrap_or(Value::Null));
436 object.insert("max".into(), column.max.clone().unwrap_or(Value::Null));
437 object.insert("compressed_size".into(), json!(column.compressed_size));
438 object.insert("bytes".into(), json!(column.compressed_size));
440 object.insert("uncompressed_size".into(), json!(column.uncompressed_size));
441 object.insert(
442 "share".into(),
443 json!(if file.size_bytes > 0 {
444 column.compressed_size as f64 / file.size_bytes as f64
445 } else {
446 0.0
447 }),
448 );
449 object.insert(
450 "ratio".into(),
451 json!(if column.uncompressed_size > 0 {
452 column.compressed_size as f64 / column.uncompressed_size as f64
453 } else {
454 0.0
455 }),
456 );
457 object.insert(
458 "bytes_per_value".into(),
459 json!(if column.num_values > 0 {
460 column.compressed_size as f64 / column.num_values as f64
461 } else {
462 0.0
463 }),
464 );
465 if let Some(distinct) = column.distinct_count {
466 object.insert("distinct_count".into(), json!(distinct));
467 }
468 let row_groups: Vec<Value> = column
469 .row_groups
470 .iter()
471 .map(|group| {
472 json!({
473 "index": group.index,
474 "rows": group.rows,
475 "min": group.min.clone().unwrap_or(Value::Null),
476 "max": group.max.clone().unwrap_or(Value::Null),
477 })
478 })
479 .collect();
480 object.insert("row_groups".into(), Value::Array(row_groups));
481 out.push(Value::Object(object));
482 }
483
484 Ok(json!({
485 "file": path.display().to_string(),
486 "size_bytes": file.size_bytes,
487 "column_bytes": file.column_bytes,
488 "footer_bytes": file.footer_bytes,
489 "metadata_bytes": file.metadata_bytes,
490 "row_group_bytes": file.row_group_bytes,
491 "lookup_reads_typical": file.lookup_reads_typical,
492 "lookup_reads_worst": file.lookup_reads_worst,
493 "rows_per_group": {
494 "min": file.row_group_rows.iter().copied().min().unwrap_or(0),
495 "max": file.row_group_rows.iter().copied().max().unwrap_or(0),
496 "average": if file.row_group_rows.is_empty() {
497 0
498 } else {
499 file.rows / file.row_groups as i64
500 },
501 "even": file
502 .row_group_rows
503 .iter()
504 .all(|rows| *rows == file.row_group_rows[0]),
505 },
506 "columns": out,
507 }))
508}
509
510fn arrow_leaf_types(path: &Path) -> Result<BTreeMap<String, String>> {
516 let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
517 let builder = ParquetRecordBatchReaderBuilder::try_new(file)
518 .with_context(|| format!("read the footer of {}", path.display()))?;
519 let arrow_schema = builder.schema().clone();
520
521 let mut types = BTreeMap::new();
522 for field in arrow_schema.fields().iter() {
523 collect_leaves(field, "", &mut types);
524 }
525 Ok(types)
526}
527
528fn collect_leaves(field: &arrow_schema::Field, prefix: &str, types: &mut BTreeMap<String, String>) {
530 let path = if prefix.is_empty() {
531 field.name().clone()
532 } else {
533 format!("{prefix}.{}", field.name())
534 };
535 match field.data_type() {
536 arrow_schema::DataType::Struct(fields) => {
537 for inner in fields.iter() {
538 collect_leaves(inner, &path, types);
539 }
540 }
541 arrow_schema::DataType::List(inner)
542 | arrow_schema::DataType::LargeList(inner)
543 | arrow_schema::DataType::FixedSizeList(inner, _)
544 | arrow_schema::DataType::Map(inner, _) => collect_leaves(inner, &path, types),
545 other => {
546 types.insert(path, data_type_name(other));
547 }
548 }
549}
550
551struct ColumnStats {
552 path: String,
553 physical_type: String,
554 logical_type: String,
555 compression: String,
556 encodings: BTreeSet<String>,
557 num_values: i64,
558 null_count: u64,
559 min: Option<Value>,
560 max: Option<Value>,
561 compressed_size: i64,
562 uncompressed_size: i64,
563 row_groups: Vec<GroupStat>,
564}
565
566pub fn scan_distinct(path: &Path) -> Result<Vec<HashSet<String>>> {
568 let file = File::open(path)?;
569 let reader = ParquetRecordBatchReaderBuilder::try_new(file)?
570 .with_batch_size(8192)
571 .build()?;
572 let mut sets: Vec<HashSet<String>> = Vec::new();
573 for batch in reader {
574 let batch = batch?;
575 if sets.is_empty() {
576 sets = (0..batch.num_columns()).map(|_| HashSet::new()).collect();
577 }
578 for (index, column) in batch.columns().iter().enumerate() {
579 let set = &mut sets[index];
580 for row in 0..batch.num_rows() {
581 let value = crate::value::cell(column, row);
582 set.insert(value.to_string());
583 }
584 }
585 }
586 Ok(sets)
587}
588
589fn merge_min(left: Option<Value>, right: Option<Value>) -> Option<Value> {
591 match (left, right) {
592 (None, other) | (other, None) => other,
593 (Some(a), Some(b)) => {
594 let take_a = match (&a, &b) {
595 (Value::Number(x), Value::Number(y)) => {
596 x.as_f64().unwrap_or(f64::MAX) <= y.as_f64().unwrap_or(f64::MAX)
597 }
598 _ => {
599 let (a, b) = (a.to_string(), b.to_string());
600 a <= b
601 }
602 };
603 Some(if take_a { a } else { b })
604 }
605 }
606}
607
608fn merge_max(left: Option<Value>, right: Option<Value>) -> Option<Value> {
610 match (left, right) {
611 (None, other) | (other, None) => other,
612 (Some(a), Some(b)) => {
613 let take_a = match (&a, &b) {
614 (Value::Number(x), Value::Number(y)) => {
615 x.as_f64().unwrap_or(f64::MIN) >= y.as_f64().unwrap_or(f64::MIN)
616 }
617 _ => {
618 let (a, b) = (a.to_string(), b.to_string());
619 a >= b
620 }
621 };
622 Some(if take_a { a } else { b })
623 }
624 }
625}
626
627fn bounds(statistics: &Statistics) -> (Option<Value>, Option<Value>) {
629 match statistics {
630 Statistics::Boolean(values) => (
631 values.min_opt().map(|v| Value::Bool(*v)),
632 values.max_opt().map(|v| Value::Bool(*v)),
633 ),
634 Statistics::Int32(values) => (
635 values.min_opt().map(|v| json!(v)),
636 values.max_opt().map(|v| json!(v)),
637 ),
638 Statistics::Int64(values) => (
639 values.min_opt().map(|v| json!(v)),
640 values.max_opt().map(|v| json!(v)),
641 ),
642 Statistics::Int96(values) => (
643 values.min_opt().map(|v| json!(v.to_string())),
644 values.max_opt().map(|v| json!(v.to_string())),
645 ),
646 Statistics::Float(values) => (
647 values.min_opt().map(|v| json!(v)),
648 values.max_opt().map(|v| json!(v)),
649 ),
650 Statistics::Double(values) => (
651 values.min_opt().map(|v| json!(v)),
652 values.max_opt().map(|v| json!(v)),
653 ),
654 Statistics::ByteArray(values) => (
655 values.min_opt().map(|v| bytes_value(v.as_bytes())),
656 values.max_opt().map(|v| bytes_value(v.as_bytes())),
657 ),
658 Statistics::FixedLenByteArray(values) => (
659 values.min_opt().map(|v| bytes_value(v.as_bytes())),
660 values.max_opt().map(|v| bytes_value(v.as_bytes())),
661 ),
662 }
663}
664
665fn bytes_value(bytes: &[u8]) -> Value {
667 match std::str::from_utf8(bytes) {
668 Ok(text) => Value::String(text.to_string()),
669 Err(_) => Value::String(bytes.iter().map(|b| format!("{b:02x}")).collect()),
670 }
671}