1pub(super) mod jobs;
3mod numeric;
4
5use super::{
6 Comparison, MAX_COMPARISON_KEY, MAX_DISTINCT_VALUES, MAX_STATE_BYTES, MAX_TERMS, Plan, Query,
7 QueryPage, admit_ordered_fields, admit_output, admit_projection, comparison_key,
8 copy_projection, execute, projection_size,
9};
10use crate::{
11 Entity, EntitySchema, Error, FieldType, IndexValue, TypeSchema, Value, ValueSchema,
12 codec::Decoder, key,
13};
14use ic_storage::Memory;
15use std::collections::{BTreeMap, BTreeSet};
16
17const MAX_GROUPS: usize = 32;
18
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub enum GroupOrder {
22 #[default]
24 Key,
25 AggregateAscending,
27 AggregateDescending,
29 KeyDescending,
31}
32
33#[derive(Default)]
34pub(super) struct GroupRequest<'a> {
35 predicates: Vec<(Comparison, IndexValue<'a>, bool)>,
37 order: Option<GroupOrder>,
38 page: Option<jobs::pages::PageRequest<'a>>,
39}
40impl GroupRequest<'_> {
41 pub(super) fn is_empty(&self) -> bool {
42 self.predicates.is_empty() && self.order.is_none() && self.page.is_none()
43 }
44
45 fn admit(&self, entity: &EntitySchema, reducer: &Reducer) -> Result<Selection, Error> {
46 if self
47 .page
48 .is_some_and(|page| !(1..=MAX_GROUPS).contains(&page.size))
49 {
50 return Err(Error::Limit);
51 }
52 let field = match reducer {
53 Reducer::Count { .. } | Reducer::Distinct { .. } => ValueSchema {
54 value: FieldType::Nat64,
55 optional: false,
56 },
57 Reducer::Extremum { position, .. } => {
58 let field = &entity.fields[*position];
59 ValueSchema {
60 value: field.value,
61 optional: field.optional,
62 }
63 }
64 Reducer::Numeric(state) => state.output(),
65 };
66 let absent_result = !matches!(reducer, Reducer::Count { .. } | Reducer::Distinct { .. });
68 let predicates = self
69 .predicates
70 .iter()
71 .map(|&(comparison, value, or_next)| {
72 if match value {
73 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
74 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
75 _ => false,
76 } {
77 return Err(Error::Limit);
78 }
79 comparison.admit(field.value, absent_result, value)?;
80 let key = if value == IndexValue::Absent {
81 None
82 } else {
83 let mut key = Vec::new();
84 value.append_component(field.optional, &mut key);
85 if key.len() > MAX_COMPARISON_KEY {
86 return Err(Error::Limit);
87 }
88 Some(key)
89 };
90 Ok((comparison, key, or_next))
91 })
92 .collect::<Result<_, Error>>()?;
93 Ok(Selection {
94 predicates,
95 order: self.order.unwrap_or_default(),
96 optional: field.optional,
97 })
98 }
99}
100
101struct Selection {
102 predicates: Vec<(Comparison, Option<Vec<u8>>, bool)>,
103 order: GroupOrder,
104 optional: bool,
106}
107
108#[derive(Debug)]
110pub struct Aggregate<T> {
111 pub value: T,
113 pub examined: usize,
115 pub fetched: usize,
117 pub output_bytes: usize,
119}
120
121#[derive(Debug)]
123pub struct GroupCount<K> {
124 pub key: K,
126 pub count: u64,
128}
129
130#[derive(Debug)]
132pub struct GroupValue<K, R> {
133 pub key: K,
135 pub value: Option<R>,
137}
138
139impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
140 #[must_use]
145 pub fn group_page(mut self, size: usize, after: Option<&'a jobs::GroupCursor>) -> Self {
146 self.request.groups.page = Some(jobs::pages::PageRequest { size, after });
147 self
148 }
149
150 #[must_use]
157 pub fn filter_groups(
158 mut self,
159 comparison: Comparison,
160 value: impl Into<IndexValue<'a>>,
161 ) -> Self {
162 if self.request.groups.predicates.len() == MAX_TERMS {
163 self.request.over_limit = true;
164 } else {
165 self.request
166 .groups
167 .predicates
168 .push((comparison, value.into(), false));
169 }
170 self
171 }
172
173 #[must_use]
180 pub fn filter_groups_any(mut self, alternatives: &[(Comparison, IndexValue<'a>)]) -> Self {
181 let count = alternatives.len();
182 if count == 0 || count > MAX_TERMS - self.request.groups.predicates.len() {
183 self.request.over_limit = true;
184 } else {
185 self.request.groups.predicates.extend(
186 alternatives
187 .iter()
188 .enumerate()
189 .map(|(i, &(comparison, value))| (comparison, value, i + 1 != count)),
190 );
191 }
192 self
193 }
194
195 #[must_use]
198 pub fn order_groups(mut self, order: GroupOrder) -> Self {
199 self.request.groups.order = Some(order);
200 self
201 }
202
203 pub fn min<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
216 self.extremum(false)
217 }
218
219 pub fn max<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
226 self.extremum(true)
227 }
228
229 fn extremum<R: Value>(self, maximum: bool) -> Result<Aggregate<Option<R>>, Error> {
230 let (plan, reducer) = self.extremum_plan::<R>(maximum)?;
231 self.scalar_value(&plan, reducer)
232 }
233
234 fn extremum_plan<R: Value>(&self, maximum: bool) -> Result<(Plan<'a>, Reducer), Error> {
235 let plan = self.aggregate_plan(Some(R::definition()), false)?;
236 let reducer = Reducer::extremum(
237 E::SCHEMA,
238 plan.projection.ok_or(Error::InvalidQuery)?,
239 maximum,
240 )?;
241 Ok((plan, reducer))
242 }
243
244 fn scalar_value<R: Value>(
245 self,
246 plan: &Plan<'_>,
247 mut reducer: Reducer,
248 ) -> Result<Aggregate<Option<R>>, Error> {
249 let page = execute(
250 &self.db.map,
251 E::SCHEMA,
252 &self.request,
253 plan,
254 Some(Accumulator::Scalar(&mut reducer)),
255 )?;
256 let mut output_bytes = 0;
257 let value = reducer
258 .finish()?
259 .into_value()?
260 .map(|bytes| {
261 admit_output(bytes.len(), self.request.bytes, &mut output_bytes)?;
262 decode_record(&bytes)
263 })
264 .transpose()?;
265 Ok(Aggregate {
266 value,
267 examined: page.examined,
268 fetched: page.fetched,
269 output_bytes,
270 })
271 }
272
273 pub fn group_min<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
290 self.group_extrema(false)
291 }
292
293 pub fn group_max<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
299 self.group_extrema(true)
300 }
301
302 fn group_extrema<K: Value, R: Value>(
303 self,
304 maximum: bool,
305 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
306 let (plan, initial) = self.group_extremum_plan::<K, R>(maximum)?;
307 self.group_values(&plan, initial)
308 }
309
310 fn group_extremum_plan<K: Value, R: Value>(
311 &self,
312 maximum: bool,
313 ) -> Result<(Plan<'a>, Reducer), Error> {
314 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
315 let operand = admit_projection(E::SCHEMA, R::definition())?;
316 let initial = Reducer::extremum(E::SCHEMA, operand, maximum)?;
317 plan.selected |= operand;
318 Ok((plan, initial))
319 }
320
321 fn group_values<K: Value, R: Value>(
322 self,
323 plan: &Plan<'_>,
324 initial: Reducer,
325 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
326 let (groups, page) = self.grouped(plan, initial)?;
327 let (value, output_bytes) = value_output(groups, self.request.rows, self.request.bytes)?;
328 Ok(Aggregate {
329 value,
330 examined: page.examined,
331 fetched: page.fetched,
332 output_bytes,
333 })
334 }
335
336 pub fn exists(self) -> Result<Aggregate<bool>, Error> {
348 let plan = self.aggregate_plan(None, false)?;
349 let mut found = false;
350 let page = execute(
351 &self.db.map,
352 E::SCHEMA,
353 &self.request,
354 &plan,
355 Some(Accumulator::Exists(&mut found)),
356 )?;
357 Ok(Aggregate {
358 value: found,
359 examined: page.examined,
360 fetched: page.fetched,
361 output_bytes: 1,
362 })
363 }
364
365 pub fn count(self) -> Result<Aggregate<u64>, Error> {
379 if self.request.bytes < 8 {
380 return Err(Error::RowTooLarge);
381 }
382 let mut plan = self.aggregate_plan(None, false)?;
383 if self.request.predicates.is_empty() && self.request.index.is_none() {
384 return Ok(Aggregate {
385 value: self.db.cardinality::<E>()?,
386 examined: 0,
387 fetched: 0,
388 output_bytes: 8,
389 });
390 }
391 if super::range::covers_primary(&plan)
392 || super::order::count_prefix(E::SCHEMA, &self.request, &mut plan)?
393 {
394 return self.count_keys(&plan);
395 }
396 let reducer = self.count_reducer(None)?;
397 self.scalar_count_value(&plan, reducer)
398 }
399
400 pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
405 self.scalar_count(None)
406 }
407
408 pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
419 if self.request.index.is_none() || !self.request.predicates.is_empty() {
420 return Err(Error::InvalidQuery);
421 }
422 if self.request.bytes < 8 {
423 return Err(Error::RowTooLarge);
424 }
425 let plan = self.aggregate_plan(None, false)?;
426 self.count_keys(&plan)
427 }
428
429 fn count_keys(&self, plan: &Plan<'_>) -> Result<Aggregate<u64>, Error> {
430 let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
431 let examined = bounds.map_or(0, |range| {
432 self.db.map.range(range).take(self.request.work).count()
433 });
434 if examined == self.request.work {
435 return Err(Error::Limit);
436 }
437 Ok(Aggregate {
438 value: examined as u64,
439 examined,
440 fetched: 0,
441 output_bytes: 8,
442 })
443 }
444
445 pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
453 self.scalar_count(Some(field))
454 }
455
456 pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
465 if self.request.bytes < 8 {
466 return Err(Error::RowTooLarge);
467 }
468 let (plan, reducer) = self.distinct_plan::<K>()?;
469 self.scalar_count_value(&plan, reducer)
470 }
471
472 fn distinct_plan<K: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
473 let plan = self.aggregate_plan(Some(K::definition()), false)?;
474 let reducer = Reducer::distinct(plan.projection.ok_or(Error::InvalidQuery)?);
475 Ok((plan, reducer))
476 }
477
478 fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
479 if self.request.bytes < 8 {
480 return Err(Error::RowTooLarge);
481 }
482 let plan = self.aggregate_plan(None, false)?;
483 let reducer = self.count_reducer(field)?;
484 self.scalar_count_value(&plan, reducer)
485 }
486
487 fn scalar_count_value(
488 self,
489 plan: &Plan<'_>,
490 mut reducer: Reducer,
491 ) -> Result<Aggregate<u64>, Error> {
492 let page = execute(
493 &self.db.map,
494 E::SCHEMA,
495 &self.request,
496 plan,
497 Some(Accumulator::Scalar(&mut reducer)),
498 )?;
499 Ok(Aggregate {
500 value: reducer.finish()?.into_count()?,
501 examined: page.examined,
502 fetched: page.fetched,
503 output_bytes: 8,
504 })
505 }
506
507 pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
524 self.group_counts(None)
525 }
526
527 pub fn group_count_field<K: Value>(
536 self,
537 field: &str,
538 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
539 self.group_counts(Some(field))
540 }
541
542 pub fn group_count_distinct<K: Value, R: Value>(
555 self,
556 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
557 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
558 self.group_count_values(&plan, reducer)
559 }
560
561 fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
562 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
563 let operand = admit_projection(E::SCHEMA, R::definition())?;
564 admit_ordered_fields(E::SCHEMA, operand)?;
565 plan.selected |= operand;
566 Ok((plan, Reducer::distinct(operand)))
567 }
568
569 fn group_counts<K: Value>(
570 self,
571 field: Option<&str>,
572 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
573 let plan = self.aggregate_plan(Some(K::definition()), true)?;
574 let reducer = self.count_reducer(field)?;
575 self.group_count_values(&plan, reducer)
576 }
577
578 fn group_count_values<K: Value>(
579 self,
580 plan: &Plan<'_>,
581 reducer: Reducer,
582 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
583 let (groups, page) = self.grouped(plan, reducer)?;
584 let (value, output_bytes) = count_output(groups, self.request.rows, self.request.bytes)?;
585 Ok(Aggregate {
586 value,
587 examined: page.examined,
588 fetched: page.fetched,
589 output_bytes,
590 })
591 }
592
593 fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
594 let presence = field
596 .map(|name| {
597 E::SCHEMA
598 .fields
599 .iter()
600 .enumerate()
601 .find(|(_, f)| f.name == name)
602 .map(|(i, f)| f.optional.then_some(i))
603 .ok_or(Error::InvalidQuery)
604 })
605 .transpose()?
606 .flatten();
607 Ok(Reducer::Count { presence, total: 0 })
608 }
609
610 fn grouped(
611 &self,
612 plan: &Plan<'_>,
613 initial: Reducer,
614 ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
615 if self.request.groups.page.is_some() {
616 return Err(Error::InvalidQuery);
617 }
618 let mut groups = self.admit_groups(plan, initial)?;
619 let page = execute(
620 &self.db.map,
621 E::SCHEMA,
622 &self.request,
623 plan,
624 Some(Accumulator::Groups(&mut groups)),
625 )?;
626 Ok((groups, page))
627 }
628
629 fn admit_groups(&self, plan: &Plan<'_>, initial: Reducer) -> Result<Groups, Error> {
630 Ok(Groups {
631 selection: self.request.groups.admit(E::SCHEMA, &initial)?,
632 mask: plan.projection.ok_or(Error::InvalidQuery)?,
633 initial,
634 rows: BTreeMap::new(),
635 state_bytes: 0,
636 })
637 }
638
639 fn aggregate_plan(
640 &self,
641 output: Option<&TypeSchema>,
642 group_output: bool,
643 ) -> Result<Plan<'static>, Error> {
644 if self.request.cursor.is_some()
645 || self.request.distinct
646 || self.request.order.is_some()
647 || self.request.descending
648 {
649 return Err(Error::InvalidQuery);
650 }
651 self.db.schema.admits(E::SCHEMA)?;
652 let mut plan = Plan::admit(
653 E::SCHEMA,
654 &self.request,
655 self.db.schema.fingerprint(),
656 self.db.incarnation,
657 output,
658 group_output,
659 )?;
660 if let Some(mask) = plan.projection {
661 admit_ordered_fields(E::SCHEMA, mask)?;
662 plan.selected |= mask;
663 }
664 Ok(plan)
665 }
666}
667
668fn value_output<K: Value, R: Value>(
669 groups: Groups,
670 rows: usize,
671 bytes: usize,
672) -> Result<(Vec<GroupValue<K, R>>, usize), Error> {
673 let mut output_bytes = 0;
674 let value = groups
675 .into_output()?
676 .into_iter()
677 .take(rows)
678 .map(|(key, reducer)| {
679 admit_output(key.len() + reducer.encoded_len(), bytes, &mut output_bytes)?;
680 decode_group_value(&key, reducer)
681 })
682 .collect::<Result<_, Error>>()?;
683 Ok((value, output_bytes))
684}
685
686fn count_output<K: Value>(
687 groups: Groups,
688 rows: usize,
689 bytes: usize,
690) -> Result<(Vec<GroupCount<K>>, usize), Error> {
691 let mut output_bytes = 0;
692 let value = groups
693 .into_output()?
694 .into_iter()
695 .take(rows)
696 .map(|(key, reducer)| {
697 admit_output(key.len() + 8, bytes, &mut output_bytes)?;
698 decode_group_count(&key, reducer)
699 })
700 .collect::<Result<_, Error>>()?;
701 Ok((value, output_bytes))
702}
703
704fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
705 Ok(GroupCount {
706 key: decode_record(key)?,
707 count: result.into_count()?,
708 })
709}
710
711fn decode_group_value<K: Value, R: Value>(
712 key: &[u8],
713 result: Completed,
714) -> Result<GroupValue<K, R>, Error> {
715 let value = result.into_value()?;
716 Ok(GroupValue {
717 key: decode_record(key)?,
718 value: value.as_deref().map(decode_record).transpose()?,
719 })
720}
721
722fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
723 let mut reader = Decoder::new(bytes)?;
724 let value = R::decode_from(&mut reader)?;
725 reader.finish()?;
726 Ok(value)
727}
728
729pub(super) enum Accumulator<'a> {
731 Exists(&'a mut bool),
733 Scalar(&'a mut Reducer),
734 Groups(&'a mut Groups),
735}
736impl Accumulator<'_> {
737 pub(super) fn needs_spans(&self) -> bool {
738 !matches!(
739 self,
740 Self::Exists(_)
741 | Self::Scalar(
742 Reducer::Numeric(_)
743 | Reducer::Count { presence: None, .. }
744 | Reducer::Distinct { .. }
745 )
746 )
747 }
748
749 pub(super) fn push(
750 &mut self,
751 entity: &EntitySchema,
752 values: &[IndexValue<'_>],
753 bytes: &[u8],
754 spans: &[(u16, u16)],
755 ) -> Result<(), Error> {
756 match self {
757 Self::Exists(found) => {
758 **found = true;
759 Ok(())
760 }
761 Self::Scalar(state) => state.push(entity, values, bytes, spans, MAX_STATE_BYTES),
762 Self::Groups(state) => state.push(entity, values, bytes, spans),
763 }
764 }
765}
766
767#[derive(Clone)]
768pub(super) enum Reducer {
769 Numeric(numeric::NumericAggregate),
770 Distinct {
771 mask: u16,
772 seen: BTreeSet<Vec<u8>>,
773 },
774 Count {
775 presence: Option<usize>,
776 total: u64,
777 },
778 Extremum {
779 position: usize,
780 maximum: bool,
781 selected: Option<(Vec<u8>, Vec<u8>)>,
782 },
783}
784impl Reducer {
785 fn distinct(mask: u16) -> Self {
786 Self::Distinct {
787 mask,
788 seen: BTreeSet::new(),
789 }
790 }
791
792 fn extremum(entity: &EntitySchema, mask: u16, maximum: bool) -> Result<Self, Error> {
793 if mask.count_ones() != 1 {
794 return Err(Error::InvalidQuery);
795 }
796 let position = mask.trailing_zeros() as usize;
797 if !key::supports(entity.fields[position].value) {
798 return Err(Error::InvalidQuery);
799 }
800 Ok(Self::Extremum {
801 position,
802 maximum,
803 selected: None,
804 })
805 }
806
807 fn retained_bytes(&self) -> usize {
808 match self {
809 Self::Numeric(state) => state.retained_bytes(),
810 Self::Count { .. } => 8,
811 Self::Distinct { seen, .. } => 8 + seen.iter().map(Vec::capacity).sum::<usize>(),
812 Self::Extremum { selected, .. } => selected
813 .as_ref()
814 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
815 }
816 }
817
818 fn finish(self) -> Result<Completed, Error> {
819 match self {
820 Self::Count { total, .. } => Ok(Completed::Count(total)),
821 Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
822 Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
823 Self::Numeric(state) => state.finish(),
824 }
825 }
826
827 fn push(
828 &mut self,
829 entity: &EntitySchema,
830 values: &[IndexValue<'_>],
831 bytes: &[u8],
832 spans: &[(u16, u16)],
833 allowance: usize,
834 ) -> Result<(), Error> {
835 match self {
836 Self::Numeric(state) => state.push(values)?,
837 Self::Distinct { mask, seen } => {
838 let key = comparison_key(entity, *mask, values)?;
839 if !seen.contains(&key) {
840 if seen.len() == MAX_DISTINCT_VALUES
841 || 8 + seen.iter().map(Vec::capacity).sum::<usize>() + key.capacity()
842 > allowance
843 {
844 return Err(Error::Limit);
845 }
846 seen.insert(key);
847 }
848 }
849 Self::Count { presence, total } => {
850 *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
851 }
852 Self::Extremum {
853 position,
854 maximum,
855 selected,
856 } => {
857 let value = values[*position];
858 if value == IndexValue::Absent {
859 return Ok(());
860 }
861 let mut key = Vec::new();
862 value.append_component(entity.fields[*position].optional, &mut key);
863 if key.len() > MAX_COMPARISON_KEY {
864 return Err(Error::Limit);
865 }
866 if selected
867 .as_ref()
868 .is_none_or(|(old, _)| if *maximum { key > *old } else { key < *old })
869 {
870 let (start, end) = spans[*position];
871 if key.capacity() + usize::from(end - start) > allowance {
872 return Err(Error::Limit);
873 }
874 let output = bytes[usize::from(start)..usize::from(end)].to_vec();
876 if key.capacity() + output.capacity() > allowance {
877 return Err(Error::Limit);
878 }
879 *selected = Some((key, output));
880 }
881 }
882 }
883 Ok(())
884 }
885}
886
887enum Completed {
889 Count(u64),
890 Value(Option<(Vec<u8>, Vec<u8>)>),
891}
892impl Completed {
893 fn encoded_len(&self) -> usize {
894 match self {
895 Self::Count(_) => 8,
896 Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
897 }
898 }
899 fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
901 match self {
902 Self::Count(total) => {
903 *scratch = total.to_be_bytes();
904 Some(scratch)
905 }
906 Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
907 }
908 }
909
910 fn retained_bytes(&self) -> usize {
911 match self {
912 Self::Count(_) => 8,
913 Self::Value(value) => value
914 .as_ref()
915 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
916 }
917 }
918 fn into_count(self) -> Result<u64, Error> {
919 match self {
920 Self::Count(count) => Ok(count),
921 _ => Err(Error::Corrupt),
922 }
923 }
924 fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
925 match self {
926 Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
927 _ => Err(Error::Corrupt),
928 }
929 }
930}
931
932pub(super) struct Groups {
933 selection: Selection,
934 mask: u16,
935 initial: Reducer,
937 rows: BTreeMap<Vec<u8>, (Vec<u8>, Reducer)>,
938 state_bytes: usize,
939}
940impl Groups {
941 fn into_output(self) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
942 let mut state_bytes = self.state_bytes;
944 let mut rows = self
945 .rows
946 .into_iter()
947 .map(|(key, (record, reducer))| {
948 let previous = reducer.retained_bytes();
949 let result = reducer.finish()?;
950 state_bytes = state_bytes - previous + result.retained_bytes();
951 if state_bytes > MAX_STATE_BYTES {
952 return Err(Error::Limit);
953 }
954 Ok((key, (record, result)))
955 })
956 .collect::<Result<Vec<_>, Error>>()?;
957 rows.retain(|(_, (_, result))| {
958 let mut scratch = [0; 8];
959 let actual = result.result_key(&mut scratch);
960 self.selection
961 .predicates
962 .split_inclusive(|(_, _, or_next)| !or_next)
963 .all(|clause| {
964 clause.iter().any(|(comparison, operand, _)| {
965 comparison.accepts(actual, operand.as_deref(), self.selection.optional)
966 })
967 })
968 });
969 if self.selection.order == GroupOrder::KeyDescending {
970 rows.reverse();
973 } else if self.selection.order != GroupOrder::Key {
974 rows.sort_unstable_by(|(ka, (_, a)), (kb, (_, b))| {
975 let (mut sa, mut sb) = ([0; 8], [0; 8]);
976 let order = a.result_key(&mut sa).cmp(&b.result_key(&mut sb));
977 let order = if self.selection.order == GroupOrder::AggregateDescending {
978 order.reverse()
979 } else {
980 order
981 };
982 order.then_with(|| ka.cmp(kb))
983 });
984 }
985 Ok(rows.into_iter().map(|(_, row)| row).collect())
986 }
987
988 fn push(
989 &mut self,
990 entity: &EntitySchema,
991 values: &[IndexValue<'_>],
992 bytes: &[u8],
993 spans: &[(u16, u16)],
994 ) -> Result<(), Error> {
995 let key = comparison_key(entity, self.mask, values)?;
996 let size = projection_size(spans, self.mask);
997 if let Some((_, reducer)) = self.rows.get_mut(&key) {
998 let previous = reducer.retained_bytes();
999 reducer.push(
1000 entity,
1001 values,
1002 bytes,
1003 spans,
1004 MAX_STATE_BYTES - self.state_bytes + previous,
1005 )?;
1006 self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1007 return Ok(());
1008 }
1009 let base = key.capacity() + size;
1010 let available = MAX_STATE_BYTES - self.state_bytes;
1011 if self.rows.len() == MAX_GROUPS || base + self.initial.retained_bytes() > available {
1012 return Err(Error::Limit);
1013 }
1014 let mut reducer = self.initial.clone();
1015 reducer.push(entity, values, bytes, spans, available - base)?;
1016 let output = copy_projection(bytes, spans, self.mask, size);
1017 let retained = key.capacity() + output.capacity() + reducer.retained_bytes();
1020 if retained > available {
1021 return Err(Error::Limit);
1022 }
1023 self.state_bytes += retained;
1024 self.rows.insert(key, (output, reducer));
1025 Ok(())
1026 }
1027}