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]
584 pub fn filter(
585 mut self,
586 field: &'a str,
587 comparison: Comparison,
588 value: impl Into<IndexValue<'a>>,
589 ) -> Self {
590 self.request
591 .filter(field, comparison, QueryOperand::Literal(value.into()));
592
593 self
594 }
595
596 #[must_use]
598 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
599 self.filter(field, Comparison::Eq, value)
600 }
601
602 #[must_use]
604 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
605 self.filter(field, Comparison::Ne, value)
606 }
607
608 #[must_use]
610 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
611 self.filter(field, Comparison::Lt, value)
612 }
613
614 #[must_use]
616 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
617 self.filter(field, Comparison::Le, value)
618 }
619
620 #[must_use]
622 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
623 self.filter(field, Comparison::Gt, value)
624 }
625
626 #[must_use]
628 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
629 self.filter(field, Comparison::Ge, value)
630 }
631
632 #[must_use]
638 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
639 self.request
640 .filter(left, comparison, QueryOperand::Field(right));
641
642 self
643 }
644
645 #[must_use]
649 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
650 self.request
651 .filter(field, comparison, QueryOperand::Length(length));
652
653 self
654 }
655
656 #[must_use]
659 pub fn filter_present(self, field: &'a str) -> Self {
660 self.filter(field, Comparison::Ne, IndexValue::Absent)
661 }
662
663 #[must_use]
666 pub fn filter_absent(self, field: &'a str) -> Self {
667 self.filter(field, Comparison::Eq, IndexValue::Absent)
668 }
669
670 #[must_use]
677 pub fn filter_between(
678 self,
679 field: &'a str,
680 lower: impl Into<IndexValue<'a>>,
681 upper: impl Into<IndexValue<'a>>,
682 ) -> Self {
683 self.filter(field, Comparison::Ge, lower)
684 .filter(field, Comparison::Le, upper)
685 }
686
687 #[must_use]
695 pub fn filter_not_between(
696 self,
697 field: &'a str,
698 lower: impl Into<IndexValue<'a>>,
699 upper: impl Into<IndexValue<'a>>,
700 ) -> Self {
701 self.filter_any(&[
702 (field, Comparison::Lt, lower.into()),
703 (field, Comparison::Gt, upper.into()),
704 ])
705 }
706
707 #[must_use]
712 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
713 self.filter_fields(field, Comparison::Ge, lower)
714 .filter_fields(field, Comparison::Le, upper)
715 }
716
717 #[must_use]
722 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
723 self.filter_any_operands(&[
724 (field, Comparison::Lt, QueryOperand::Field(lower)),
725 (field, Comparison::Gt, QueryOperand::Field(upper)),
726 ])
727 }
728
729 #[must_use]
737 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
738 self.request.or_clause(
739 alternatives
740 .iter()
741 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
742 );
743
744 self
745 }
746
747 #[must_use]
752 pub fn filter_any_operands(
753 mut self,
754 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
755 ) -> Self {
756 self.request.or_clause(alternatives.iter().copied());
757
758 self
759 }
760
761 #[must_use]
771 pub fn filter_in(
772 mut self,
773 field: &'a str,
774 values: &[impl Copy + Into<IndexValue<'a>>],
775 ) -> Self {
776 self.request.or_clause(
777 values
778 .iter()
779 .copied()
780 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
781 );
782
783 self
784 }
785
786 #[must_use]
794 pub fn filter_not_in(
795 mut self,
796 field: &'a str,
797 values: &[impl Copy + Into<IndexValue<'a>>],
798 ) -> Self {
799 self.request
800 .filter_not_in(field, values.iter().copied().map(Into::into));
801
802 self
803 }
804
805 #[must_use]
810 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
811 self.request.using_index(name, values);
812
813 self
814 }
815
816 #[must_use]
819 pub fn order_asc(mut self, field: &'a str) -> Self {
820 self.request.append_order(field, SortDirection::Ascending);
821
822 self
823 }
824
825 #[must_use]
828 pub fn order_desc(mut self, field: &'a str) -> Self {
829 self.request.append_order(field, SortDirection::Descending);
830
831 self
832 }
833
834 #[must_use]
845 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
846 self.request.order_by(fields);
847
848 self
849 }
850
851 #[must_use]
856 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
857 self.request.order_by_each(fields);
858
859 self
860 }
861
862 #[must_use]
864 pub fn descending(mut self) -> Self {
865 self.request.descending = true;
866
867 self
868 }
869
870 #[must_use]
877 pub fn limit(mut self, rows: usize) -> Self {
878 self.request.rows = rows;
879
880 self
881 }
882
883 #[must_use]
885 pub fn work_limit(mut self, candidates: usize) -> Self {
886 self.request.work = candidates;
887
888 self
889 }
890
891 #[cfg(feature = "test-support")]
893 #[doc(hidden)]
894 #[must_use]
895 pub fn test_output_limit(mut self, bytes: usize) -> Self {
896 self.request.bytes = bytes;
897
898 self
899 }
900
901 #[must_use]
903 pub fn after(mut self, cursor: &'a QueryCursor) -> Self {
904 self.request.cursor = Some(cursor);
905
906 self
907 }
908
909 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
916 observe!(query, { self.entity_page() })
917 }
918
919 fn entity_page(self) -> Result<QueryPage<E>, Error> {
920 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
921 }
922
923 pub fn first(self) -> Result<Option<E>, Error> {
929 self.first_with(Self::entity_page)
930 }
931
932 pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
936 self.first_with(Self::projected_page::<R>)
937 }
938
939 fn first_with<R>(
940 self,
941 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
942 ) -> Result<Option<R>, Error> {
943 observe!(query, {
944 let page = fetch(self.probe_matches(1)?)?;
945 if page.rows.is_empty() && page.next.is_some() {
946 return Err(Error::Limit);
947 }
948 Ok(page)
949 })
950 .map(|mut page| page.rows.pop())
951 }
952
953 pub fn try_one(self) -> Result<Option<E>, Error> {
960 self.try_one_with(Self::entity_page)
961 }
962
963 pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
969 self.try_one_with(Self::projected_page::<R>)
970 }
971
972 fn try_one_with<R>(
973 self,
974 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
975 ) -> Result<Option<R>, Error> {
976 observe!(query, {
977 if self.request.cursor.is_some() {
978 return Err(Error::InvalidQuery);
979 }
980 let page = fetch(self.probe_matches(2)?)?;
981 if page.rows.len() == 2 {
982 return Err(Error::MultipleMatches);
983 }
984 if page.next.is_some() {
985 return Err(Error::Limit);
986 }
987
988 Ok(page)
989 })
990 .map(|mut page| page.rows.pop())
991 }
992
993 fn probe_matches(mut self, rows: usize) -> Result<Self, Error> {
994 if !(1..=32).contains(&self.request.rows) {
995 return Err(Error::Limit);
996 }
997
998 self.request.single_result_probe = true;
999
1000 Ok(self.limit(rows))
1001 }
1002
1003 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1013 observe!(query, { self.projected_page() })
1014 }
1015
1016 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1017 let raw = fetch_rows(
1018 &*self.db.read()?,
1019 E::SCHEMA,
1020 self.request,
1021 Some(R::definition()),
1022 )?;
1023
1024 raw.decode_projection()
1025 }
1026}
1027
1028fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u16, Error> {
1032 let TypeBody::Record(fields) = &output.body else {
1033 return Err(Error::InvalidQuery);
1034 };
1035 if fields.is_empty()
1036 || fields.len() > crate::schema::MAX_FIELDS
1037 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1038 {
1039 return Err(Error::InvalidQuery);
1040 }
1041 let mut source = TypeGraph::default();
1042 let mut target = TypeGraph::default();
1043 let mut mask = 0;
1044 for field in *fields {
1045 let position = entity
1046 .field_position(field.name)
1047 .ok_or(Error::InvalidQuery)?;
1048 let stored = &entity.fields[position];
1049 if stored.value != field.value || stored.optional != field.optional {
1050 return Err(Error::InvalidQuery);
1051 }
1052 source
1053 .include(stored.value)
1054 .map_err(|_| Error::InvalidQuery)?;
1055 target
1056 .include(field.value)
1057 .map_err(|_| Error::InvalidQuery)?;
1058 mask |= 1 << position;
1059 }
1060 if !source.contains(&target) {
1061 return Err(Error::InvalidQuery);
1062 }
1063
1064 Ok(mask)
1065}
1066
1067struct Term {
1068 position: usize,
1069 comparison: Comparison,
1070 operand: TermOperand,
1071 or_next: bool,
1072}
1073
1074enum TermOperand {
1075 Literal {
1076 bytes: Vec<u8>,
1077 absent: bool,
1078 },
1079 Member {
1080 item: FieldType,
1081 needle: MemberNeedle,
1082 },
1083 Nested {
1084 member: crate::member::RecordMember,
1085 literal: Vec<u8>,
1086 absent: bool,
1087 },
1088 Field(usize),
1089 Length(u32),
1090}
1091
1092enum MemberNeedle {
1093 Literal(Vec<u8>),
1094 Field(usize),
1095}
1096
1097fn member_type(field: FieldType) -> Option<FieldType> {
1098 match key::operand_type(field) {
1099 FieldType::List { item, .. } => Some(*item),
1100 FieldType::Named(link) => match (link.definition)().body {
1101 TypeBody::Set { item, .. } => Some(item),
1102 _ => None,
1103 },
1104 _ => None,
1105 }
1106}
1107
1108fn contains_member(
1110 span: &[u8],
1111 optional: bool,
1112 item: FieldType,
1113 needle: &[u8],
1114 scratch: &mut Vec<u8>,
1115) -> Result<bool, Error> {
1116 let mut reader = Decoder::new(span)?;
1117 if optional && !reader.boolean()? {
1118 return Ok(false);
1119 }
1120 for _ in 0..reader.nat32()? {
1121 scratch.clear();
1122 IndexValue::read(&mut reader, item)?.append_component(false, scratch);
1123 if scratch.as_slice() == needle {
1124 return Ok(true);
1125 }
1126 }
1127
1128 Ok(false)
1129}
1130
1131fn projection_positions(mut mask: u16) -> impl Iterator<Item = usize> {
1134 std::iter::from_fn(move || {
1135 if mask == 0 {
1136 return None;
1137 }
1138 let position = mask.trailing_zeros() as usize;
1139 mask &= mask - 1;
1140 Some(position)
1141 })
1142}
1143
1144fn admit_ordered_fields(entity: &EntitySchema, mask: u16) -> Result<(), Error> {
1145 for i in projection_positions(mask) {
1146 if !key::supports(entity.fields[i].value) {
1147 return Err(Error::InvalidQuery);
1148 }
1149 }
1150
1151 Ok(())
1152}
1153
1154fn comparison_key(
1156 entity: &EntitySchema,
1157 mask: u16,
1158 values: &[IndexValue<'_>],
1159 scratch: &mut Vec<u8>,
1160) -> Result<(), Error> {
1161 build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1162}
1163
1164fn build_comparison_key<'a>(
1165 entity: &EntitySchema,
1166 mask: u16,
1167 key: &mut Vec<u8>,
1168 mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1169) -> Result<(), Error> {
1170 key.clear();
1171 for i in projection_positions(mask) {
1172 let field = &entity.fields[i];
1173 value(i, field)?.append_component(field.optional, key);
1174 if key.len() > MAX_COMPARISON_KEY {
1175 return Err(Error::Limit);
1176 }
1177 }
1178
1179 Ok(())
1180}
1181
1182fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1183 if size > limit {
1184 return Err(Error::RowTooLarge);
1185 }
1186 if size > limit - *used {
1187 return Err(Error::Limit);
1188 }
1189 *used += size;
1190
1191 Ok(())
1192}
1193
1194fn projection_size(spans: &[(u16, u16)], mask: u16) -> usize {
1196 projection_positions(mask)
1197 .map(|i| {
1198 let (start, end) = spans[i];
1199 usize::from(end - start)
1200 })
1201 .sum()
1202}
1203
1204fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u16, size: usize) -> Vec<u8> {
1205 let mut output = Vec::with_capacity(size);
1206 for i in projection_positions(mask) {
1207 let (start, end) = spans[i];
1208 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1209 }
1210
1211 output
1212}
1213#[derive(Clone, Copy)]
1214enum PlanOutput {
1215 Rows,
1216 Aggregate { grouped: bool },
1217}
1218
1219struct Plan<'a> {
1220 primary: usize,
1221 index: Option<&'a IndexSchema>,
1222 prefix: Vec<u8>,
1223 fixed_components: usize,
1224 terms: Vec<Term>,
1225 selected: u16,
1226 span_fields: u16,
1228 binding: [u8; 32],
1229 projection: Option<u16>,
1230 distinct: distinct::Strategy,
1231 sort: Option<Vec<order::SortField>>,
1232 descending: bool,
1233}
1234impl<'a> Plan<'a> {
1235 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1236 self.terms.split_inclusive(|term| !term.or_next)
1237 }
1238
1239 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1240 self.index = Some(path.index);
1241 self.prefix = path.prefix;
1242 self.fixed_components = path.fixed;
1243 self.selected |= entity.key_fields();
1244 }
1245
1246 fn admit(
1247 entity: &'a EntitySchema,
1248 request: &Request<'_>,
1249 schema: [u8; 32],
1250 incarnation: [u8; 16],
1251 projection: Option<&TypeSchema>,
1252 output: PlanOutput,
1253 ) -> Result<Self, Error> {
1254 if request.over_limit
1255 || !(1..=32).contains(&request.rows)
1256 || !(1..=MAX_WORK).contains(&request.work)
1257 || !(1..=MAX_OUTPUT).contains(&request.bytes)
1258 {
1259 return Err(Error::Limit);
1260 }
1261 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1262 {
1263 return Err(Error::InvalidQuery);
1264 }
1265 for value in request
1267 .predicates
1268 .iter()
1269 .filter_map(|p| match &p.operand {
1270 QueryOperand::Literal(value) => Some(value),
1271 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1272 })
1273 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1274 {
1275 if match value {
1276 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1277 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1278 _ => false,
1279 } {
1280 return Err(Error::Limit);
1281 }
1282 }
1283 let primary = entity
1284 .field_position(entity.primary_key)
1285 .filter(|&i| !entity.fields[i].optional)
1286 .ok_or(Error::InvalidQuery)?;
1287 let mut plan = Self {
1288 primary,
1289 index: None,
1290 prefix: prefix(2, entity.id),
1291 fixed_components: 0,
1292 terms: Vec::new(),
1293 selected: 1 << primary,
1294 span_fields: 0,
1295 binding: [0; 32],
1296 projection: projection
1297 .map(|output| admit_projection(entity, output))
1298 .transpose()?,
1299 distinct: distinct::Strategy::Identity,
1300 sort: None,
1301 descending: request.descending ^ request.primary_descending(entity),
1302 };
1303 for predicate in &request.predicates {
1304 let (position, member) = crate::member::resolve_field(entity, predicate.field)?;
1305 let field = &entity.fields[position];
1306 if let Some(member) = member {
1307 if !predicate.comparison.is_relational() {
1308 return Err(Error::InvalidQuery);
1309 }
1310 let leaf = member.field();
1311 let QueryOperand::Literal(value) = predicate.operand else {
1312 return Err(Error::InvalidQuery);
1313 };
1314 predicate
1315 .comparison
1316 .admit(leaf.value, field.optional || leaf.optional, value)?;
1317 let mut literal = Vec::new();
1318 value.append_component(false, &mut literal);
1319 plan.span_fields |= 1 << position;
1320 plan.terms.push(Term {
1321 position,
1322 comparison: predicate.comparison,
1323 operand: TermOperand::Nested {
1324 member,
1325 literal,
1326 absent: value == IndexValue::Absent,
1327 },
1328 or_next: predicate.or_next,
1329 });
1330 continue;
1331 }
1332 let member = if predicate.comparison == Comparison::Contains {
1333 member_type(field.value)
1334 } else {
1335 None
1336 };
1337 let operand = match predicate.operand {
1338 QueryOperand::Length(length) => {
1339 let supported = match key::operand_type(field.value) {
1340 FieldType::Text { .. }
1341 | FieldType::Blob { .. }
1342 | FieldType::List { .. } => true,
1343 FieldType::Named(link) => matches!(
1344 (link.definition)().body,
1345 TypeBody::Map { .. } | TypeBody::Set { .. }
1346 ),
1347 _ => false,
1348 };
1349 if !supported || !predicate.comparison.is_relational() {
1350 return Err(Error::InvalidQuery);
1351 }
1352 plan.span_fields |= 1 << position;
1353
1354 TermOperand::Length(length)
1355 }
1356 QueryOperand::Field(name) => {
1357 let right = entity.field_position(name).ok_or(Error::InvalidQuery)?;
1358 let right_type = entity.fields[right].value;
1359 let left_type = member.unwrap_or(field.value);
1360 let compatible = left_type == right_type
1361 || matches!(
1362 (left_type, right_type),
1363 (FieldType::Text { .. }, FieldType::Text { .. })
1364 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1365 );
1366 if !compatible
1367 || !key::supports(left_type)
1368 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1369 {
1370 return Err(Error::InvalidQuery);
1371 }
1372 plan.selected |= 1 << right;
1373
1374 if let Some(item) = member {
1375 plan.span_fields |= 1 << position;
1376
1377 TermOperand::Member {
1378 item,
1379 needle: MemberNeedle::Field(right),
1380 }
1381 } else {
1382 plan.selected |= 1 << position;
1383
1384 TermOperand::Field(right)
1385 }
1386 }
1387 QueryOperand::Literal(value) => {
1388 if let Some(item) = member {
1389 if !key::supports(item) {
1390 return Err(Error::InvalidQuery);
1391 }
1392 value.admit(item, false)?;
1393 let mut bytes = Vec::new();
1394 value.append_component(false, &mut bytes);
1395 plan.span_fields |= 1 << position;
1396
1397 TermOperand::Member {
1398 item,
1399 needle: MemberNeedle::Literal(bytes),
1400 }
1401 } else {
1402 let absent = value == IndexValue::Absent;
1403 if key::supports(field.value) {
1404 plan.selected |= 1 << position;
1405 } else if absent
1406 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1407 {
1408 plan.span_fields |= 1 << position;
1409 } else {
1410 return Err(Error::InvalidQuery);
1411 }
1412 predicate
1413 .comparison
1414 .admit(field.value, field.optional, value)?;
1415 let mut bytes = Vec::new();
1416 value.append_component(field.optional, &mut bytes);
1417
1418 TermOperand::Literal { bytes, absent }
1419 }
1420 }
1421 };
1422 plan.terms.push(Term {
1423 position,
1424 comparison: predicate.comparison,
1425 operand,
1426 or_next: predicate.or_next,
1427 });
1428 }
1429 match order::select(entity, request, output)? {
1432 order::Path::Primary => {}
1433 order::Path::Index(path) => plan.use_index(entity, path),
1434 order::Path::Sort(fields) => {
1435 order::select_filtered_path(entity, request, &mut plan, false)?;
1436 for field in &fields {
1437 if field.member.is_some() {
1438 plan.span_fields |= 1 << field.position;
1439 } else {
1440 plan.selected |= 1 << field.position;
1441 }
1442 }
1443 plan.sort = Some(fields);
1444 }
1445 }
1446 if request.distinct {
1447 plan.distinct = distinct::admit(entity, request, &plan)?;
1448 if let distinct::Strategy::Complete { key_fields } = plan.distinct {
1449 plan.selected |= key_fields;
1450 }
1451 }
1452 let mut hash = Sha256::new();
1453 hash.update(b"ic-db:query:v1\0");
1454 hash.update(schema);
1455 hash.update(incarnation);
1456 hash.update([u8::from(request.descending)]);
1457 hash.update((plan.prefix.len() as u32).to_le_bytes());
1458 hash.update(&plan.prefix);
1459 for term in &plan.terms {
1460 hash.update([term.position as u8, term.comparison as u8]);
1461
1462 match &term.operand {
1463 TermOperand::Nested {
1464 member,
1465 literal,
1466 absent,
1467 } => {
1468 hash.update((u32::MAX - 2).to_le_bytes());
1469 hash.update([member.position() as u8, u8::from(*absent)]);
1470 hash.update((literal.len() as u32).to_le_bytes());
1471 hash.update(literal);
1472 }
1473 TermOperand::Literal { bytes, .. }
1474 | TermOperand::Member {
1475 needle: MemberNeedle::Literal(bytes),
1476 ..
1477 } => {
1478 hash.update((bytes.len() as u32).to_le_bytes());
1479 hash.update(bytes);
1480 }
1481 TermOperand::Length(length) => {
1482 hash.update((u32::MAX - 1).to_le_bytes());
1483 hash.update(length.to_le_bytes());
1484 }
1485 TermOperand::Field(right)
1486 | TermOperand::Member {
1487 needle: MemberNeedle::Field(right),
1488 ..
1489 } => {
1490 hash.update(u32::MAX.to_le_bytes());
1492 hash.update([*right as u8]);
1493 }
1494 }
1495 }
1496 let clauses = plan
1499 .terms
1500 .iter()
1501 .enumerate()
1502 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1503 if clauses != 0 {
1504 hash.update(b"or-clauses\0");
1505 hash.update([clauses]);
1506 }
1507 if let Some(order) = &request.order {
1508 hash.update(b"order\0");
1509 hash.update([order.len() as u8]);
1510 for name in order {
1511 if let Some(position) = entity.field_position(name) {
1513 hash.update([position as u8]);
1514 } else {
1515 hash.update([u8::MAX, name.len() as u8]);
1517 hash.update(name.as_bytes());
1518 }
1519 }
1520 }
1521 if request.order_descending != 0 {
1522 hash.update(b"order-directions\0");
1523 hash.update([request.order_descending]);
1524 }
1525 if let Some(mask) = plan.projection {
1528 hash.update(b"projection\0");
1529 hash.update(mask.to_le_bytes());
1530 }
1531 if request.distinct {
1532 hash.update(b"distinct\0");
1533 }
1534 plan.binding = hash.finalize().into();
1535 if let Some(cursor) = request.cursor {
1536 if cursor.binding != plan.binding {
1537 return Err(Error::InvalidCursor);
1538 }
1539 plan.validate_position(entity, cursor)
1540 .map_err(|_| Error::InvalidCursor)?;
1541 }
1542
1543 Ok(plan)
1544 }
1545
1546 fn validate_position(&self, entity: &EntitySchema, cursor: &QueryCursor) -> Result<(), Error> {
1547 if cursor.resume == Resume::AfterUnemittedClass
1548 && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
1549 {
1550 return Err(Error::InvalidCursor);
1551 }
1552 let bytes = cursor.position.as_slice();
1553 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
1554 return Err(Error::InvalidCursor);
1555 }
1556 if let Some(index) = self.index {
1557 let mut remaining = bytes
1558 .get(INDEX_PREFIX_BYTES..)
1559 .ok_or(Error::InvalidCursor)?;
1560 for name in index.fields {
1561 consume_index_component(entity, index, name, &mut remaining)?;
1562 }
1563 if !index.unique {
1564 key::consume(&mut remaining, entity.key_type()?)?;
1565 }
1566 if !remaining.is_empty() {
1567 return Err(Error::InvalidCursor);
1568 }
1569 } else {
1570 RowKey::decode(
1571 bytes
1572 .get(ENTITY_PREFIX_BYTES..)
1573 .ok_or(Error::InvalidCursor)?,
1574 entity.key_type()?,
1575 )?;
1576 }
1577
1578 Ok(())
1579 }
1580
1581 fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
1582 QueryCursor {
1583 binding: self.binding,
1584 position: position.to_vec(),
1585 resume,
1586 }
1587 }
1588}
1589
1590fn consume_index_component(
1592 entity: &EntitySchema,
1593 index: &IndexSchema,
1594 name: &str,
1595 remaining: &mut &[u8],
1596) -> Result<(), Error> {
1597 let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
1598
1599 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
1600}
1601
1602#[inline(never)]
1605#[expect(
1606 clippy::needless_pass_by_value,
1607 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1608)]
1609fn fetch_rows<M: Memory>(
1610 db: &Database<M>,
1611 entity: &EntitySchema,
1612 request: Request<'_>,
1613 projection: Option<&TypeSchema>,
1614) -> Result<QueryPage<Vec<u8>>, Error> {
1615 db.schema.admits(entity)?;
1616 let plan = Plan::admit(
1617 entity,
1618 &request,
1619 db.schema.fingerprint(),
1620 db.incarnation,
1621 projection,
1622 PlanOutput::Rows,
1623 )?;
1624
1625 execute(&db.map, entity, &request, &plan, None)
1626}
1627
1628fn execute<M: Memory>(
1629 map: &Map<M>,
1630 entity: &EntitySchema,
1631 request: &Request<'_>,
1632 plan: &Plan<'_>,
1633 mut aggregate: Option<aggregate::Accumulator<'_>>,
1634) -> Result<QueryPage<Vec<u8>>, Error> {
1635 execute_inner(map, entity, request, plan, aggregate.as_mut(), None)
1636}
1637
1638const STEP_INPUT_BYTES: usize = 64 * 1024;
1641const CANDIDATE_BYTES: usize = crate::codec::MAX_ROW_BYTES + 2 * crate::MAX_INDEX_KEY_BYTES;
1642
1643fn execute_inner<M: Memory>(
1644 map: &Map<M>,
1645 entity: &EntitySchema,
1646 request: &Request<'_>,
1647 plan: &Plan<'_>,
1648 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1649 mut input_bytes: Option<&mut usize>,
1650) -> Result<QueryPage<Vec<u8>>, Error> {
1651 let mut page = QueryPage {
1652 rows: Vec::new(),
1653 next: None,
1654 examined: 0,
1655 fetched: 0,
1656 output_bytes: 0,
1657 };
1658 let Some(bounds) = range::bounds(entity, request, plan)? else {
1659 return Ok(page);
1660 };
1661 let terminal = range::terminal_key(&bounds, plan.descending);
1662 let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
1663 let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
1664 Some(distinct::Collection::new(
1665 plan.projection.ok_or(Error::InvalidQuery)?,
1666 key_fields,
1667 ))
1668 } else {
1669 None
1670 };
1671 let mut sorted = plan
1672 .sort
1673 .as_ref()
1674 .map(|_| sort::Collection::new(request, plan.distinct));
1675 let mut component = Vec::new();
1676 let mut right_component = Vec::new();
1677 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
1679 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1680 } else {
1681 None
1682 };
1683 let primary_type = entity.fields[plan.primary].value;
1684 while let Some(entry) = if plan.descending {
1685 entries.next_back()
1686 } else {
1687 entries.next()
1688 } {
1689 if request.work == 0 {
1693 return Err(Error::Limit);
1694 }
1695 page.examined += 1;
1696 let stored_key = entry.key();
1697 let mut read_bytes = stored_key.len();
1698 let (owner, bytes) = if plan.index.is_some() {
1699 let owner_bytes = entry.value();
1700 read_bytes += owner_bytes.len();
1701 let owner = RowKey::decode(&owner_bytes, primary_type)?;
1702 let bytes = map.get(&row_key(entity.id, owner)).ok_or(Error::Corrupt)?;
1703
1704 (owner, bytes)
1705 } else {
1706 (
1707 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
1708 entry.value(),
1709 )
1710 };
1711 if let Some(used) = input_bytes.as_deref_mut() {
1712 read_bytes += bytes.len();
1713 if read_bytes > CANDIDATE_BYTES {
1714 return Err(Error::Corrupt);
1715 }
1716 *used += read_bytes;
1717 }
1718 page.fetched += 1;
1719 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
1720 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1721 entity.inspect_fields(
1722 &bytes,
1723 plan.selected,
1724 &mut values,
1725 (plan.index.is_some()
1726 || plan.span_fields != 0
1727 || match &aggregate {
1728 Some(accumulator) => accumulator.needs_spans(),
1729 None => plan.projection.is_some(),
1730 })
1731 .then_some(&mut spans),
1732 )?;
1733 if RowKey::from_index(values[plan.primary])? != owner {
1734 return Err(Error::Corrupt);
1735 }
1736 if plan.index.is_some() {
1737 validate_index_entry(
1738 entity,
1739 &entity.row_info(&values, &bytes, &spans)?,
1740 owner,
1741 stored_key,
1742 )?;
1743 }
1744 let mut accepts = |term: &Term| -> Result<bool, Error> {
1745 let value = values[term.position];
1746 component.clear();
1747 let (operand, optional) = match &term.operand {
1748 TermOperand::Nested {
1749 member,
1750 literal,
1751 absent,
1752 } => {
1753 let (start, end) = spans[term.position];
1754 let span = &bytes[usize::from(start)..usize::from(end)];
1755 let optional = entity.fields[term.position].optional;
1756 let value = member.read(span, optional)?;
1757 if *absent {
1758 return Ok(term.comparison.accepts_absent(value == IndexValue::Absent));
1759 }
1760 value.append_component(false, &mut component);
1761 return Ok(term.comparison.accepts(
1762 (value != IndexValue::Absent).then_some(&component),
1763 Some(literal),
1764 false,
1765 ));
1766 }
1767 TermOperand::Literal { absent: true, .. }
1768 if plan.span_fields & (1 << term.position) != 0 =>
1769 {
1770 let absent = bytes[usize::from(spans[term.position].0)] == 0;
1771
1772 return Ok(term.comparison.accepts_absent(absent));
1773 }
1774 TermOperand::Member { item, needle } => {
1775 let needle = match needle {
1776 MemberNeedle::Literal(bytes) => bytes.as_slice(),
1777 MemberNeedle::Field(right) => {
1778 let value = values[*right];
1779 if value == IndexValue::Absent {
1780 return Ok(false);
1781 }
1782 right_component.clear();
1783 value.append_component(false, &mut right_component);
1784
1785 &right_component
1786 }
1787 };
1788 let (start, end) = spans[term.position];
1789
1790 return contains_member(
1791 &bytes[usize::from(start)..usize::from(end)],
1792 entity.fields[term.position].optional,
1793 *item,
1794 needle,
1795 &mut component,
1796 );
1797 }
1798 TermOperand::Length(length) => {
1799 let (start, end) = spans[term.position];
1800 let span = &bytes[usize::from(start)..usize::from(end)];
1801 let actual =
1802 crate::codec::validated_length(span, entity.fields[term.position].optional);
1803
1804 return Ok(term.comparison.accepts_length(actual, *length));
1805 }
1806 TermOperand::Literal { bytes, absent } => (
1807 (!absent).then_some(bytes.as_slice()),
1808 entity.fields[term.position].optional,
1809 ),
1810 TermOperand::Field(right) => {
1811 let rhs = values[*right];
1812 right_component.clear();
1813 rhs.append_component(false, &mut right_component);
1814
1815 (
1816 (rhs != IndexValue::Absent).then_some(right_component.as_slice()),
1817 false,
1818 )
1819 }
1820 };
1821 value.append_component(optional, &mut component);
1822
1823 Ok(term.comparison.accepts(
1824 (value != IndexValue::Absent).then_some(component.as_slice()),
1825 operand,
1826 optional,
1827 ))
1828 };
1829 let matches = 'matches: {
1830 'clause: for clause in plan.clauses() {
1831 for term in clause {
1832 if accepts(term)? {
1833 continue 'clause;
1834 }
1835 }
1836 break 'matches false;
1837 }
1838
1839 true
1840 };
1841 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
1842 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
1843 if matches && let Some(accumulator) = aggregate.as_mut() {
1844 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
1845 if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
1846 return Ok(page);
1848 }
1849 } else if matches && let Some(collection) = collected.as_mut() {
1850 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
1851 if request.single_result_probe && collection.rows.len() == request.rows {
1854 break;
1855 }
1856 } else if matches && let Some(collection) = sorted.as_mut() {
1857 collection.push(entity, plan, &values, &bytes, &spans)?;
1858 } else if matches && !duplicate {
1859 let size = plan
1860 .projection
1861 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
1862 if size > request.bytes {
1863 return Err(Error::RowTooLarge);
1864 }
1865 if size > request.bytes - page.output_bytes {
1866 page.next = Some(plan.cursor(stored_key, Resume::Retry));
1867
1868 return Ok(page);
1869 }
1870 page.output_bytes += size;
1871 if let Some(mask) = plan.projection {
1872 page.rows.push(copy_projection(&bytes, &spans, mask, size));
1873 } else {
1874 page.rows.push(bytes);
1875 }
1876 if plan.distinct == distinct::Strategy::FirstMatch {
1877 return Ok(page);
1878 }
1879 if let Some(boundary) = boundary {
1880 previous = Some(boundary.to_vec());
1881 }
1882 }
1883 if page.rows.len() == request.rows
1884 || page.examined == request.work
1885 || input_bytes
1886 .as_deref()
1887 .is_some_and(|used| *used > STEP_INPUT_BYTES - CANDIDATE_BYTES)
1888 {
1889 if terminal == Some(stored_key) {
1890 break;
1891 }
1892 if (aggregate.is_some() && input_bytes.is_none())
1893 || collected.is_some()
1894 || sorted.is_some()
1895 {
1896 return Err(Error::Limit);
1899 }
1900 let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
1901 Resume::AfterUnemittedClass
1902 } else {
1903 Resume::After
1904 };
1905 page.next = Some(plan.cursor(stored_key, resume));
1906
1907 return Ok(page);
1908 }
1909 }
1910 if let Some(collection) = collected {
1911 page.output_bytes = collection.output_bytes;
1912 page.rows = collection.rows;
1913 }
1914 if let Some(collection) = sorted {
1915 collection.finish(request.bytes, &mut page)?;
1916 }
1917
1918 Ok(page)
1919}