|
| 1 | +use crate::errors::DatabaseError; |
| 2 | +use crate::execution::dql::sort::{BumpVec, NullableVec, RemappingIterator}; |
| 3 | +use crate::execution::{build_read, Executor, ReadExecutor}; |
| 4 | +use crate::planner::operator::sort::SortField; |
| 5 | +use crate::planner::operator::top_k::TopKOperator; |
| 6 | +use crate::planner::LogicalPlan; |
| 7 | +use crate::storage::table_codec::BumpBytes; |
| 8 | +use crate::storage::{StatisticsMetaCache, TableCache, Transaction, ViewCache}; |
| 9 | +use crate::throw; |
| 10 | +use crate::types::tuple::{Schema, Tuple}; |
| 11 | +use bumpalo::Bump; |
| 12 | +use std::cmp::Reverse; |
| 13 | +use std::collections::BinaryHeap; |
| 14 | +use std::ops::Coroutine; |
| 15 | +use std::ops::CoroutineState; |
| 16 | +use std::pin::Pin; |
| 17 | + |
| 18 | +fn top_sort<'a>( |
| 19 | + arena: &'a Bump, |
| 20 | + schema: &Schema, |
| 21 | + sort_fields: &[SortField], |
| 22 | + tuples: NullableVec<'a, (usize, Tuple)>, |
| 23 | + limit: Option<usize>, |
| 24 | + offset: Option<usize>, |
| 25 | +) -> Result<Box<dyn Iterator<Item = Tuple> + 'a>, DatabaseError> { |
| 26 | + let mut sort_keys = BumpVec::with_capacity_in(tuples.len(), arena); |
| 27 | + for (i, tuple) in tuples.0.iter().enumerate() { |
| 28 | + let mut full_key = BumpVec::new_in(arena); |
| 29 | + for SortField { |
| 30 | + expr, |
| 31 | + nulls_first, |
| 32 | + asc, |
| 33 | + } in sort_fields |
| 34 | + { |
| 35 | + let mut key = BumpBytes::new_in(arena); |
| 36 | + let tuple = tuple.as_ref().map(|(_, tuple)| tuple).unwrap(); |
| 37 | + expr.eval(Some((tuple, &**schema)))? |
| 38 | + .memcomparable_encode(&mut key)?; |
| 39 | + if *asc { |
| 40 | + for byte in key.iter_mut() { |
| 41 | + *byte ^= 0xFF; |
| 42 | + } |
| 43 | + } |
| 44 | + key.push(if *nulls_first { u8::MIN } else { u8::MAX }); |
| 45 | + full_key.extend(key); |
| 46 | + } |
| 47 | + //full_key.extend_from_slice(&(i as u64).to_be_bytes()); |
| 48 | + sort_keys.push((i, full_key)) |
| 49 | + } |
| 50 | + |
| 51 | + let keep_count = offset.unwrap_or(0) + limit.unwrap_or(sort_keys.len()); |
| 52 | + |
| 53 | + let mut heap: BinaryHeap<Reverse<(&[u8], usize)>> = BinaryHeap::with_capacity(keep_count); |
| 54 | + for (i, key) in sort_keys.iter() { |
| 55 | + let key = key.as_slice(); |
| 56 | + if heap.len() < keep_count { |
| 57 | + heap.push(Reverse((key, *i))); |
| 58 | + } else if let Some(&Reverse((min_key, _))) = heap.peek() { |
| 59 | + if key > min_key { |
| 60 | + heap.pop(); |
| 61 | + heap.push(Reverse((key, *i))); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + let mut topk: Vec<(Vec<u8>, usize)> = heap |
| 67 | + .into_iter() |
| 68 | + .map(|Reverse((key, i))| (key.to_vec(), i)) |
| 69 | + .collect(); |
| 70 | + topk.sort_by(|(k1, i1), (k2, i2)| k1.cmp(k2).then_with(|| i1.cmp(i2).reverse())); |
| 71 | + topk.reverse(); |
| 72 | + |
| 73 | + let mut bumped_indices = |
| 74 | + BumpVec::with_capacity_in(topk.len().saturating_sub(offset.unwrap_or(0)), arena); |
| 75 | + for (_, idx) in topk.into_iter().skip(offset.unwrap_or(0)) { |
| 76 | + bumped_indices.push(idx); |
| 77 | + } |
| 78 | + Ok(Box::new(RemappingIterator::new(0, tuples, bumped_indices))) |
| 79 | +} |
| 80 | + |
| 81 | +pub struct TopK { |
| 82 | + arena: Bump, |
| 83 | + sort_fields: Vec<SortField>, |
| 84 | + limit: Option<usize>, |
| 85 | + offset: Option<usize>, |
| 86 | + input: LogicalPlan, |
| 87 | +} |
| 88 | + |
| 89 | +impl From<(TopKOperator, LogicalPlan)> for TopK { |
| 90 | + fn from( |
| 91 | + ( |
| 92 | + TopKOperator { |
| 93 | + sort_fields, |
| 94 | + limit, |
| 95 | + offset, |
| 96 | + }, |
| 97 | + input, |
| 98 | + ): (TopKOperator, LogicalPlan), |
| 99 | + ) -> Self { |
| 100 | + TopK { |
| 101 | + arena: Default::default(), |
| 102 | + sort_fields, |
| 103 | + limit, |
| 104 | + offset, |
| 105 | + input, |
| 106 | + } |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +impl<'a, T: Transaction + 'a> ReadExecutor<'a, T> for TopK { |
| 111 | + fn execute( |
| 112 | + self, |
| 113 | + cache: (&'a TableCache, &'a ViewCache, &'a StatisticsMetaCache), |
| 114 | + transaction: *mut T, |
| 115 | + ) -> Executor<'a> { |
| 116 | + Box::new( |
| 117 | + #[coroutine] |
| 118 | + move || { |
| 119 | + let TopK { |
| 120 | + arena, |
| 121 | + sort_fields, |
| 122 | + limit, |
| 123 | + offset, |
| 124 | + mut input, |
| 125 | + } = self; |
| 126 | + |
| 127 | + let arena: *const Bump = &arena; |
| 128 | + |
| 129 | + let mut tuples = NullableVec::new(unsafe { &*arena }); |
| 130 | + let schema = input.output_schema().clone(); |
| 131 | + let mut tuple_offset = 0; |
| 132 | + |
| 133 | + let mut coroutine = build_read(input, cache, transaction); |
| 134 | + |
| 135 | + while let CoroutineState::Yielded(tuple) = Pin::new(&mut coroutine).resume(()) { |
| 136 | + tuples.put((tuple_offset, throw!(tuple))); |
| 137 | + tuple_offset += 1; |
| 138 | + } |
| 139 | + |
| 140 | + for tuple in throw!(top_sort( |
| 141 | + unsafe { &*arena }, |
| 142 | + &schema, |
| 143 | + &sort_fields, |
| 144 | + tuples, |
| 145 | + limit, |
| 146 | + offset |
| 147 | + )) { |
| 148 | + yield Ok(tuple) |
| 149 | + } |
| 150 | + }, |
| 151 | + ) |
| 152 | + } |
| 153 | +} |
0 commit comments