1mod aggregate;
4mod distinct;
5mod order;
6mod range;
7mod sort;
8
9pub use aggregate::{
10 Aggregate, GroupCount, GroupOrder, GroupSummaries, GroupSummary, GroupSummaryPage, GroupValue,
11 SummaryMeasure,
12 jobs::{AggregateJobs, GroupCursor, GroupPage, JobHandle, JobOutcome, JobStep},
13};
14
15use super::{
16 Database, ENTITY_PREFIX_BYTES, INDEX_PREFIX_BYTES, Map, prefix, row_key, validate_index_entry,
17};
18use crate::{
19 Entity, EntitySchema, Error, FieldType, IndexSchema, IndexValue, TypeBody, TypeSchema, Value,
20 codec::Decoder, key, primary::RowKey, types::TypeGraph,
21};
22use ic_storage::Memory;
23use sha2::{Digest, Sha256};
24use std::{
25 cell::{Ref, RefCell},
26 marker::PhantomData,
27 ops::Deref,
28 rc::Rc,
29};
30
31const MAX_TERMS: usize = 8;
32const MAX_WORK: usize = 512;
33const MAX_OUTPUT: usize = 128 * 1024;
34const MAX_COMPARISON_KEY: usize = 4096;
35const MAX_DISTINCT_VALUES: usize = 32;
36const MAX_STATE_BYTES: usize = 128 * 1024;
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum SortDirection {
41 Ascending,
43 Descending,
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49#[repr(u8)]
50pub enum Comparison {
51 Eq = 0,
53 Ne = 1,
55 Lt = 2,
57 Le = 3,
59 Gt = 4,
61 Ge = 5,
63 StartsWith = 6,
67 EndsWith = 7,
70 Contains = 8,
74}
75
76impl Comparison {
77 fn is_relational(self) -> bool {
78 matches!(
79 self,
80 Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge
81 )
82 }
83
84 fn supports_scalar(self, field: FieldType) -> bool {
85 self.is_relational()
86 || matches!(
87 key::operand_type(field),
88 FieldType::Text { .. } | FieldType::Blob { .. }
89 )
90 }
91
92 fn admit(self, field: FieldType, optional: bool, value: IndexValue<'_>) -> Result<(), Error> {
93 value.admit(field, optional)?;
94 if !self.supports_scalar(field) {
95 return Err(Error::InvalidQuery);
96 }
97 if value == IndexValue::Absent && !matches!(self, Self::Eq | Self::Ne) {
98 return Err(Error::InvalidOperand);
99 }
100
101 Ok(())
102 }
103
104 fn accepts(self, actual: Option<&[u8]>, operand: Option<&[u8]>, optional: bool) -> bool {
105 if actual.is_none() {
106 return self.accepts_absent(operand.is_none());
107 }
108
109 match self {
110 Self::Eq => actual == operand,
111 Self::Ne => actual != operand,
112 Self::StartsWith | Self::EndsWith | Self::Contains => {
113 fn content(key: &[u8], optional: bool) -> Option<&[u8]> {
116 key.get(usize::from(optional)..)?.strip_suffix(&[0, 0])
117 }
118
119 actual
120 .and_then(|key| content(key, optional))
121 .zip(operand.and_then(|key| content(key, optional)))
122 .is_some_and(|(actual, operand)| match self {
123 Self::StartsWith => actual.starts_with(operand),
126 Self::EndsWith => actual
130 .strip_suffix(operand)
131 .is_some_and(|prefix| prefix.last() != Some(&0)),
132 _ => contains_component(actual, operand),
133 })
134 }
135 _ if actual.is_none() || operand.is_none() => false,
136 Self::Lt => actual < operand,
137 Self::Le => actual <= operand,
138 Self::Gt => actual > operand,
139 Self::Ge => actual >= operand,
140 }
141 }
142
143 fn accepts_length(self, actual: Option<u32>, threshold: u32) -> bool {
144 let encoded = actual.map(u32::to_be_bytes);
145
146 self.accepts(
147 encoded.as_ref().map(|v| v.as_slice()),
148 Some(&threshold.to_be_bytes()),
149 false,
150 )
151 }
152
153 fn accepts_absent(self, other_absent: bool) -> bool {
156 match self {
157 Self::Eq => other_absent,
158 Self::Ne => !other_absent,
159 _ => false,
160 }
161 }
162}
163
164fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
166 let Some(start) = memchr::memmem::find(actual, needle) else {
167 return false;
168 };
169 if start == 0 || actual[start - 1] != 0 {
170 return true;
171 }
172 fn raw(content: &[u8]) -> Vec<u8> {
176 let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
177 let mut encoded = content.iter();
178 while let Some(&byte) = encoded.next() {
179 bytes.push(byte);
180 if byte == 0 {
181 encoded.next();
182 }
183 }
184
185 bytes
186 }
187
188 memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
189}
190
191#[derive(Clone, Debug, PartialEq, Eq)]
195pub struct QueryCursor {
196 binding: [u8; 32],
197 position: Vec<u8>,
198 resume: Resume,
199}
200
201#[derive(Clone, Copy, Debug, PartialEq, Eq)]
202enum Resume {
203 After = 0,
204 Retry = 1,
205 AfterUnemittedClass = 2,
206}
207impl QueryCursor {
208 pub(super) const MAX_ENCODED_BYTES: usize = 34 + crate::MAX_INDEX_KEY_BYTES;
209
210 #[must_use]
212 pub fn to_bytes(&self) -> Vec<u8> {
213 let mut bytes = vec![1, self.resume as u8];
214 bytes.extend(self.binding);
215 bytes.extend(&self.position);
216
217 bytes
218 }
219
220 pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
224 if !(35..=Self::MAX_ENCODED_BYTES).contains(&bytes.len()) || bytes[0] != 1 {
225 return Err(Error::InvalidCursor);
226 }
227
228 Ok(Self {
229 binding: bytes[2..34].try_into().map_err(|_| Error::InvalidCursor)?,
230 position: bytes[34..].to_vec(),
231 resume: match bytes[1] {
232 0 => Resume::After,
233 1 => Resume::Retry,
234 2 => Resume::AfterUnemittedClass,
235 _ => return Err(Error::InvalidCursor),
236 },
237 })
238 }
239}
240
241#[derive(Debug)]
244pub struct QueryPage<T> {
245 pub rows: Vec<T>,
247 pub next: Option<QueryCursor>,
249 pub examined: usize,
251 pub fetched: usize,
253 pub output_bytes: usize,
255}
256
257impl QueryPage<Vec<u8>> {
258 #[inline(never)]
259 pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
260 Ok(QueryPage {
261 rows: self
262 .rows
263 .iter()
264 .map(|bytes| E::decode(bytes))
265 .collect::<Result<_, _>>()?,
266 next: self.next,
267 examined: self.examined,
268 fetched: self.fetched,
269 output_bytes: self.output_bytes,
270 })
271 }
272
273 #[inline(never)]
274 fn decode_projection<R: Value>(self) -> Result<QueryPage<R>, Error> {
275 Ok(QueryPage {
276 rows: self
277 .rows
278 .iter()
279 .map(|bytes| {
280 let mut reader = Decoder::new(bytes)?;
281 let row = R::decode_from(&mut reader)?;
283 reader.finish()?;
284
285 Ok(row)
286 })
287 .collect::<Result<_, Error>>()?,
288 next: self.next,
289 examined: self.examined,
290 fetched: self.fetched,
291 output_bytes: self.output_bytes,
292 })
293 }
294}
295
296#[derive(Clone, Copy, Debug, PartialEq, Eq)]
298pub enum QueryOperand<'a> {
299 Literal(IndexValue<'a>),
301 Length(u32),
303 Field(&'a str),
305}
306
307struct Predicate<'a> {
308 field: &'a str,
309 comparison: Comparison,
310 operand: QueryOperand<'a>,
311 or_next: bool,
313}
314struct Request<'a> {
315 groups: aggregate::GroupRequest<'a>,
316 predicates: Vec<Predicate<'a>>,
317 index: Option<(&'a str, Vec<IndexValue<'a>>)>,
318 order: Option<Vec<&'a str>>,
319 order_descending: u8,
320 descending: bool,
321 distinct: bool,
322 single_result_probe: bool,
323 rows: usize,
324 work: usize,
325 bytes: usize,
326 cursor: Option<&'a QueryCursor>,
327 over_limit: bool,
328}
329
330impl Default for Request<'_> {
331 fn default() -> Self {
332 Self {
333 groups: aggregate::GroupRequest::default(),
334 predicates: Vec::new(),
335 index: None,
336 order: None,
337 order_descending: 0,
338 descending: false,
339 distinct: false,
340 single_result_probe: false,
341 rows: 32,
342 work: 128,
343 bytes: MAX_OUTPUT,
344 cursor: None,
345 over_limit: false,
346 }
347 }
348}
349
350impl<'a> Request<'a> {
353 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
354 self.predicates.split_inclusive(|p| !p.or_next)
355 }
356
357 #[inline(never)]
358 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
359 if self.predicates.len() == MAX_TERMS {
360 self.over_limit = true;
361 } else {
362 self.predicates.push(Predicate {
363 field,
364 comparison,
365 operand,
366 or_next: false,
367 });
368 }
369 }
370
371 #[inline(never)]
372 fn or_clause(
373 &mut self,
374 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
375 ) {
376 let count = alternatives.len();
377
378 if count == 0 || count > MAX_TERMS - self.predicates.len() {
379 self.over_limit = true;
380 } else {
381 self.predicates.extend(alternatives.enumerate().map(
382 |(i, (field, comparison, operand))| Predicate {
383 field,
384 comparison,
385 operand,
386 or_next: i + 1 < count,
387 },
388 ));
389 }
390 }
391
392 #[inline(never)]
393 fn filter_not_in(
394 &mut self,
395 field: &'a str,
396 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
397 ) {
398 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
399 self.over_limit = true;
400
401 return;
402 }
403 for value in values {
404 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
405 }
406 }
407
408 #[inline(never)]
409 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
410 if values.len() > 4 {
411 self.over_limit = true;
412 } else {
413 self.index = Some((name, values.to_vec()));
414 }
415 }
416
417 #[inline(never)]
418 fn order_by(&mut self, fields: &[&'a str]) {
419 self.order_descending = 0;
420
421 if fields.len() > 4 {
422 self.over_limit = true;
423 } else {
424 self.order = Some(fields.to_vec());
425 }
426 }
427
428 #[inline(never)]
429 fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
430 if fields.len() > 4 {
431 self.over_limit = true;
432
433 return;
434 }
435 self.order = Some(Vec::with_capacity(fields.len()));
436 self.order_descending = 0;
437 for &(field, direction) in fields {
438 self.append_order(field, direction);
439 }
440 }
441
442 fn append_order(&mut self, field: &'a str, direction: SortDirection) {
443 let fields = self.order.get_or_insert_with(Vec::new);
444 if fields.len() == 4 {
445 self.over_limit = true;
446
447 return;
448 }
449 if direction == SortDirection::Descending {
450 self.order_descending |= 1 << fields.len();
451 }
452 fields.push(field);
453 }
454
455 fn primary_descending(&self, entity: &EntitySchema) -> bool {
456 self.order_descending != 0
457 && self.order.as_ref().is_some_and(|fields| {
458 fields.last() == Some(&entity.primary_key)
459 && self.order_descending & (1 << (fields.len() - 1)) != 0
460 })
461 }
462}
463
464pub(super) fn source_page<M: Memory>(
466 map: &Map<M>,
467 entity: &EntitySchema,
468 binding: [u8; 32],
469 incarnation: [u8; 16],
470 cursor: Option<&QueryCursor>,
471 rows: usize,
472 bytes: usize,
473) -> Result<QueryPage<Vec<u8>>, Error> {
474 let request = Request {
475 rows,
476 work: rows,
477 bytes,
478 cursor,
479 ..Request::default()
480 };
481 let plan = Plan::admit(
482 entity,
483 &request,
484 binding,
485 incarnation,
486 None,
487 PlanOutput::Rows,
488 )?;
489
490 execute(map, entity, &request, &plan, None)
491}
492
493enum QuerySource<'a, M: Memory> {
494 Direct(&'a Database<M>),
495 Session(Rc<RefCell<Database<M>>>),
496}
497
498enum QueryRead<'a, M: Memory> {
499 Direct(&'a Database<M>),
500 Session(Ref<'a, Database<M>>),
501}
502
503impl<M: Memory> Deref for QueryRead<'_, M> {
504 type Target = Database<M>;
505
506 fn deref(&self) -> &Self::Target {
507 match self {
508 Self::Direct(db) => db,
509 Self::Session(db) => db,
510 }
511 }
512}
513
514impl<M: Memory> QuerySource<'_, M> {
515 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
516 match self {
517 Self::Direct(db) => Ok(QueryRead::Direct(db)),
518 Self::Session(db) => db
519 .try_borrow()
520 .map(QueryRead::Session)
521 .map_err(|_| Error::BorrowConflict),
522 }
523 }
524}
525
526pub struct Query<'a, E, M: Memory> {
530 db: QuerySource<'a, M>,
531 request: Request<'a>,
532 entity: PhantomData<E>,
533}
534impl<M: Memory> Database<M> {
535 #[must_use]
537 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
538 Query {
539 db: QuerySource::Direct(self),
540 entity: PhantomData,
541 request: Request::default(),
542 }
543 }
544}
545impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
546 pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
547 Self {
548 db: QuerySource::Session(db),
549 request: Request::default(),
550 entity: PhantomData,
551 }
552 }
553
554 #[must_use]
566 pub fn distinct(mut self) -> Self {
567 self.request.distinct = true;
568
569 self
570 }
571
572 #[must_use]
582 pub fn filter(
583 mut self,
584 field: &'a str,
585 comparison: Comparison,
586 value: impl Into<IndexValue<'a>>,
587 ) -> Self {
588 self.request
589 .filter(field, comparison, QueryOperand::Literal(value.into()));
590
591 self
592 }
593
594 #[must_use]
596 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
597 self.filter(field, Comparison::Eq, value)
598 }
599
600 #[must_use]
602 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
603 self.filter(field, Comparison::Ne, value)
604 }
605
606 #[must_use]
608 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
609 self.filter(field, Comparison::Lt, value)
610 }
611
612 #[must_use]
614 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
615 self.filter(field, Comparison::Le, value)
616 }
617
618 #[must_use]
620 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
621 self.filter(field, Comparison::Gt, value)
622 }
623
624 #[must_use]
626 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
627 self.filter(field, Comparison::Ge, value)
628 }
629
630 #[must_use]
636 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
637 self.request
638 .filter(left, comparison, QueryOperand::Field(right));
639
640 self
641 }
642
643 #[must_use]
647 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
648 self.request
649 .filter(field, comparison, QueryOperand::Length(length));
650
651 self
652 }
653
654 #[must_use]
657 pub fn filter_present(self, field: &'a str) -> Self {
658 self.filter(field, Comparison::Ne, IndexValue::Absent)
659 }
660
661 #[must_use]
664 pub fn filter_absent(self, field: &'a str) -> Self {
665 self.filter(field, Comparison::Eq, IndexValue::Absent)
666 }
667
668 #[must_use]
675 pub fn filter_between(
676 self,
677 field: &'a str,
678 lower: impl Into<IndexValue<'a>>,
679 upper: impl Into<IndexValue<'a>>,
680 ) -> Self {
681 self.filter(field, Comparison::Ge, lower)
682 .filter(field, Comparison::Le, upper)
683 }
684
685 #[must_use]
693 pub fn filter_not_between(
694 self,
695 field: &'a str,
696 lower: impl Into<IndexValue<'a>>,
697 upper: impl Into<IndexValue<'a>>,
698 ) -> Self {
699 self.filter_any(&[
700 (field, Comparison::Lt, lower.into()),
701 (field, Comparison::Gt, upper.into()),
702 ])
703 }
704
705 #[must_use]
710 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
711 self.filter_fields(field, Comparison::Ge, lower)
712 .filter_fields(field, Comparison::Le, upper)
713 }
714
715 #[must_use]
720 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
721 self.filter_any_operands(&[
722 (field, Comparison::Lt, QueryOperand::Field(lower)),
723 (field, Comparison::Gt, QueryOperand::Field(upper)),
724 ])
725 }
726
727 #[must_use]
734 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
735 self.request.or_clause(
736 alternatives
737 .iter()
738 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
739 );
740
741 self
742 }
743
744 #[must_use]
749 pub fn filter_any_operands(
750 mut self,
751 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
752 ) -> Self {
753 self.request.or_clause(alternatives.iter().copied());
754
755 self
756 }
757
758 #[must_use]
768 pub fn filter_in(
769 mut self,
770 field: &'a str,
771 values: &[impl Copy + Into<IndexValue<'a>>],
772 ) -> Self {
773 self.request.or_clause(
774 values
775 .iter()
776 .copied()
777 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
778 );
779
780 self
781 }
782
783 #[must_use]
791 pub fn filter_not_in(
792 mut self,
793 field: &'a str,
794 values: &[impl Copy + Into<IndexValue<'a>>],
795 ) -> Self {
796 self.request
797 .filter_not_in(field, values.iter().copied().map(Into::into));
798
799 self
800 }
801
802 #[must_use]
807 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
808 self.request.using_index(name, values);
809
810 self
811 }
812
813 #[must_use]
816 pub fn order_asc(mut self, field: &'a str) -> Self {
817 self.request.append_order(field, SortDirection::Ascending);
818
819 self
820 }
821
822 #[must_use]
825 pub fn order_desc(mut self, field: &'a str) -> Self {
826 self.request.append_order(field, SortDirection::Descending);
827
828 self
829 }
830
831 #[must_use]
841 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
842 self.request.order_by(fields);
843
844 self
845 }
846
847 #[must_use]
852 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
853 self.request.order_by_each(fields);
854
855 self
856 }
857
858 #[must_use]
860 pub fn descending(mut self) -> Self {
861 self.request.descending = true;
862
863 self
864 }
865
866 #[must_use]
873 pub fn limit(mut self, rows: usize) -> Self {
874 self.request.rows = rows;
875
876 self
877 }
878
879 #[must_use]
881 pub fn work_limit(mut self, candidates: usize) -> Self {
882 self.request.work = candidates;
883
884 self
885 }
886
887 #[cfg(feature = "test-support")]
889 #[doc(hidden)]
890 #[must_use]
891 pub fn test_output_limit(mut self, bytes: usize) -> Self {
892 self.request.bytes = bytes;
893
894 self
895 }
896
897 #[must_use]
899 pub fn after(mut self, cursor: &'a QueryCursor) -> Self {
900 self.request.cursor = Some(cursor);
901
902 self
903 }
904
905 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
912 observe!(query, { self.entity_page() })
913 }
914
915 fn entity_page(self) -> Result<QueryPage<E>, Error> {
916 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
917 }
918
919 pub fn first(self) -> Result<Option<E>, Error> {
925 self.first_with(Self::entity_page)
926 }
927
928 pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
932 self.first_with(Self::projected_page::<R>)
933 }
934
935 fn first_with<R>(
936 self,
937 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
938 ) -> Result<Option<R>, Error> {
939 observe!(query, {
940 let page = fetch(self.probe_matches(1)?)?;
941 if page.rows.is_empty() && page.next.is_some() {
942 return Err(Error::Limit);
943 }
944 Ok(page)
945 })
946 .map(|mut page| page.rows.pop())
947 }
948
949 pub fn try_one(self) -> Result<Option<E>, Error> {
956 self.try_one_with(Self::entity_page)
957 }
958
959 pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
965 self.try_one_with(Self::projected_page::<R>)
966 }
967
968 fn try_one_with<R>(
969 self,
970 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
971 ) -> Result<Option<R>, Error> {
972 observe!(query, {
973 if self.request.cursor.is_some() {
974 return Err(Error::InvalidQuery);
975 }
976 let page = fetch(self.probe_matches(2)?)?;
977 if page.rows.len() == 2 {
978 return Err(Error::MultipleMatches);
979 }
980 if page.next.is_some() {
981 return Err(Error::Limit);
982 }
983
984 Ok(page)
985 })
986 .map(|mut page| page.rows.pop())
987 }
988
989 fn probe_matches(mut self, rows: usize) -> Result<Self, Error> {
990 if !(1..=32).contains(&self.request.rows) {
991 return Err(Error::Limit);
992 }
993
994 self.request.single_result_probe = true;
995
996 Ok(self.limit(rows))
997 }
998
999 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1009 observe!(query, { self.projected_page() })
1010 }
1011
1012 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1013 let raw = fetch_rows(
1014 &*self.db.read()?,
1015 E::SCHEMA,
1016 self.request,
1017 Some(R::definition()),
1018 )?;
1019
1020 raw.decode_projection()
1021 }
1022}
1023
1024fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u16, Error> {
1028 let TypeBody::Record(fields) = &output.body else {
1029 return Err(Error::InvalidQuery);
1030 };
1031 if fields.is_empty()
1032 || fields.len() > crate::schema::MAX_FIELDS
1033 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1034 {
1035 return Err(Error::InvalidQuery);
1036 }
1037 let mut source = TypeGraph::default();
1038 let mut target = TypeGraph::default();
1039 let mut mask = 0;
1040 for field in *fields {
1041 let position = entity
1042 .field_position(field.name)
1043 .ok_or(Error::InvalidQuery)?;
1044 let stored = &entity.fields[position];
1045 if stored.value != field.value || stored.optional != field.optional {
1046 return Err(Error::InvalidQuery);
1047 }
1048 source
1049 .include(stored.value)
1050 .map_err(|_| Error::InvalidQuery)?;
1051 target
1052 .include(field.value)
1053 .map_err(|_| Error::InvalidQuery)?;
1054 mask |= 1 << position;
1055 }
1056 if !source.contains(&target) {
1057 return Err(Error::InvalidQuery);
1058 }
1059
1060 Ok(mask)
1061}
1062
1063struct Term {
1064 position: usize,
1065 comparison: Comparison,
1066 operand: TermOperand,
1067 or_next: bool,
1068}
1069
1070enum TermOperand {
1071 Literal {
1072 bytes: Vec<u8>,
1073 absent: bool,
1074 },
1075 Member {
1076 item: FieldType,
1077 needle: MemberNeedle,
1078 },
1079 Field(usize),
1080 Length(u32),
1081}
1082
1083enum MemberNeedle {
1084 Literal(Vec<u8>),
1085 Field(usize),
1086}
1087
1088fn member_type(field: FieldType) -> Option<FieldType> {
1089 match key::operand_type(field) {
1090 FieldType::List { item, .. } => Some(*item),
1091 FieldType::Named(link) => match (link.definition)().body {
1092 TypeBody::Set { item, .. } => Some(item),
1093 _ => None,
1094 },
1095 _ => None,
1096 }
1097}
1098
1099fn contains_member(
1101 span: &[u8],
1102 optional: bool,
1103 item: FieldType,
1104 needle: &[u8],
1105 scratch: &mut Vec<u8>,
1106) -> Result<bool, Error> {
1107 let mut reader = Decoder::new(span)?;
1108 if optional && !reader.boolean()? {
1109 return Ok(false);
1110 }
1111 for _ in 0..reader.nat32()? {
1112 scratch.clear();
1113 IndexValue::read(&mut reader, item)?.append_component(false, scratch);
1114 if scratch.as_slice() == needle {
1115 return Ok(true);
1116 }
1117 }
1118
1119 Ok(false)
1120}
1121
1122fn projection_positions(mut mask: u16) -> impl Iterator<Item = usize> {
1125 std::iter::from_fn(move || {
1126 if mask == 0 {
1127 return None;
1128 }
1129 let position = mask.trailing_zeros() as usize;
1130 mask &= mask - 1;
1131 Some(position)
1132 })
1133}
1134
1135fn admit_ordered_fields(entity: &EntitySchema, mask: u16) -> Result<(), Error> {
1136 for i in projection_positions(mask) {
1137 if !key::supports(entity.fields[i].value) {
1138 return Err(Error::InvalidQuery);
1139 }
1140 }
1141
1142 Ok(())
1143}
1144
1145fn comparison_key(
1147 entity: &EntitySchema,
1148 mask: u16,
1149 values: &[IndexValue<'_>],
1150 scratch: &mut Vec<u8>,
1151) -> Result<(), Error> {
1152 build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1153}
1154
1155fn build_comparison_key<'a>(
1156 entity: &EntitySchema,
1157 mask: u16,
1158 key: &mut Vec<u8>,
1159 mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1160) -> Result<(), Error> {
1161 key.clear();
1162 for i in projection_positions(mask) {
1163 let field = &entity.fields[i];
1164 value(i, field)?.append_component(field.optional, key);
1165 if key.len() > MAX_COMPARISON_KEY {
1166 return Err(Error::Limit);
1167 }
1168 }
1169
1170 Ok(())
1171}
1172
1173fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1174 if size > limit {
1175 return Err(Error::RowTooLarge);
1176 }
1177 if size > limit - *used {
1178 return Err(Error::Limit);
1179 }
1180 *used += size;
1181
1182 Ok(())
1183}
1184
1185fn projection_size(spans: &[(u16, u16)], mask: u16) -> usize {
1187 projection_positions(mask)
1188 .map(|i| {
1189 let (start, end) = spans[i];
1190 usize::from(end - start)
1191 })
1192 .sum()
1193}
1194
1195fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u16, size: usize) -> Vec<u8> {
1196 let mut output = Vec::with_capacity(size);
1197 for i in projection_positions(mask) {
1198 let (start, end) = spans[i];
1199 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1200 }
1201
1202 output
1203}
1204#[derive(Clone, Copy)]
1205enum PlanOutput {
1206 Rows,
1207 Aggregate { grouped: bool },
1208}
1209
1210struct Plan<'a> {
1211 primary: usize,
1212 index: Option<&'a IndexSchema>,
1213 prefix: Vec<u8>,
1214 fixed_components: usize,
1215 terms: Vec<Term>,
1216 selected: u16,
1217 span_fields: u16,
1219 binding: [u8; 32],
1220 projection: Option<u16>,
1221 distinct: distinct::Strategy,
1222 sort: Option<Vec<(usize, bool)>>,
1223 descending: bool,
1224}
1225impl<'a> Plan<'a> {
1226 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1227 self.terms.split_inclusive(|term| !term.or_next)
1228 }
1229
1230 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1231 self.index = Some(path.index);
1232 self.prefix = path.prefix;
1233 self.fixed_components = path.fixed;
1234 self.selected |= entity.key_fields();
1235 }
1236
1237 fn admit(
1238 entity: &'a EntitySchema,
1239 request: &Request<'_>,
1240 schema: [u8; 32],
1241 incarnation: [u8; 16],
1242 projection: Option<&TypeSchema>,
1243 output: PlanOutput,
1244 ) -> Result<Self, Error> {
1245 if request.over_limit
1246 || !(1..=32).contains(&request.rows)
1247 || !(1..=MAX_WORK).contains(&request.work)
1248 || !(1..=MAX_OUTPUT).contains(&request.bytes)
1249 {
1250 return Err(Error::Limit);
1251 }
1252 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1253 {
1254 return Err(Error::InvalidQuery);
1255 }
1256 for value in request
1258 .predicates
1259 .iter()
1260 .filter_map(|p| match &p.operand {
1261 QueryOperand::Literal(value) => Some(value),
1262 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1263 })
1264 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1265 {
1266 if match value {
1267 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1268 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1269 _ => false,
1270 } {
1271 return Err(Error::Limit);
1272 }
1273 }
1274 let primary = entity
1275 .field_position(entity.primary_key)
1276 .filter(|&i| !entity.fields[i].optional)
1277 .ok_or(Error::InvalidQuery)?;
1278 let mut plan = Self {
1279 primary,
1280 index: None,
1281 prefix: prefix(2, entity.id),
1282 fixed_components: 0,
1283 terms: Vec::new(),
1284 selected: 1 << primary,
1285 span_fields: 0,
1286 binding: [0; 32],
1287 projection: projection
1288 .map(|output| admit_projection(entity, output))
1289 .transpose()?,
1290 distinct: distinct::Strategy::Identity,
1291 sort: None,
1292 descending: request.descending ^ request.primary_descending(entity),
1293 };
1294 for predicate in &request.predicates {
1295 let position = entity
1296 .field_position(predicate.field)
1297 .ok_or(Error::InvalidQuery)?;
1298 let field = &entity.fields[position];
1299 let member = if predicate.comparison == Comparison::Contains {
1300 member_type(field.value)
1301 } else {
1302 None
1303 };
1304 let operand = match predicate.operand {
1305 QueryOperand::Length(length) => {
1306 let supported = match key::operand_type(field.value) {
1307 FieldType::Text { .. }
1308 | FieldType::Blob { .. }
1309 | FieldType::List { .. } => true,
1310 FieldType::Named(link) => matches!(
1311 (link.definition)().body,
1312 TypeBody::Map { .. } | TypeBody::Set { .. }
1313 ),
1314 _ => false,
1315 };
1316 if !supported || !predicate.comparison.is_relational() {
1317 return Err(Error::InvalidQuery);
1318 }
1319 plan.span_fields |= 1 << position;
1320
1321 TermOperand::Length(length)
1322 }
1323 QueryOperand::Field(name) => {
1324 let right = entity.field_position(name).ok_or(Error::InvalidQuery)?;
1325 let right_type = entity.fields[right].value;
1326 let left_type = member.unwrap_or(field.value);
1327 let compatible = left_type == right_type
1328 || matches!(
1329 (left_type, right_type),
1330 (FieldType::Text { .. }, FieldType::Text { .. })
1331 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1332 );
1333 if !compatible
1334 || !key::supports(left_type)
1335 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1336 {
1337 return Err(Error::InvalidQuery);
1338 }
1339 plan.selected |= 1 << right;
1340
1341 if let Some(item) = member {
1342 plan.span_fields |= 1 << position;
1343
1344 TermOperand::Member {
1345 item,
1346 needle: MemberNeedle::Field(right),
1347 }
1348 } else {
1349 plan.selected |= 1 << position;
1350
1351 TermOperand::Field(right)
1352 }
1353 }
1354 QueryOperand::Literal(value) => {
1355 if let Some(item) = member {
1356 if !key::supports(item) {
1357 return Err(Error::InvalidQuery);
1358 }
1359 value.admit(item, false)?;
1360 let mut bytes = Vec::new();
1361 value.append_component(false, &mut bytes);
1362 plan.span_fields |= 1 << position;
1363
1364 TermOperand::Member {
1365 item,
1366 needle: MemberNeedle::Literal(bytes),
1367 }
1368 } else {
1369 let absent = value == IndexValue::Absent;
1370 if key::supports(field.value) {
1371 plan.selected |= 1 << position;
1372 } else if absent
1373 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1374 {
1375 plan.span_fields |= 1 << position;
1376 } else {
1377 return Err(Error::InvalidQuery);
1378 }
1379 predicate
1380 .comparison
1381 .admit(field.value, field.optional, value)?;
1382 let mut bytes = Vec::new();
1383 value.append_component(field.optional, &mut bytes);
1384
1385 TermOperand::Literal { bytes, absent }
1386 }
1387 }
1388 };
1389 plan.terms.push(Term {
1390 position,
1391 comparison: predicate.comparison,
1392 operand,
1393 or_next: predicate.or_next,
1394 });
1395 }
1396 match order::select(entity, request, output)? {
1399 order::Path::Primary => {}
1400 order::Path::Index(path) => plan.use_index(entity, path),
1401 order::Path::Sort(fields) => {
1402 order::select_filtered_path(entity, request, &mut plan, false)?;
1403 for &(position, _) in &fields {
1404 plan.selected |= 1 << position;
1405 }
1406 plan.sort = Some(fields);
1407 }
1408 }
1409 if request.distinct {
1410 plan.distinct = distinct::admit(
1411 entity,
1412 request,
1413 plan.projection,
1414 plan.index,
1415 plan.fixed_components,
1416 plan.sort.is_some(),
1417 )?;
1418 if plan.distinct == distinct::Strategy::Complete {
1419 plan.selected |= plan.projection.ok_or(Error::InvalidQuery)?;
1420 }
1421 }
1422 let mut hash = Sha256::new();
1423 hash.update(b"ic-db:query:v1\0");
1424 hash.update(schema);
1425 hash.update(incarnation);
1426 hash.update([u8::from(request.descending)]);
1427 hash.update((plan.prefix.len() as u32).to_le_bytes());
1428 hash.update(&plan.prefix);
1429 for term in &plan.terms {
1430 hash.update([term.position as u8, term.comparison as u8]);
1431
1432 match &term.operand {
1433 TermOperand::Literal { bytes, .. }
1434 | TermOperand::Member {
1435 needle: MemberNeedle::Literal(bytes),
1436 ..
1437 } => {
1438 hash.update((bytes.len() as u32).to_le_bytes());
1439 hash.update(bytes);
1440 }
1441 TermOperand::Length(length) => {
1442 hash.update((u32::MAX - 1).to_le_bytes());
1443 hash.update(length.to_le_bytes());
1444 }
1445 TermOperand::Field(right)
1446 | TermOperand::Member {
1447 needle: MemberNeedle::Field(right),
1448 ..
1449 } => {
1450 hash.update(u32::MAX.to_le_bytes());
1452 hash.update([*right as u8]);
1453 }
1454 }
1455 }
1456 let clauses = plan
1459 .terms
1460 .iter()
1461 .enumerate()
1462 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1463 if clauses != 0 {
1464 hash.update(b"or-clauses\0");
1465 hash.update([clauses]);
1466 }
1467 if let Some(order) = &request.order {
1468 hash.update(b"order\0");
1469 hash.update([order.len() as u8]);
1470 for name in order {
1471 hash.update([entity.field_position(name).ok_or(Error::InvalidQuery)? as u8]);
1473 }
1474 }
1475 if request.order_descending != 0 {
1476 hash.update(b"order-directions\0");
1477 hash.update([request.order_descending]);
1478 }
1479 if let Some(mask) = plan.projection {
1482 hash.update(b"projection\0");
1483 hash.update(mask.to_le_bytes());
1484 }
1485 if request.distinct {
1486 hash.update(b"distinct\0");
1487 }
1488 plan.binding = hash.finalize().into();
1489 if let Some(cursor) = request.cursor {
1490 if cursor.binding != plan.binding {
1491 return Err(Error::InvalidCursor);
1492 }
1493 plan.validate_position(entity, cursor)
1494 .map_err(|_| Error::InvalidCursor)?;
1495 }
1496
1497 Ok(plan)
1498 }
1499
1500 fn validate_position(&self, entity: &EntitySchema, cursor: &QueryCursor) -> Result<(), Error> {
1501 if cursor.resume == Resume::AfterUnemittedClass
1502 && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
1503 {
1504 return Err(Error::InvalidCursor);
1505 }
1506 let bytes = cursor.position.as_slice();
1507 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
1508 return Err(Error::InvalidCursor);
1509 }
1510 if let Some(index) = self.index {
1511 let mut remaining = bytes
1512 .get(INDEX_PREFIX_BYTES..)
1513 .ok_or(Error::InvalidCursor)?;
1514 for name in index.fields {
1515 consume_index_component(entity, index, name, &mut remaining)?;
1516 }
1517 if !index.unique {
1518 key::consume(&mut remaining, entity.key_type()?)?;
1519 }
1520 if !remaining.is_empty() {
1521 return Err(Error::InvalidCursor);
1522 }
1523 } else {
1524 RowKey::decode(
1525 bytes
1526 .get(ENTITY_PREFIX_BYTES..)
1527 .ok_or(Error::InvalidCursor)?,
1528 entity.key_type()?,
1529 )?;
1530 }
1531
1532 Ok(())
1533 }
1534
1535 fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
1536 QueryCursor {
1537 binding: self.binding,
1538 position: position.to_vec(),
1539 resume,
1540 }
1541 }
1542}
1543
1544fn consume_index_component(
1546 entity: &EntitySchema,
1547 index: &IndexSchema,
1548 name: &str,
1549 remaining: &mut &[u8],
1550) -> Result<(), Error> {
1551 let field = entity.field_by_name(name).ok_or(Error::InvalidQuery)?;
1552
1553 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
1554}
1555
1556#[inline(never)]
1559#[expect(
1560 clippy::needless_pass_by_value,
1561 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1562)]
1563fn fetch_rows<M: Memory>(
1564 db: &Database<M>,
1565 entity: &EntitySchema,
1566 request: Request<'_>,
1567 projection: Option<&TypeSchema>,
1568) -> Result<QueryPage<Vec<u8>>, Error> {
1569 db.schema.admits(entity)?;
1570 let plan = Plan::admit(
1571 entity,
1572 &request,
1573 db.schema.fingerprint(),
1574 db.incarnation,
1575 projection,
1576 PlanOutput::Rows,
1577 )?;
1578
1579 execute(&db.map, entity, &request, &plan, None)
1580}
1581
1582fn execute<M: Memory>(
1583 map: &Map<M>,
1584 entity: &EntitySchema,
1585 request: &Request<'_>,
1586 plan: &Plan<'_>,
1587 mut aggregate: Option<aggregate::Accumulator<'_>>,
1588) -> Result<QueryPage<Vec<u8>>, Error> {
1589 execute_inner(map, entity, request, plan, aggregate.as_mut(), None)
1590}
1591
1592const STEP_INPUT_BYTES: usize = 64 * 1024;
1595const CANDIDATE_BYTES: usize = crate::codec::MAX_ROW_BYTES + 2 * crate::MAX_INDEX_KEY_BYTES;
1596
1597fn execute_inner<M: Memory>(
1598 map: &Map<M>,
1599 entity: &EntitySchema,
1600 request: &Request<'_>,
1601 plan: &Plan<'_>,
1602 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1603 mut input_bytes: Option<&mut usize>,
1604) -> Result<QueryPage<Vec<u8>>, Error> {
1605 let mut page = QueryPage {
1606 rows: Vec::new(),
1607 next: None,
1608 examined: 0,
1609 fetched: 0,
1610 output_bytes: 0,
1611 };
1612 let Some(bounds) = range::bounds(entity, request, plan)? else {
1613 return Ok(page);
1614 };
1615 let terminal = range::terminal_key(&bounds, plan.descending);
1616 let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
1617 let mut collected = if plan.distinct == distinct::Strategy::Complete {
1618 Some(distinct::Collection::new(
1619 plan.projection.ok_or(Error::InvalidQuery)?,
1620 ))
1621 } else {
1622 None
1623 };
1624 let mut sorted = plan
1625 .sort
1626 .as_ref()
1627 .map(|_| sort::Collection::new(request, plan.distinct));
1628 let mut component = Vec::new();
1629 let mut right_component = Vec::new();
1630 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
1632 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1633 } else {
1634 None
1635 };
1636 let primary_type = entity.fields[plan.primary].value;
1637 while let Some(entry) = if plan.descending {
1638 entries.next_back()
1639 } else {
1640 entries.next()
1641 } {
1642 if request.work == 0 {
1646 return Err(Error::Limit);
1647 }
1648 page.examined += 1;
1649 let stored_key = entry.key();
1650 let mut read_bytes = stored_key.len();
1651 let (owner, bytes) = if plan.index.is_some() {
1652 let owner_bytes = entry.value();
1653 read_bytes += owner_bytes.len();
1654 let owner = RowKey::decode(&owner_bytes, primary_type)?;
1655 let bytes = map.get(&row_key(entity.id, owner)).ok_or(Error::Corrupt)?;
1656
1657 (owner, bytes)
1658 } else {
1659 (
1660 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
1661 entry.value(),
1662 )
1663 };
1664 if let Some(used) = input_bytes.as_deref_mut() {
1665 read_bytes += bytes.len();
1666 if read_bytes > CANDIDATE_BYTES {
1667 return Err(Error::Corrupt);
1668 }
1669 *used += read_bytes;
1670 }
1671 page.fetched += 1;
1672 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
1673 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1674 entity.inspect_fields(
1675 &bytes,
1676 plan.selected,
1677 &mut values,
1678 (plan.span_fields != 0
1679 || plan.projection.is_some()
1680 || aggregate.as_ref().is_some_and(|a| a.needs_spans()))
1681 .then_some(&mut spans),
1682 )?;
1683 if RowKey::from_index(values[plan.primary])? != owner {
1684 return Err(Error::Corrupt);
1685 }
1686 if plan.index.is_some() {
1687 validate_index_entry(entity, &entity.row_info(&values)?, owner, stored_key)?;
1688 }
1689 let mut accepts = |term: &Term| -> Result<bool, Error> {
1690 let value = values[term.position];
1691 component.clear();
1692 let (operand, optional) = match &term.operand {
1693 TermOperand::Literal { absent: true, .. }
1694 if plan.span_fields & (1 << term.position) != 0 =>
1695 {
1696 let absent = bytes[usize::from(spans[term.position].0)] == 0;
1697
1698 return Ok(term.comparison.accepts_absent(absent));
1699 }
1700 TermOperand::Member { item, needle } => {
1701 let needle = match needle {
1702 MemberNeedle::Literal(bytes) => bytes.as_slice(),
1703 MemberNeedle::Field(right) => {
1704 let value = values[*right];
1705 if value == IndexValue::Absent {
1706 return Ok(false);
1707 }
1708 right_component.clear();
1709 value.append_component(false, &mut right_component);
1710
1711 &right_component
1712 }
1713 };
1714 let (start, end) = spans[term.position];
1715
1716 return contains_member(
1717 &bytes[usize::from(start)..usize::from(end)],
1718 entity.fields[term.position].optional,
1719 *item,
1720 needle,
1721 &mut component,
1722 );
1723 }
1724 TermOperand::Length(length) => {
1725 let (start, end) = spans[term.position];
1726 let span = &bytes[usize::from(start)..usize::from(end)];
1727 let actual =
1728 crate::codec::validated_length(span, entity.fields[term.position].optional);
1729
1730 return Ok(term.comparison.accepts_length(actual, *length));
1731 }
1732 TermOperand::Literal { bytes, absent } => (
1733 (!absent).then_some(bytes.as_slice()),
1734 entity.fields[term.position].optional,
1735 ),
1736 TermOperand::Field(right) => {
1737 let rhs = values[*right];
1738 right_component.clear();
1739 rhs.append_component(false, &mut right_component);
1740
1741 (
1742 (rhs != IndexValue::Absent).then_some(right_component.as_slice()),
1743 false,
1744 )
1745 }
1746 };
1747 value.append_component(optional, &mut component);
1748
1749 Ok(term.comparison.accepts(
1750 (value != IndexValue::Absent).then_some(component.as_slice()),
1751 operand,
1752 optional,
1753 ))
1754 };
1755 let matches = 'matches: {
1756 'clause: for clause in plan.clauses() {
1757 for term in clause {
1758 if accepts(term)? {
1759 continue 'clause;
1760 }
1761 }
1762 break 'matches false;
1763 }
1764
1765 true
1766 };
1767 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
1768 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
1769 if matches && let Some(accumulator) = aggregate.as_mut() {
1770 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
1771 if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
1772 return Ok(page);
1774 }
1775 } else if matches && let Some(collection) = collected.as_mut() {
1776 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
1777 if request.single_result_probe && collection.rows.len() == request.rows {
1780 break;
1781 }
1782 } else if matches && let Some(collection) = sorted.as_mut() {
1783 collection.push(entity, plan, &values, &bytes, &spans)?;
1784 } else if matches && !duplicate {
1785 let size = plan
1786 .projection
1787 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
1788 if size > request.bytes {
1789 return Err(Error::RowTooLarge);
1790 }
1791 if size > request.bytes - page.output_bytes {
1792 page.next = Some(plan.cursor(stored_key, Resume::Retry));
1793
1794 return Ok(page);
1795 }
1796 page.output_bytes += size;
1797 if let Some(mask) = plan.projection {
1798 page.rows.push(copy_projection(&bytes, &spans, mask, size));
1799 } else {
1800 page.rows.push(bytes);
1801 }
1802 if plan.distinct == distinct::Strategy::FirstMatch {
1803 return Ok(page);
1804 }
1805 if let Some(boundary) = boundary {
1806 previous = Some(boundary.to_vec());
1807 }
1808 }
1809 if page.rows.len() == request.rows
1810 || page.examined == request.work
1811 || input_bytes
1812 .as_deref()
1813 .is_some_and(|used| *used > STEP_INPUT_BYTES - CANDIDATE_BYTES)
1814 {
1815 if terminal == Some(stored_key) {
1816 break;
1817 }
1818 if (aggregate.is_some() && input_bytes.is_none())
1819 || collected.is_some()
1820 || sorted.is_some()
1821 {
1822 return Err(Error::Limit);
1825 }
1826 let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
1827 Resume::AfterUnemittedClass
1828 } else {
1829 Resume::After
1830 };
1831 page.next = Some(plan.cursor(stored_key, resume));
1832
1833 return Ok(page);
1834 }
1835 }
1836 if let Some(collection) = collected {
1837 page.output_bytes = collection.output_bytes;
1838 page.rows = collection.rows;
1839 }
1840 if let Some(collection) = sorted {
1841 collection.finish(request.bytes, &mut page)?;
1842 }
1843
1844 Ok(page)
1845}