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