1use std::fs::File;
11use std::path::Path;
12
13use anyhow::{Context, Result};
14use arrow_array::RecordBatch;
15use arrow_ord::sort::{lexsort_to_indices, SortColumn, SortOptions};
16use arrow_select::concat::concat_batches;
17use arrow_select::take::take_record_batch;
18use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
19use parquet::arrow::arrow_writer::ArrowWriter;
20
21use crate::plan::Plan;
22
23pub fn sort_file(path: &Path, keys: &[(String, bool)], out: &Path, wanted: &Plan) -> Result<u64> {
27 let facts = crate::meta::file_facts(path)?;
29 let mut plan = crate::bench::baseline(&facts);
30 plan.merge(wanted);
31
32 let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
33 let builder = ParquetRecordBatchReaderBuilder::try_new(file)
34 .with_context(|| format!("read the footer of {}", path.display()))?;
35 let schema = builder.schema().clone();
36
37 let mut batches: Vec<RecordBatch> = Vec::new();
38 for batch in builder.build()? {
39 batches.push(batch?);
40 }
41 let batch = concat_batches(&schema, &batches)?;
42
43 let mut columns = Vec::new();
45 for (name, descending) in keys {
46 let values = batch
47 .column_by_name(name)
48 .cloned()
49 .with_context(|| format!("the file has no column named {name}"))?;
50 columns.push(SortColumn {
51 values,
52 options: Some(SortOptions {
53 descending: *descending,
54 nulls_first: true,
55 }),
56 });
57 }
58 if columns.is_empty() {
59 anyhow::bail!("say what to sort by");
60 }
61
62 let indices = lexsort_to_indices(&columns, None).map_err(|error| anyhow::anyhow!("{error}"))?;
63 let sorted = take_record_batch(&batch, &indices).map_err(|error| anyhow::anyhow!("{error}"))?;
64
65 let distinct = crate::plan::distinct_of_batch(&sorted);
67 let columns: Vec<crate::plan::Column> = sorted
68 .schema()
69 .fields()
70 .iter()
71 .enumerate()
72 .map(|(index, field)| crate::plan::Column {
73 name: field.name().clone(),
74 distinct: distinct.get(index).map(|count| *count as u64),
75 rows: sorted.num_rows() as i64,
76 })
77 .collect();
78 let properties = plan.writer_properties(&columns)?;
79
80 let output = File::create(out).with_context(|| format!("create {}", out.display()))?;
81 let mut writer =
82 ArrowWriter::try_new(output, schema, Some(properties)).context("open the writer")?;
83 writer.write(&sorted)?;
84 writer.close()?;
85
86 let size = std::fs::metadata(out)?.len();
87 Ok(size)
88}