use std::fs::File;
use std::path::Path;
use anyhow::{Context, Result};
use arrow_array::RecordBatch;
use arrow_ord::sort::{lexsort_to_indices, SortColumn, SortOptions};
use arrow_select::concat::concat_batches;
use arrow_select::take::take_record_batch;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::arrow::arrow_writer::ArrowWriter;
use crate::plan::Plan;
pub fn sort_file(path: &Path, keys: &[(String, bool)], out: &Path, wanted: &Plan) -> Result<u64> {
let facts = crate::meta::file_facts(path)?;
let mut plan = crate::bench::baseline(&facts);
plan.merge(wanted);
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 schema = builder.schema().clone();
let mut batches: Vec<RecordBatch> = Vec::new();
for batch in builder.build()? {
batches.push(batch?);
}
let batch = concat_batches(&schema, &batches)?;
let mut columns = Vec::new();
for (name, descending) in keys {
let values = batch
.column_by_name(name)
.cloned()
.with_context(|| format!("the file has no column named {name}"))?;
columns.push(SortColumn {
values,
options: Some(SortOptions {
descending: *descending,
nulls_first: true,
}),
});
}
if columns.is_empty() {
anyhow::bail!("say what to sort by");
}
let indices = lexsort_to_indices(&columns, None).map_err(|error| anyhow::anyhow!("{error}"))?;
let sorted = take_record_batch(&batch, &indices).map_err(|error| anyhow::anyhow!("{error}"))?;
let distinct = crate::plan::distinct_of_batch(&sorted);
let columns: Vec<crate::plan::Column> = sorted
.schema()
.fields()
.iter()
.enumerate()
.map(|(index, field)| crate::plan::Column {
name: field.name().clone(),
distinct: distinct.get(index).map(|count| *count as u64),
rows: sorted.num_rows() as i64,
})
.collect();
let properties = plan.writer_properties(&columns)?;
let output = File::create(out).with_context(|| format!("create {}", out.display()))?;
let mut writer =
ArrowWriter::try_new(output, schema, Some(properties)).context("open the writer")?;
writer.write(&sorted)?;
writer.close()?;
let size = std::fs::metadata(out)?.len();
Ok(size)
}