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