Skip to main content

akar_processor/physical/order_aggregate/
orderby.rs

1//! Auto-extracted from physical_operator.rs
2use crate::physical::common::{take_global_rows, value_cmp};
3use crate::physical::order_aggregate::BlockMergeSorter;
4use crate::physical::types::{OperatorResult, PhysicalOperatorExec};
5use akar_common::types::Value;
6use akar_common::vector::DataChunk;
7
8// ==================== ChunkAccessor ====================
9
10/// Provides random-access by global row index across multiple DataChunks.
11/// Eliminates the need to pre-collect all values into Vec<Vec<(Value, bool)>>.
12struct ChunkAccessor<'a> {
13    chunks: &'a [DataChunk],
14    offsets: Vec<usize>,
15    num_fields: usize,
16}
17
18impl<'a> ChunkAccessor<'a> {
19    fn new(chunks: &'a [DataChunk]) -> Self {
20        let mut offsets = Vec::with_capacity(chunks.len());
21        let mut cum = 0usize;
22        for c in chunks {
23            offsets.push(cum);
24            cum += c.size;
25        }
26        let num_fields = chunks.first().map(|c| c.num_fields()).unwrap_or(0);
27        Self {
28            chunks,
29            offsets,
30            num_fields,
31        }
32    }
33
34    fn total_rows(&self) -> usize {
35        self.offsets
36            .last()
37            .map(|&o| o + self.chunks.last().unwrap().size)
38            .unwrap_or(0)
39    }
40
41    fn resolve(&self, global_row: usize) -> (usize, usize) {
42        for (ci, chunk) in self.chunks.iter().enumerate() {
43            let offset = self.offsets[ci];
44            if global_row < offset + chunk.size {
45                return (ci, global_row - offset);
46            }
47        }
48        (self.chunks.len() - 1, 0)
49    }
50
51    fn get_value(&self, col: usize, global_row: usize) -> Value {
52        let (ci, local) = self.resolve(global_row);
53        self.chunks[ci].get_value(col, local).unwrap_or(Value::Null)
54    }
55
56    fn is_null(&self, col: usize, global_row: usize) -> bool {
57        let (ci, local) = self.resolve(global_row);
58        self.chunks[ci].is_null(col, local)
59    }
60}
61
62// ==================== OrderBy ====================
63
64pub struct PhysicalOrderBy {
65    pub sort_keys: Vec<(u32, bool)>,
66}
67
68impl PhysicalOperatorExec for PhysicalOrderBy {
69    fn operator_type(&self) -> &str {
70        "order_by"
71    }
72
73    fn execute(&self, input: Vec<DataChunk>) -> OperatorResult {
74        if input.is_empty() {
75            return Ok(Vec::new());
76        }
77
78        let accessor = ChunkAccessor::new(&input);
79        let total_rows = accessor.total_rows();
80        if total_rows == 0 {
81            return Ok(input);
82        }
83
84        let num_fields = accessor.num_fields;
85        let field_names = input[0].field_names.clone();
86
87        // Use BlockMergeSorter for large data, simple sort for small
88        let block_size = 10000usize;
89        let indices = if total_rows > block_size && !self.sort_keys.is_empty() {
90            let sorter = BlockMergeSorter::new(block_size, self.sort_keys.clone());
91            // Multi-block path still needs collected key values for k-way merge
92            let mut all_values: Vec<Vec<(Value, bool)>> =
93                (0..num_fields).map(|_| Vec::with_capacity(total_rows)).collect();
94            for global_row in 0..total_rows {
95                for col in 0..num_fields {
96                    let val = accessor.get_value(col, global_row);
97                    let is_null = accessor.is_null(col, global_row);
98                    all_values[col].push((val, is_null));
99                }
100            }
101            sorter.sort(&all_values, num_fields)
102        } else {
103            let mut indices: Vec<usize> = (0..total_rows).collect();
104            if !self.sort_keys.is_empty() {
105                indices.sort_by(|a, b| {
106                    for &(col, ascending) in &self.sort_keys {
107                        let col = col as usize;
108                        if col >= num_fields {
109                            continue;
110                        }
111                        let va = accessor.get_value(col, *a);
112                        let vb = accessor.get_value(col, *b);
113                        let cmp = value_cmp(&va, &vb);
114                        if cmp != std::cmp::Ordering::Equal {
115                            return if ascending { cmp } else { cmp.reverse() };
116                        }
117                    }
118                    std::cmp::Ordering::Equal
119                });
120            }
121            indices
122        };
123
124        // Build sorted output chunks (up to 100 rows per chunk). Slice the
125        // source fields via Arrow `take`, preserving complex types (List/Struct).
126        let chunk_size = 100usize;
127        let mut output = Vec::new();
128        for chunk_start in (0..total_rows).step_by(chunk_size) {
129            let chunk_end = (chunk_start + chunk_size).min(total_rows);
130            output.push(take_global_rows(
131                &input,
132                &indices[chunk_start..chunk_end],
133                field_names.clone(),
134            )?);
135        }
136        Ok(output)
137    }
138}