1use std::cmp::Ordering;
4
5use arrow_array::RecordBatch;
6use arrow_schema::Schema;
7
8use crate::filter::{resolve, Filter, Predicate};
9use crate::sorted::{Entry, SortedRows};
10use crate::table::Slot;
11use crate::value::{compare, prefix, ValueFn};
12use crate::{DataError, RowId, RowRef};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
16#[non_exhaustive]
17pub enum Order {
18 #[default]
20 Ascending,
21 Descending,
23}
24
25#[derive(Debug, Clone, Default, PartialEq)]
27pub struct ViewSpec {
28 sort: Vec<(String, Order)>,
29 filter: Option<Filter>,
30}
31
32impl ViewSpec {
33 pub fn new() -> Self {
35 Self::default()
36 }
37
38 #[must_use]
41 pub fn sort_by(mut self, column: impl Into<String>, order: Order) -> Self {
42 self.sort.push((column.into(), order));
43 self
44 }
45
46 #[must_use]
48 pub fn filter(mut self, filter: Filter) -> Self {
49 self.filter = Some(filter);
50 self
51 }
52}
53
54#[derive(Debug, Clone)]
56pub(crate) struct SortColumn {
57 column: usize,
58 read: ValueFn,
59 descending: bool,
60}
61
62impl SortColumn {
63 pub(crate) fn ascending(column: usize, read: ValueFn) -> Self {
64 Self {
65 column,
66 read,
67 descending: false,
68 }
69 }
70}
71
72#[derive(Debug, Clone)]
74pub(crate) struct ViewState {
75 sort: Vec<SortColumn>,
76 filter: Option<Predicate>,
77 rows: SortedRows,
78 member: Vec<bool>,
80}
81
82#[derive(Debug, Clone, Copy)]
84pub(crate) struct Rows<'a> {
85 pub(crate) batches: &'a [RecordBatch],
86 pub(crate) slots: &'a [Option<Slot>],
87}
88
89impl Rows<'_> {
90 pub(crate) fn at(&self, id: RowId) -> RowRef {
91 match self.slots.get(id as usize) {
92 Some(Some(slot)) => slot.row_ref(),
93 _ => unreachable!("row id {id} is held, but its slot is free"),
96 }
97 }
98}
99
100impl ViewState {
101 pub(crate) fn compile(spec: &ViewSpec, schema: &Schema) -> Result<Self, DataError> {
102 let sort = spec
103 .sort
104 .iter()
105 .map(|(name, order)| {
106 let (column, _, read) = resolve(schema, name)?;
107 Ok(SortColumn {
108 column,
109 read,
110 descending: *order == Order::Descending,
111 })
112 })
113 .collect::<Result<_, DataError>>()?;
114 let filter = spec
115 .filter
116 .as_ref()
117 .map(|f| Predicate::compile(f, schema))
118 .transpose()?;
119 Ok(Self {
120 sort,
121 filter,
122 rows: SortedRows::default(),
123 member: Vec::new(),
124 })
125 }
126
127 pub(crate) fn len(&self) -> usize {
128 self.rows.len()
129 }
130
131 pub(crate) fn get(&self, index: usize) -> Option<RowId> {
132 self.rows.get(index)
133 }
134
135 fn passes(&self, batches: &[RecordBatch], at: RowRef) -> bool {
137 self.filter
138 .as_ref()
139 .is_none_or(|f| f.eval(&batches[at.batch], at.row) == Some(true))
140 }
141
142 pub(crate) fn remove(&mut self, rows: Rows<'_>, id: RowId, at: RowRef) {
144 if !self.member.get(id as usize).copied().unwrap_or(false) {
145 return;
146 }
147 let probe = entry(&self.sort, rows.batches, id, at);
148 let sort = &self.sort;
149 let found = self
150 .rows
151 .remove(id, |other| entry_order(sort, rows, other, probe, at));
152 debug_assert!(found, "a member row is in the sorted rows");
153 self.member[id as usize] = false;
154 }
155
156 pub(crate) fn position(&self, rows: Rows<'_>, id: RowId) -> Option<usize> {
158 if !self.member.get(id as usize).copied().unwrap_or(false) {
159 return None;
160 }
161 let at = rows.at(id);
162 let probe = entry(&self.sort, rows.batches, id, at);
163 let sort = &self.sort;
164 self.rows
165 .position(id, |other| entry_order(sort, rows, other, probe, at))
166 }
167
168 pub(crate) fn insert(&mut self, rows: Rows<'_>, id: RowId, at: RowRef) {
170 if !self.passes(rows.batches, at) {
171 return;
172 }
173 let probe = entry(&self.sort, rows.batches, id, at);
174 let sort = &self.sort;
175 self.rows
176 .insert(probe, |other| entry_order(sort, rows, other, probe, at));
177 if self.member.len() <= id as usize {
178 self.member.resize(id as usize + 1, false);
179 }
180 self.member[id as usize] = true;
181 }
182
183 pub(crate) fn rebuild(&mut self, rows: Rows<'_>) {
185 let mut entries: Vec<Entry> = rows
186 .slots
187 .iter()
188 .enumerate()
189 .filter_map(|(id, slot)| Some((RowId::try_from(id).ok()?, slot.as_ref()?.row_ref())))
190 .filter(|&(_, at)| self.passes(rows.batches, at))
191 .map(|(id, at)| entry(&self.sort, rows.batches, id, at))
192 .collect();
193 entries.sort_unstable_by(|&a, &b| entry_order(&self.sort, rows, a, b, rows.at(b.id)));
194 self.member.clear();
195 self.member.resize(rows.slots.len(), false);
196 for entry in &entries {
197 self.member[entry.id as usize] = true;
198 }
199 self.rows.rebuild(&entries);
200 }
201}
202
203pub(crate) fn entry(sort: &[SortColumn], batches: &[RecordBatch], id: RowId, at: RowRef) -> Entry {
205 let key = sort.first().map_or(0, |first| {
206 let value = (first.read)(batches[at.batch].column(first.column).as_ref(), at.row);
207 prefix(value, first.descending)
208 });
209 Entry { key, id }
210}
211
212pub(crate) fn entry_order(
215 sort: &[SortColumn],
216 rows: Rows<'_>,
217 other: Entry,
218 probe: Entry,
219 probe_at: RowRef,
220) -> Ordering {
221 other.key.cmp(&probe.key).then_with(|| {
222 row_order(
223 sort,
224 rows.batches,
225 (other.id, rows.at(other.id)),
226 (probe.id, probe_at),
227 )
228 })
229}
230
231fn row_order(
234 sort: &[SortColumn],
235 batches: &[RecordBatch],
236 a: (RowId, RowRef),
237 b: (RowId, RowRef),
238) -> Ordering {
239 for key in sort {
240 let read = |at: RowRef| (key.read)(batches[at.batch].column(key.column).as_ref(), at.row);
241 let order = compare(read(a.1), read(b.1), key.descending);
242 if order.is_ne() {
243 return order;
244 }
245 }
246 a.0.cmp(&b.0)
247}