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,
by: &str,
descending: 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 key = batch
.column_by_name(by)
.cloned()
.with_context(|| format!("the file has no column named {by}"))?;
let indices = lexsort_to_indices(
&[SortColumn {
values: key,
options: Some(SortOptions {
descending,
nulls_first: true,
}),
}],
None,
)
.map_err(|error| anyhow::anyhow!("{error}"))?;
let sorted = take_record_batch(&batch, &indices).map_err(|error| anyhow::anyhow!("{error}"))?;
let columns = crate::plan::columns_of(path, &plan, 0)?;
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)
}