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 supports_record_member(self) -> bool {
78 self.is_relational() || matches!(self, Self::StartsWith | Self::EndsWith)
79 }
80
81 fn is_relational(self) -> bool {
82 matches!(
83 self,
84 Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge
85 )
86 }
87
88 fn supports_scalar(self, field: FieldType) -> bool {
89 self.is_relational()
90 || matches!(
91 key::operand_type(field),
92 FieldType::Text { .. } | FieldType::Blob { .. }
93 )
94 }
95
96 fn admit(self, field: FieldType, optional: bool, value: IndexValue<'_>) -> Result<(), Error> {
97 value.admit(field, optional)?;
98 if !self.supports_scalar(field) {
99 return Err(Error::InvalidQuery);
100 }
101 if value == IndexValue::Absent && !matches!(self, Self::Eq | Self::Ne) {
102 return Err(Error::InvalidOperand);
103 }
104
105 Ok(())
106 }
107
108 fn accepts(self, actual: Option<&[u8]>, operand: Option<&[u8]>, optional: bool) -> bool {
109 if actual.is_none() {
110 return self.accepts_absent(operand.is_none());
111 }
112
113 match self {
114 Self::Eq => actual == operand,
115 Self::Ne => actual != operand,
116 Self::StartsWith | Self::EndsWith | Self::Contains => {
117 fn content(key: &[u8], optional: bool) -> Option<&[u8]> {
120 key.get(usize::from(optional)..)?.strip_suffix(&[0, 0])
121 }
122
123 actual
124 .and_then(|key| content(key, optional))
125 .zip(operand.and_then(|key| content(key, optional)))
126 .is_some_and(|(actual, operand)| match self {
127 Self::StartsWith => actual.starts_with(operand),
130 Self::EndsWith => actual
134 .strip_suffix(operand)
135 .is_some_and(|prefix| prefix.last() != Some(&0)),
136 _ => contains_component(actual, operand),
137 })
138 }
139 _ if actual.is_none() || operand.is_none() => false,
140 Self::Lt => actual < operand,
141 Self::Le => actual <= operand,
142 Self::Gt => actual > operand,
143 Self::Ge => actual >= operand,
144 }
145 }
146
147 fn accepts_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
149 match self {
150 Self::Eq => Some(equal_values(left, right)),
151 Self::Ne => Some(!equal_values(left, right)),
152 _ => Some(self.accepts_bytes(scalar_bytes(left)?, scalar_bytes(right)?)),
153 }
154 }
155
156 fn accepts_bytes(self, actual: &[u8], operand: &[u8]) -> bool {
158 match self {
159 Self::StartsWith => actual.starts_with(operand),
160 Self::EndsWith => actual.ends_with(operand),
161 Self::Contains => memchr::memmem::find(actual, operand).is_some(),
162 _ => self.accepts(Some(actual), Some(operand), false),
163 }
164 }
165
166 fn accepts_length(self, actual: Option<u32>, threshold: u32) -> bool {
167 let encoded = actual.map(u32::to_be_bytes);
168
169 self.accepts(
170 encoded.as_ref().map(|v| v.as_slice()),
171 Some(&threshold.to_be_bytes()),
172 false,
173 )
174 }
175
176 fn uniform_length_result(self, min: u32, max: u32, n: u32) -> Option<bool> {
178 match self {
179 Self::Eq | Self::Ne if min == max || n < min || n > max => {
180 Some(self.accepts_length(Some(min), n))
181 }
182 Self::Lt | Self::Ge if max < n || min >= n => Some(self.accepts_length(Some(min), n)),
183 Self::Le | Self::Gt if max <= n || min > n => Some(self.accepts_length(Some(min), n)),
184 _ => None,
185 }
186 }
187
188 fn accepts_absent(self, other_absent: bool) -> bool {
191 match self {
192 Self::Eq => other_absent,
193 Self::Ne => !other_absent,
194 _ => false,
195 }
196 }
197}
198
199fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
201 let Some(start) = memchr::memmem::find(actual, needle) else {
202 return false;
203 };
204 if start == 0 || actual[start - 1] != 0 {
205 return true;
206 }
207 fn raw(content: &[u8]) -> Vec<u8> {
211 let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
212 let mut encoded = content.iter();
213 while let Some(&byte) = encoded.next() {
214 bytes.push(byte);
215 if byte == 0 {
216 encoded.next();
217 }
218 }
219
220 bytes
221 }
222
223 memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
224}
225
226#[derive(Clone, Debug, PartialEq, Eq)]
230pub struct QueryCursor {
231 binding: [u8; 32],
232 position: Vec<u8>,
233 resume: Resume,
234}
235
236#[derive(Clone, Copy, Debug, PartialEq, Eq)]
237enum Resume {
238 After = 0,
239 Retry = 1,
240 AfterUnemittedClass = 2,
241}
242impl QueryCursor {
243 pub(super) const MAX_ENCODED_BYTES: usize = 34 + crate::MAX_INDEX_KEY_BYTES;
244
245 #[must_use]
247 pub fn to_bytes(&self) -> Vec<u8> {
248 let mut bytes = vec![1, self.resume as u8];
249 bytes.extend(self.binding);
250 bytes.extend(&self.position);
251
252 bytes
253 }
254
255 pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
259 if !(35..=Self::MAX_ENCODED_BYTES).contains(&bytes.len()) || bytes[0] != 1 {
260 return Err(Error::InvalidCursor);
261 }
262
263 Ok(Self {
264 binding: bytes[2..34].try_into().map_err(|_| Error::InvalidCursor)?,
265 position: bytes[34..].to_vec(),
266 resume: match bytes[1] {
267 0 => Resume::After,
268 1 => Resume::Retry,
269 2 => Resume::AfterUnemittedClass,
270 _ => return Err(Error::InvalidCursor),
271 },
272 })
273 }
274}
275
276impl serde::Serialize for QueryCursor {
277 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
278 self.to_bytes().serialize(serializer)
279 }
280}
281
282impl<'de> serde::Deserialize<'de> for QueryCursor {
283 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
284 struct Frame;
285
286 impl<'de> serde::de::Visitor<'de> for Frame {
287 type Value = QueryCursor;
288
289 fn expecting(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
290 fmt.write_str("a bounded IC DB query cursor frame")
291 }
292
293 fn visit_seq<A: serde::de::SeqAccess<'de>>(
294 self,
295 mut seq: A,
296 ) -> Result<QueryCursor, A::Error> {
297 let size = seq.size_hint().unwrap_or(0);
298 if size > QueryCursor::MAX_ENCODED_BYTES {
299 return Err(serde::de::Error::custom(Error::InvalidCursor));
300 }
301 let mut frame = Vec::with_capacity(size);
302 while let Some(byte) = seq.next_element()? {
303 if frame.len() == QueryCursor::MAX_ENCODED_BYTES {
304 return Err(serde::de::Error::custom(Error::InvalidCursor));
305 }
306 frame.push(byte);
307 }
308 QueryCursor::from_bytes(&frame).map_err(serde::de::Error::custom)
309 }
310 }
311
312 deserializer.deserialize_seq(Frame)
313 }
314}
315
316#[derive(Debug)]
319pub struct QueryPage<T> {
320 pub rows: Vec<T>,
322 pub next: Option<QueryCursor>,
324 pub examined: usize,
326 pub fetched: usize,
328 pub output_bytes: usize,
330}
331
332impl QueryPage<Vec<u8>> {
333 #[inline(never)]
334 pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
335 Ok(QueryPage {
336 rows: self
337 .rows
338 .iter()
339 .map(|bytes| E::decode(bytes))
340 .collect::<Result<_, _>>()?,
341 next: self.next,
342 examined: self.examined,
343 fetched: self.fetched,
344 output_bytes: self.output_bytes,
345 })
346 }
347
348 #[inline(never)]
349 fn decode_projection<R: Value>(self) -> Result<QueryPage<R>, Error> {
350 Ok(QueryPage {
351 rows: self
352 .rows
353 .iter()
354 .map(|bytes| {
355 let mut reader = Decoder::new(bytes)?;
356 let row = R::decode_from(&mut reader)?;
358 reader.finish()?;
359
360 Ok(row)
361 })
362 .collect::<Result<_, Error>>()?,
363 next: self.next,
364 examined: self.examined,
365 fetched: self.fetched,
366 output_bytes: self.output_bytes,
367 })
368 }
369}
370
371#[derive(Clone, Copy, Debug, PartialEq, Eq)]
373pub enum QueryOperand<'a> {
374 Literal(IndexValue<'a>),
376 Length(u32),
378 Field(&'a str),
380}
381
382struct Predicate<'a> {
383 field: &'a str,
384 comparison: Comparison,
385 operand: QueryOperand<'a>,
386 or_next: bool,
388}
389
390impl Predicate<'_> {
391 fn tests_presence(&self, entity: &EntitySchema, operand: &TermOperand) -> bool {
393 match (self.comparison, self.operand) {
394 (Comparison::Ne, QueryOperand::Literal(IndexValue::Absent))
395 | (Comparison::Ge, QueryOperand::Literal(IndexValue::Bool(false)))
396 | (Comparison::Le, QueryOperand::Literal(IndexValue::Bool(true))) => true,
397 (_, QueryOperand::Length(_)) => {
398 self.present_length_result(entity) == Some(true)
399 && self.comparison != Comparison::Ne
400 }
401 (
402 Comparison::Le
403 | Comparison::Ge
404 | Comparison::StartsWith
405 | Comparison::EndsWith
406 | Comparison::Contains,
407 QueryOperand::Field(right),
408 ) => right == self.field,
409 (
410 Comparison::Ge
411 | Comparison::StartsWith
412 | Comparison::EndsWith
413 | Comparison::Contains,
414 QueryOperand::Literal(needle),
415 ) => {
416 !matches!(operand, TermOperand::Member { .. })
418 && scalar_bytes(needle).is_some_and(<[u8]>::is_empty)
419 }
420 _ => false,
421 }
422 }
423
424 fn present_length_result(&self, entity: &EntitySchema) -> Option<bool> {
426 let QueryOperand::Length(n) = self.operand else {
427 return None;
428 };
429 let max = length_limit(entity.index_field(self.field)?.value)?;
430 self.comparison.uniform_length_result(0, max, n)
431 }
432
433 fn constant_comparison(&self, entity: &EntitySchema) -> Option<bool> {
434 if let QueryOperand::Literal(value) = self.operand {
435 return match (self.comparison, value) {
437 (Comparison::Lt, IndexValue::Bool(false))
438 | (Comparison::Gt, IndexValue::Bool(true)) => Some(false),
439 (Comparison::Lt, _) if scalar_bytes(value).is_some_and(<[u8]>::is_empty) => {
440 Some(false)
441 }
442 _ => None,
443 };
444 }
445 if matches!(self.operand, QueryOperand::Length(_)) {
446 let result = self.present_length_result(entity)?;
447 return (result == self.comparison.accepts_absent(false)
448 || entity.field_is_required(self.field))
449 .then_some(result);
450 }
451 if !matches!(self.operand, QueryOperand::Field(right) if right == self.field) {
452 return None;
453 }
454 match self.comparison {
455 Comparison::Eq => Some(true),
456 Comparison::Ne | Comparison::Lt | Comparison::Gt => Some(false),
457 _ => None,
458 }
459 }
460}
461
462struct Request<'a> {
463 groups: aggregate::GroupRequest<'a>,
464 predicates: Vec<Predicate<'a>>,
465 index: Option<(&'a str, Vec<IndexValue<'a>>)>,
466 order: Option<Vec<&'a str>>,
467 order_descending: u8,
468 descending: bool,
469 distinct: bool,
470 single_result_probe: bool,
471 rows: usize,
472 work: usize,
473 bytes: usize,
474 cursor: Option<&'a QueryCursor>,
475 over_limit: bool,
476}
477
478impl Default for Request<'_> {
479 fn default() -> Self {
480 Self {
481 groups: aggregate::GroupRequest::default(),
482 predicates: Vec::new(),
483 index: None,
484 order: None,
485 order_descending: 0,
486 descending: false,
487 distinct: false,
488 single_result_probe: false,
489 rows: 32,
490 work: 128,
491 bytes: MAX_OUTPUT,
492 cursor: None,
493 over_limit: false,
494 }
495 }
496}
497
498impl<'a> Request<'a> {
501 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
502 self.predicates.split_inclusive(|p| !p.or_next)
503 }
504
505 #[inline(never)]
506 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
507 if self.predicates.len() == MAX_TERMS {
508 self.over_limit = true;
509 } else {
510 self.predicates.push(Predicate {
511 field,
512 comparison,
513 operand,
514 or_next: false,
515 });
516 }
517 }
518
519 #[inline(never)]
520 fn or_clause(
521 &mut self,
522 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
523 ) {
524 let count = alternatives.len();
525
526 if count == 0 || count > MAX_TERMS - self.predicates.len() {
527 self.over_limit = true;
528 } else {
529 self.predicates.extend(alternatives.enumerate().map(
530 |(i, (field, comparison, operand))| Predicate {
531 field,
532 comparison,
533 operand,
534 or_next: i + 1 < count,
535 },
536 ));
537 }
538 }
539
540 #[inline(never)]
541 fn filter_not_in(
542 &mut self,
543 field: &'a str,
544 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
545 ) {
546 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
547 self.over_limit = true;
548
549 return;
550 }
551 for value in values {
552 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
553 }
554 }
555
556 #[inline(never)]
557 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
558 if values.len() > 4 {
559 self.over_limit = true;
560 } else {
561 self.index = Some((name, values.to_vec()));
562 }
563 }
564
565 #[inline(never)]
566 fn order_by(&mut self, fields: &[&'a str]) {
567 self.order_descending = 0;
568
569 if fields.len() > 4 {
570 self.over_limit = true;
571 } else {
572 self.order = Some(fields.to_vec());
573 }
574 }
575
576 #[inline(never)]
577 fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
578 if fields.len() > 4 {
579 self.over_limit = true;
580
581 return;
582 }
583 self.order = Some(Vec::with_capacity(fields.len()));
584 self.order_descending = 0;
585 for &(field, direction) in fields {
586 self.append_order(field, direction);
587 }
588 }
589
590 fn append_order(&mut self, field: &'a str, direction: SortDirection) {
591 let fields = self.order.get_or_insert_with(Vec::new);
592 if fields.len() == 4 {
593 self.over_limit = true;
594
595 return;
596 }
597 if direction == SortDirection::Descending {
598 self.order_descending |= 1 << fields.len();
599 }
600 fields.push(field);
601 }
602
603 fn primary_descending(&self, entity: &EntitySchema) -> bool {
604 self.order_descending != 0
605 && self.order.as_ref().is_some_and(|fields| {
606 fields.last() == Some(&entity.primary_key)
607 && self.order_descending & (1 << (fields.len() - 1)) != 0
608 })
609 }
610}
611
612pub(super) fn source_page<M: Memory>(
614 map: &Map<M>,
615 entity: &EntitySchema,
616 binding: [u8; 32],
617 incarnation: [u8; 16],
618 cursor: Option<&QueryCursor>,
619 rows: usize,
620 bytes: usize,
621) -> Result<QueryPage<Vec<u8>>, Error> {
622 let request = Request {
623 rows,
624 work: rows,
625 bytes,
626 cursor,
627 ..Request::default()
628 };
629 let plan = Plan::admit(
630 entity,
631 &request,
632 binding,
633 incarnation,
634 None,
635 PlanOutput::Rows,
636 )?;
637
638 execute(map, entity, &request, &plan, None)
639}
640
641enum QuerySource<'a, M: Memory> {
642 Direct(&'a Database<M>),
643 Session(Rc<RefCell<Database<M>>>),
644}
645
646enum QueryRead<'a, M: Memory> {
647 Direct(&'a Database<M>),
648 Session(Ref<'a, Database<M>>),
649}
650
651impl<M: Memory> Deref for QueryRead<'_, M> {
652 type Target = Database<M>;
653
654 fn deref(&self) -> &Self::Target {
655 match self {
656 Self::Direct(db) => db,
657 Self::Session(db) => db,
658 }
659 }
660}
661
662impl<M: Memory> QuerySource<'_, M> {
663 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
664 match self {
665 Self::Direct(db) => Ok(QueryRead::Direct(db)),
666 Self::Session(db) => db
667 .try_borrow()
668 .map(QueryRead::Session)
669 .map_err(|_| Error::BorrowConflict),
670 }
671 }
672}
673
674pub struct Query<'a, E, M: Memory> {
678 db: QuerySource<'a, M>,
679 request: Request<'a>,
680 entity: PhantomData<E>,
681}
682impl<M: Memory> Database<M> {
683 #[must_use]
685 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
686 Query {
687 db: QuerySource::Direct(self),
688 entity: PhantomData,
689 request: Request::default(),
690 }
691 }
692}
693impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
694 pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
695 Self {
696 db: QuerySource::Session(db),
697 request: Request::default(),
698 entity: PhantomData,
699 }
700 }
701
702 #[must_use]
714 pub fn distinct(mut self) -> Self {
715 self.request.distinct = true;
716
717 self
718 }
719
720 #[must_use]
733 pub fn filter(
734 mut self,
735 field: &'a str,
736 comparison: Comparison,
737 value: impl Into<IndexValue<'a>>,
738 ) -> Self {
739 self.request
740 .filter(field, comparison, QueryOperand::Literal(value.into()));
741
742 self
743 }
744
745 #[must_use]
747 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
748 self.filter(field, Comparison::Eq, value)
749 }
750
751 #[must_use]
753 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
754 self.filter(field, Comparison::Ne, value)
755 }
756
757 #[must_use]
759 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
760 self.filter(field, Comparison::Lt, value)
761 }
762
763 #[must_use]
765 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
766 self.filter(field, Comparison::Le, value)
767 }
768
769 #[must_use]
771 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
772 self.filter(field, Comparison::Gt, value)
773 }
774
775 #[must_use]
777 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
778 self.filter(field, Comparison::Ge, value)
779 }
780
781 #[must_use]
789 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
790 self.request
791 .filter(left, comparison, QueryOperand::Field(right));
792
793 self
794 }
795
796 #[must_use]
801 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
802 self.request
803 .filter(field, comparison, QueryOperand::Length(length));
804
805 self
806 }
807
808 #[must_use]
811 pub fn filter_present(self, field: &'a str) -> Self {
812 self.filter(field, Comparison::Ne, IndexValue::Absent)
813 }
814
815 #[must_use]
818 pub fn filter_absent(self, field: &'a str) -> Self {
819 self.filter(field, Comparison::Eq, IndexValue::Absent)
820 }
821
822 #[must_use]
829 pub fn filter_between(
830 self,
831 field: &'a str,
832 lower: impl Into<IndexValue<'a>>,
833 upper: impl Into<IndexValue<'a>>,
834 ) -> Self {
835 self.filter(field, Comparison::Ge, lower)
836 .filter(field, Comparison::Le, upper)
837 }
838
839 #[must_use]
847 pub fn filter_not_between(
848 self,
849 field: &'a str,
850 lower: impl Into<IndexValue<'a>>,
851 upper: impl Into<IndexValue<'a>>,
852 ) -> Self {
853 self.filter_any(&[
854 (field, Comparison::Lt, lower.into()),
855 (field, Comparison::Gt, upper.into()),
856 ])
857 }
858
859 #[must_use]
864 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
865 self.filter_fields(field, Comparison::Ge, lower)
866 .filter_fields(field, Comparison::Le, upper)
867 }
868
869 #[must_use]
874 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
875 self.filter_any_operands(&[
876 (field, Comparison::Lt, QueryOperand::Field(lower)),
877 (field, Comparison::Gt, QueryOperand::Field(upper)),
878 ])
879 }
880
881 #[must_use]
889 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
890 self.request.or_clause(
891 alternatives
892 .iter()
893 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
894 );
895
896 self
897 }
898
899 #[must_use]
904 pub fn filter_any_operands(
905 mut self,
906 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
907 ) -> Self {
908 self.request.or_clause(alternatives.iter().copied());
909
910 self
911 }
912
913 #[must_use]
923 pub fn filter_in(
924 mut self,
925 field: &'a str,
926 values: &[impl Copy + Into<IndexValue<'a>>],
927 ) -> Self {
928 self.request.or_clause(
929 values
930 .iter()
931 .copied()
932 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
933 );
934
935 self
936 }
937
938 #[must_use]
946 pub fn filter_not_in(
947 mut self,
948 field: &'a str,
949 values: &[impl Copy + Into<IndexValue<'a>>],
950 ) -> Self {
951 self.request
952 .filter_not_in(field, values.iter().copied().map(Into::into));
953
954 self
955 }
956
957 #[must_use]
962 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
963 self.request.using_index(name, values);
964
965 self
966 }
967
968 #[must_use]
971 pub fn order_asc(mut self, field: &'a str) -> Self {
972 self.request.append_order(field, SortDirection::Ascending);
973
974 self
975 }
976
977 #[must_use]
980 pub fn order_desc(mut self, field: &'a str) -> Self {
981 self.request.append_order(field, SortDirection::Descending);
982
983 self
984 }
985
986 #[must_use]
997 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
998 self.request.order_by(fields);
999
1000 self
1001 }
1002
1003 #[must_use]
1008 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
1009 self.request.order_by_each(fields);
1010
1011 self
1012 }
1013
1014 #[must_use]
1016 pub fn descending(mut self) -> Self {
1017 self.request.descending = true;
1018
1019 self
1020 }
1021
1022 #[must_use]
1029 pub fn limit(mut self, rows: usize) -> Self {
1030 self.request.rows = rows;
1031
1032 self
1033 }
1034
1035 #[must_use]
1037 pub fn work_limit(mut self, candidates: usize) -> Self {
1038 self.request.work = candidates;
1039
1040 self
1041 }
1042
1043 #[cfg(feature = "test-support")]
1045 #[doc(hidden)]
1046 #[must_use]
1047 pub fn test_output_limit(mut self, bytes: usize) -> Self {
1048 self.request.bytes = bytes;
1049
1050 self
1051 }
1052
1053 #[must_use]
1055 pub fn after(mut self, cursor: &'a QueryCursor) -> Self {
1056 self.request.cursor = Some(cursor);
1057
1058 self
1059 }
1060
1061 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
1068 observe!(query, { self.entity_page() })
1069 }
1070
1071 fn entity_page(self) -> Result<QueryPage<E>, Error> {
1072 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
1073 }
1074
1075 pub fn first(self) -> Result<Option<E>, Error> {
1081 self.first_with(Self::entity_page)
1082 }
1083
1084 pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
1088 self.first_with(Self::projected_page::<R>)
1089 }
1090
1091 fn first_with<R>(
1092 self,
1093 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1094 ) -> Result<Option<R>, Error> {
1095 observe!(query, {
1096 let page = fetch(self.probe_matches(1)?)?;
1097 if page.rows.is_empty() && page.next.is_some() {
1098 return Err(Error::Limit);
1099 }
1100 Ok(page)
1101 })
1102 .map(|mut page| page.rows.pop())
1103 }
1104
1105 pub fn try_one(self) -> Result<Option<E>, Error> {
1112 self.try_one_with(Self::entity_page)
1113 }
1114
1115 pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
1121 self.try_one_with(Self::projected_page::<R>)
1122 }
1123
1124 fn try_one_with<R>(
1125 self,
1126 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1127 ) -> Result<Option<R>, Error> {
1128 observe!(query, {
1129 if self.request.cursor.is_some() {
1130 return Err(Error::InvalidQuery);
1131 }
1132 let page = fetch(self.probe_matches(2)?)?;
1133 if page.rows.len() == 2 {
1134 return Err(Error::MultipleMatches);
1135 }
1136 if page.next.is_some() {
1137 return Err(Error::Limit);
1138 }
1139
1140 Ok(page)
1141 })
1142 .map(|mut page| page.rows.pop())
1143 }
1144
1145 fn probe_matches(mut self, rows: usize) -> Result<Self, Error> {
1146 if !(1..=32).contains(&self.request.rows) {
1147 return Err(Error::Limit);
1148 }
1149
1150 self.request.single_result_probe = true;
1151
1152 Ok(self.limit(rows))
1153 }
1154
1155 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1165 observe!(query, { self.projected_page() })
1166 }
1167
1168 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1169 let raw = fetch_rows(
1170 &*self.db.read()?,
1171 E::SCHEMA,
1172 self.request,
1173 Some(R::definition()),
1174 )?;
1175
1176 raw.decode_projection()
1177 }
1178}
1179
1180fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u16, Error> {
1184 let TypeBody::Record(fields) = &output.body else {
1185 return Err(Error::InvalidQuery);
1186 };
1187 if fields.is_empty()
1188 || fields.len() > crate::schema::MAX_FIELDS
1189 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1190 {
1191 return Err(Error::InvalidQuery);
1192 }
1193 let mut source = TypeGraph::default();
1194 let mut target = TypeGraph::default();
1195 let mut mask = 0;
1196 for field in *fields {
1197 let position = entity
1198 .field_position(field.name)
1199 .ok_or(Error::InvalidQuery)?;
1200 let stored = &entity.fields[position];
1201 if stored.value != field.value || stored.optional != field.optional {
1202 return Err(Error::InvalidQuery);
1203 }
1204 source
1205 .include(stored.value)
1206 .map_err(|_| Error::InvalidQuery)?;
1207 target
1208 .include(field.value)
1209 .map_err(|_| Error::InvalidQuery)?;
1210 mask |= 1 << position;
1211 }
1212 if !source.contains(&target) {
1213 return Err(Error::InvalidQuery);
1214 }
1215
1216 Ok(mask)
1217}
1218
1219struct Term {
1220 tests_presence: bool,
1221 position: usize,
1222 comparison: Comparison,
1223 operand: TermOperand,
1224 or_next: bool,
1225}
1226
1227enum TermOperand {
1228 Literal {
1229 bytes: Vec<u8>,
1230 absent: bool,
1231 },
1232 Member {
1233 item: FieldType,
1234 needle: MemberNeedle,
1235 },
1236 Nested {
1237 member: crate::member::RecordMember,
1238 literal: Vec<u8>,
1239 absent: bool,
1240 },
1241 Field {
1242 right: usize,
1243 left_member: Option<crate::member::RecordMember>,
1244 right_member: Option<crate::member::RecordMember>,
1245 },
1246 Length {
1247 member: Option<crate::member::RecordMember>,
1248 threshold: u32,
1249 },
1250}
1251
1252enum MemberNeedle {
1253 Literal(Vec<u8>),
1254 Field(usize, Option<crate::member::RecordMember>),
1255}
1256
1257fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1260 match value {
1261 IndexValue::Text(text) => Some(text.as_bytes()),
1262 IndexValue::Blob(bytes) => Some(bytes),
1263 _ => None,
1264 }
1265}
1266
1267fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1268 match (left, right) {
1270 (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1271 a == b
1272 }
1273 _ => left == right,
1274 }
1275}
1276
1277fn length_limit(field: FieldType) -> Option<u32> {
1278 match key::operand_type(field) {
1279 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1280 FieldType::List { max_items, .. } => Some(max_items),
1281 FieldType::Named(link) => match (link.definition)().body {
1282 TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1283 _ => None,
1284 },
1285 _ => None,
1286 }
1287}
1288
1289fn member_type(field: FieldType) -> Option<FieldType> {
1290 match key::operand_type(field) {
1291 FieldType::List { item, .. } => Some(*item),
1292 FieldType::Named(link) => match (link.definition)().body {
1293 TypeBody::Set { item, .. } => Some(item),
1294 _ => None,
1295 },
1296 _ => None,
1297 }
1298}
1299
1300fn contains_member(
1302 span: &[u8],
1303 optional: bool,
1304 item: FieldType,
1305 needle: IndexValue<'_>,
1306) -> Result<bool, Error> {
1307 let mut reader = Decoder::new(span)?;
1308 if optional && !reader.boolean()? {
1309 return Ok(false);
1310 }
1311 for _ in 0..reader.nat32()? {
1312 let value = IndexValue::read(&mut reader, item)?;
1313 if equal_values(value, needle) {
1314 return Ok(true);
1315 }
1316 }
1317
1318 Ok(false)
1319}
1320
1321fn projection_positions(mut mask: u16) -> impl Iterator<Item = usize> {
1324 std::iter::from_fn(move || {
1325 if mask == 0 {
1326 return None;
1327 }
1328 let position = mask.trailing_zeros() as usize;
1329 mask &= mask - 1;
1330 Some(position)
1331 })
1332}
1333
1334fn admit_ordered_fields(entity: &EntitySchema, mask: u16) -> Result<(), Error> {
1335 for i in projection_positions(mask) {
1336 if !key::supports(entity.fields[i].value) {
1337 return Err(Error::InvalidQuery);
1338 }
1339 }
1340
1341 Ok(())
1342}
1343
1344fn comparison_key(
1346 entity: &EntitySchema,
1347 mask: u16,
1348 values: &[IndexValue<'_>],
1349 scratch: &mut Vec<u8>,
1350) -> Result<(), Error> {
1351 build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1352}
1353
1354fn build_comparison_key<'a>(
1355 entity: &EntitySchema,
1356 mask: u16,
1357 key: &mut Vec<u8>,
1358 mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1359) -> Result<(), Error> {
1360 key.clear();
1361 for i in projection_positions(mask) {
1362 let field = &entity.fields[i];
1363 value(i, field)?.append_component(field.optional, key);
1364 if key.len() > MAX_COMPARISON_KEY {
1365 return Err(Error::Limit);
1366 }
1367 }
1368
1369 Ok(())
1370}
1371
1372fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1373 if size > limit {
1374 return Err(Error::RowTooLarge);
1375 }
1376 if size > limit - *used {
1377 return Err(Error::Limit);
1378 }
1379 *used += size;
1380
1381 Ok(())
1382}
1383
1384fn projection_size(spans: &[(u16, u16)], mask: u16) -> usize {
1386 projection_positions(mask)
1387 .map(|i| {
1388 let (start, end) = spans[i];
1389 usize::from(end - start)
1390 })
1391 .sum()
1392}
1393
1394fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u16, size: usize) -> Vec<u8> {
1395 let mut output = Vec::with_capacity(size);
1396 for i in projection_positions(mask) {
1397 let (start, end) = spans[i];
1398 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1399 }
1400
1401 output
1402}
1403#[derive(Clone, Copy)]
1404enum PlanOutput {
1405 Rows,
1406 Aggregate { grouped: bool },
1407}
1408
1409struct Plan<'a> {
1410 primary: usize,
1411 index: Option<&'a IndexSchema>,
1412 prefix: Vec<u8>,
1413 fixed_components: usize,
1414 terms: Vec<Term>,
1415 selected: u16,
1416 span_fields: u16,
1418 binding: [u8; 32],
1419 projection: Option<u16>,
1420 distinct: distinct::Strategy,
1421 sort: Option<Vec<order::SortField>>,
1422 descending: bool,
1423}
1424impl<'a> Plan<'a> {
1425 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1426 self.terms.split_inclusive(|term| !term.or_next)
1427 }
1428
1429 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1430 self.index = Some(path.index);
1431 self.prefix = path.prefix;
1432 self.fixed_components = path.fixed;
1433 self.selected |= entity.key_fields();
1434 }
1435
1436 fn admit(
1437 entity: &'a EntitySchema,
1438 request: &Request<'_>,
1439 schema: [u8; 32],
1440 incarnation: [u8; 16],
1441 projection: Option<&TypeSchema>,
1442 output: PlanOutput,
1443 ) -> Result<Self, Error> {
1444 if request.over_limit
1445 || !(1..=32).contains(&request.rows)
1446 || !(1..=MAX_WORK).contains(&request.work)
1447 || !(1..=MAX_OUTPUT).contains(&request.bytes)
1448 {
1449 return Err(Error::Limit);
1450 }
1451 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1452 {
1453 return Err(Error::InvalidQuery);
1454 }
1455 for value in request
1457 .predicates
1458 .iter()
1459 .filter_map(|p| match &p.operand {
1460 QueryOperand::Literal(value) => Some(value),
1461 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1462 })
1463 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1464 {
1465 if match value {
1466 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1467 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1468 _ => false,
1469 } {
1470 return Err(Error::Limit);
1471 }
1472 }
1473 let primary = entity
1474 .field_position(entity.primary_key)
1475 .filter(|&i| !entity.fields[i].optional)
1476 .ok_or(Error::InvalidQuery)?;
1477 let mut plan = Self {
1478 primary,
1479 index: None,
1480 prefix: prefix(2, entity.id),
1481 fixed_components: 0,
1482 terms: Vec::new(),
1483 selected: 1 << primary,
1484 span_fields: 0,
1485 binding: [0; 32],
1486 projection: projection
1487 .map(|output| admit_projection(entity, output))
1488 .transpose()?,
1489 distinct: distinct::Strategy::Identity,
1490 sort: None,
1491 descending: request.descending ^ request.primary_descending(entity),
1492 };
1493 for predicate in &request.predicates {
1494 let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
1495 let field = &entity.fields[position];
1496 let member = if predicate.comparison == Comparison::Contains {
1497 member_type(field.value)
1498 } else {
1499 None
1500 };
1501 let operand = match (predicate.operand, record_member) {
1502 (QueryOperand::Literal(value), Some(member)) => {
1503 if !predicate.comparison.supports_record_member() {
1504 return Err(Error::InvalidQuery);
1505 }
1506 let leaf = member.field();
1507 predicate.comparison.admit(
1508 leaf.value,
1509 field.optional || leaf.optional,
1510 value,
1511 )?;
1512 let mut literal = Vec::new();
1513 value.append_component(false, &mut literal);
1514 plan.span_fields |= 1 << position;
1515 TermOperand::Nested {
1516 member,
1517 literal,
1518 absent: value == IndexValue::Absent,
1519 }
1520 }
1521 (QueryOperand::Length(length), member) => {
1522 let selected = member.map_or(field.value, |m| m.field().value);
1523 if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1524 return Err(Error::InvalidQuery);
1525 }
1526 plan.span_fields |= 1 << position;
1527
1528 TermOperand::Length {
1529 member,
1530 threshold: length,
1531 }
1532 }
1533 (QueryOperand::Field(name), left_member) => {
1534 let (right, right_member) = crate::member::resolve_field(entity, name)?;
1535 if (left_member.is_some() || right_member.is_some())
1536 && member.is_none()
1537 && !predicate.comparison.supports_record_member()
1538 {
1539 return Err(Error::InvalidQuery);
1540 }
1541 let right_type =
1542 right_member.map_or(entity.fields[right].value, |m| m.field().value);
1543 let left_type =
1544 left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1545 let compatible = left_type == right_type
1546 || matches!(
1547 (left_type, right_type),
1548 (FieldType::Text { .. }, FieldType::Text { .. })
1549 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1550 );
1551 if !compatible
1552 || !key::supports(left_type)
1553 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1554 {
1555 return Err(Error::InvalidQuery);
1556 }
1557 if right_member.is_some() {
1558 plan.span_fields |= 1 << right;
1559 } else {
1560 plan.selected |= 1 << right;
1561 }
1562
1563 if let Some(item) = member {
1564 plan.span_fields |= 1 << position;
1565
1566 TermOperand::Member {
1567 item,
1568 needle: MemberNeedle::Field(right, right_member),
1569 }
1570 } else {
1571 if left_member.is_some() {
1572 plan.span_fields |= 1 << position;
1573 } else {
1574 plan.selected |= 1 << position;
1575 }
1576 TermOperand::Field {
1577 right,
1578 left_member,
1579 right_member,
1580 }
1581 }
1582 }
1583 (QueryOperand::Literal(value), None) => {
1584 if let Some(item) = member {
1585 if !key::supports(item) {
1586 return Err(Error::InvalidQuery);
1587 }
1588 value.admit(item, false)?;
1589 let mut bytes = Vec::new();
1590 value.append_component(false, &mut bytes);
1591 plan.span_fields |= 1 << position;
1592
1593 TermOperand::Member {
1594 item,
1595 needle: MemberNeedle::Literal(bytes),
1596 }
1597 } else {
1598 let absent = value == IndexValue::Absent;
1599 if key::supports(field.value) {
1600 plan.selected |= 1 << position;
1601 } else if absent
1602 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1603 {
1604 plan.span_fields |= 1 << position;
1605 } else {
1606 return Err(Error::InvalidQuery);
1607 }
1608 predicate
1609 .comparison
1610 .admit(field.value, field.optional, value)?;
1611 let mut bytes = Vec::new();
1612 value.append_component(field.optional, &mut bytes);
1613
1614 TermOperand::Literal { bytes, absent }
1615 }
1616 }
1617 };
1618 plan.terms.push(Term {
1619 tests_presence: predicate.tests_presence(entity, &operand),
1620 position,
1621 comparison: predicate.comparison,
1622 operand,
1623 or_next: predicate.or_next,
1624 });
1625 }
1626 match order::select(entity, request, output)? {
1629 order::Path::Primary => {}
1630 order::Path::Index(path) => plan.use_index(entity, path),
1631 order::Path::Sort(fields) => {
1632 order::select_filtered_path(entity, request, &mut plan, None)?;
1633 for field in &fields {
1634 if field.member.is_some() {
1635 plan.span_fields |= 1 << field.position;
1636 } else {
1637 plan.selected |= 1 << field.position;
1638 }
1639 }
1640 plan.sort = Some(fields);
1641 }
1642 }
1643 if request.distinct {
1644 plan.distinct = distinct::admit(entity, request, &plan)?;
1645 if let distinct::Strategy::Complete { key_fields } = plan.distinct {
1646 plan.selected |= key_fields;
1647 }
1648 }
1649 let mut hash = Sha256::new();
1650 hash.update(b"ic-db:query:v1\0");
1651 hash.update(schema);
1652 hash.update(incarnation);
1653 hash.update([u8::from(request.descending)]);
1654 hash.update((plan.prefix.len() as u32).to_le_bytes());
1655 hash.update(&plan.prefix);
1656 for term in &plan.terms {
1657 hash.update([term.position as u8, term.comparison as u8]);
1658
1659 match &term.operand {
1660 TermOperand::Nested {
1661 member,
1662 literal,
1663 absent,
1664 } => {
1665 hash.update((u32::MAX - 2).to_le_bytes());
1666 hash.update([member.position() as u8, u8::from(*absent)]);
1667 hash.update((literal.len() as u32).to_le_bytes());
1668 hash.update(literal);
1669 }
1670 TermOperand::Literal { bytes, .. }
1671 | TermOperand::Member {
1672 needle: MemberNeedle::Literal(bytes),
1673 ..
1674 } => {
1675 hash.update((bytes.len() as u32).to_le_bytes());
1676 hash.update(bytes);
1677 }
1678 TermOperand::Length { member, threshold } => {
1679 if let Some(member) = member {
1680 hash.update((u32::MAX - 3).to_le_bytes());
1681 hash.update([member.position() as u8]);
1682 } else {
1683 hash.update((u32::MAX - 1).to_le_bytes());
1684 }
1685 hash.update(threshold.to_le_bytes());
1686 }
1687 TermOperand::Field {
1688 right,
1689 left_member: None,
1690 right_member: None,
1691 }
1692 | TermOperand::Member {
1693 needle: MemberNeedle::Field(right, None),
1694 ..
1695 } => {
1696 hash.update(u32::MAX.to_le_bytes());
1698 hash.update([*right as u8]);
1699 }
1700 TermOperand::Member {
1701 needle: MemberNeedle::Field(right, Some(member)),
1702 ..
1703 } => {
1704 hash.update((u32::MAX - 4).to_le_bytes());
1705 hash.update([u8::MAX, *right as u8, member.position() as u8]);
1706 }
1707 TermOperand::Field {
1708 right,
1709 left_member,
1710 right_member,
1711 } => {
1712 hash.update((u32::MAX - 4).to_le_bytes());
1713 let slot = |member: &Option<crate::member::RecordMember>| {
1714 member.map_or(u8::MAX, |m| m.position() as u8)
1715 };
1716 hash.update([slot(left_member), *right as u8, slot(right_member)]);
1717 }
1718 }
1719 }
1720 let clauses = plan
1723 .terms
1724 .iter()
1725 .enumerate()
1726 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1727 if clauses != 0 {
1728 hash.update(b"or-clauses\0");
1729 hash.update([clauses]);
1730 }
1731 if let Some(order) = &request.order {
1732 hash.update(b"order\0");
1733 hash.update([order.len() as u8]);
1734 for name in order {
1735 if let Some(position) = entity.field_position(name) {
1737 hash.update([position as u8]);
1738 } else {
1739 hash.update([u8::MAX, name.len() as u8]);
1741 hash.update(name.as_bytes());
1742 }
1743 }
1744 }
1745 if request.order_descending != 0 {
1746 hash.update(b"order-directions\0");
1747 hash.update([request.order_descending]);
1748 }
1749 if let Some(mask) = plan.projection {
1752 hash.update(b"projection\0");
1753 hash.update(mask.to_le_bytes());
1754 }
1755 if request.distinct {
1756 hash.update(b"distinct\0");
1757 }
1758 plan.binding = hash.finalize().into();
1759 if let Some(cursor) = request.cursor {
1760 if cursor.binding != plan.binding {
1761 return Err(Error::InvalidCursor);
1762 }
1763 plan.validate_position(entity, cursor)
1764 .map_err(|_| Error::InvalidCursor)?;
1765 }
1766
1767 Ok(plan)
1768 }
1769
1770 fn validate_position(&self, entity: &EntitySchema, cursor: &QueryCursor) -> Result<(), Error> {
1771 if cursor.resume == Resume::AfterUnemittedClass
1772 && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
1773 {
1774 return Err(Error::InvalidCursor);
1775 }
1776 let bytes = cursor.position.as_slice();
1777 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
1778 return Err(Error::InvalidCursor);
1779 }
1780 if let Some(index) = self.index {
1781 let mut remaining = bytes
1782 .get(INDEX_PREFIX_BYTES..)
1783 .ok_or(Error::InvalidCursor)?;
1784 for name in index.fields {
1785 consume_index_component(entity, index, name, &mut remaining)?;
1786 }
1787 if !index.unique {
1788 key::consume(&mut remaining, entity.key_type()?)?;
1789 }
1790 if !remaining.is_empty() {
1791 return Err(Error::InvalidCursor);
1792 }
1793 } else {
1794 RowKey::decode(
1795 bytes
1796 .get(ENTITY_PREFIX_BYTES..)
1797 .ok_or(Error::InvalidCursor)?,
1798 entity.key_type()?,
1799 )?;
1800 }
1801
1802 Ok(())
1803 }
1804
1805 fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
1806 QueryCursor {
1807 binding: self.binding,
1808 position: position.to_vec(),
1809 resume,
1810 }
1811 }
1812}
1813
1814fn consume_index_component(
1816 entity: &EntitySchema,
1817 index: &IndexSchema,
1818 name: &str,
1819 remaining: &mut &[u8],
1820) -> Result<(), Error> {
1821 let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
1822
1823 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
1824}
1825
1826#[inline(never)]
1829#[expect(
1830 clippy::needless_pass_by_value,
1831 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1832)]
1833fn fetch_rows<M: Memory>(
1834 db: &Database<M>,
1835 entity: &EntitySchema,
1836 request: Request<'_>,
1837 projection: Option<&TypeSchema>,
1838) -> Result<QueryPage<Vec<u8>>, Error> {
1839 db.schema.admits(entity)?;
1840 let plan = Plan::admit(
1841 entity,
1842 &request,
1843 db.schema.fingerprint(),
1844 db.incarnation,
1845 projection,
1846 PlanOutput::Rows,
1847 )?;
1848
1849 execute(&db.map, entity, &request, &plan, None)
1850}
1851
1852fn execute<M: Memory>(
1853 map: &Map<M>,
1854 entity: &EntitySchema,
1855 request: &Request<'_>,
1856 plan: &Plan<'_>,
1857 mut aggregate: Option<aggregate::Accumulator<'_>>,
1858) -> Result<QueryPage<Vec<u8>>, Error> {
1859 execute_inner(
1860 map,
1861 entity,
1862 request,
1863 plan,
1864 range::bounds(entity, request, plan)?,
1865 aggregate.as_mut(),
1866 None,
1867 )
1868}
1869
1870const STEP_INPUT_BYTES: usize = 64 * 1024;
1873const CANDIDATE_BYTES: usize = crate::codec::MAX_ROW_BYTES + 2 * crate::MAX_INDEX_KEY_BYTES;
1874
1875fn execute_inner<M: Memory>(
1876 map: &Map<M>,
1877 entity: &EntitySchema,
1878 request: &Request<'_>,
1879 plan: &Plan<'_>,
1880 bounds: Option<range::Bounds>,
1881 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1882 mut input_bytes: Option<&mut usize>,
1883) -> Result<QueryPage<Vec<u8>>, Error> {
1884 let mut page = QueryPage {
1885 rows: Vec::new(),
1886 next: None,
1887 examined: 0,
1888 fetched: 0,
1889 output_bytes: 0,
1890 };
1891 let Some(bounds) = bounds else {
1892 return Ok(page);
1893 };
1894 let terminal = range::terminal_key(&bounds, plan.descending);
1895 let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
1896 let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
1897 Some(distinct::Collection::new(
1898 plan.projection.ok_or(Error::InvalidQuery)?,
1899 key_fields,
1900 ))
1901 } else {
1902 None
1903 };
1904 let mut sorted = plan
1905 .sort
1906 .as_ref()
1907 .map(|_| sort::Collection::new(request, plan.distinct));
1908 let mut component = Vec::new();
1909 let mut right_component = Vec::new();
1910 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
1912 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1913 } else {
1914 None
1915 };
1916 let primary_type = entity.fields[plan.primary].value;
1917 let needs_spans = plan.index.is_some()
1918 || plan.span_fields != 0
1919 || match &aggregate {
1920 Some(accumulator) => accumulator.needs_spans(),
1921 None => plan.projection.is_some(),
1922 };
1923 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1925 while let Some(entry) = if plan.descending {
1926 entries.next_back()
1927 } else {
1928 entries.next()
1929 } {
1930 if request.work == 0 {
1934 return Err(Error::Limit);
1935 }
1936 page.examined += 1;
1937 let stored_key = entry.key();
1938 let mut read_bytes = stored_key.len();
1939 let (owner, bytes) = if plan.index.is_some() {
1940 let owner_bytes = entry.value();
1941 read_bytes += owner_bytes.len();
1942 let owner = RowKey::decode(&owner_bytes, primary_type)?;
1943 let bytes = map.get(&row_key(entity.id, owner)).ok_or(Error::Corrupt)?;
1944
1945 (owner, bytes)
1946 } else {
1947 (
1948 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
1949 entry.value(),
1950 )
1951 };
1952 if let Some(used) = input_bytes.as_deref_mut() {
1953 read_bytes += bytes.len();
1954 if read_bytes > CANDIDATE_BYTES {
1955 return Err(Error::Corrupt);
1956 }
1957 *used += read_bytes;
1958 }
1959 page.fetched += 1;
1960 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
1961 entity.inspect_fields(
1962 &bytes,
1963 plan.selected,
1964 &mut values,
1965 needs_spans.then_some(&mut spans),
1966 )?;
1967 if RowKey::from_index(values[plan.primary])? != owner {
1968 return Err(Error::Corrupt);
1969 }
1970 if plan.index.is_some() {
1971 validate_index_entry(
1972 entity,
1973 &entity.row_info(&values, &bytes, &spans)?,
1974 owner,
1975 stored_key,
1976 )?;
1977 }
1978 let read = |position: usize, member: Option<crate::member::RecordMember>| {
1979 if let Some(member) = member {
1980 let (start, end) = spans[position];
1981 member.read(
1982 &bytes[usize::from(start)..usize::from(end)],
1983 entity.fields[position].optional,
1984 )
1985 } else {
1986 Ok(values[position])
1987 }
1988 };
1989 let mut accepts = |term: &Term, supplied: &QueryOperand<'_>| -> Result<bool, Error> {
1990 let mut value = values[term.position];
1991 component.clear();
1992 let (operand, optional) = match &term.operand {
1993 TermOperand::Nested {
1994 member,
1995 literal,
1996 absent,
1997 } => {
1998 value = read(term.position, Some(*member))?;
1999 if *absent {
2000 return Ok(term.comparison.accepts_absent(value == IndexValue::Absent));
2001 }
2002 (Some(literal.as_slice()), false)
2003 }
2004 TermOperand::Literal { absent: true, .. } => {
2005 let absent = if plan.span_fields & (1 << term.position) != 0 {
2006 bytes[usize::from(spans[term.position].0)] == 0
2007 } else {
2008 value == IndexValue::Absent
2009 };
2010
2011 return Ok(term.comparison.accepts_absent(absent));
2012 }
2013 TermOperand::Member { item, needle } => {
2014 let needle = match (needle, supplied) {
2015 (MemberNeedle::Literal(_), QueryOperand::Literal(value)) => *value,
2016 (MemberNeedle::Field(right, member), QueryOperand::Field(_)) => {
2017 read(*right, *member)?
2018 }
2019 _ => return Err(Error::Corrupt),
2020 };
2021 if needle == IndexValue::Absent {
2022 return Ok(false);
2023 }
2024 let (start, end) = spans[term.position];
2025
2026 return contains_member(
2027 &bytes[usize::from(start)..usize::from(end)],
2028 entity.fields[term.position].optional,
2029 *item,
2030 needle,
2031 );
2032 }
2033 TermOperand::Length { member, threshold } => {
2034 let (start, end) = spans[term.position];
2035 let span = &bytes[usize::from(start)..usize::from(end)];
2036 let optional = entity.fields[term.position].optional;
2037 let actual = if let Some(member) = member {
2038 match member.read(span, optional)? {
2039 IndexValue::Absent => None,
2040 value => Some(scalar_bytes(value).ok_or(Error::Corrupt)?.len() as u32),
2041 }
2042 } else {
2043 crate::codec::validated_length(span, optional)
2044 };
2045
2046 return Ok(term.comparison.accepts_length(actual, *threshold));
2047 }
2048 TermOperand::Literal {
2049 bytes,
2050 absent: false,
2051 } => (
2052 Some(bytes.as_slice()),
2053 entity.fields[term.position].optional,
2054 ),
2055 TermOperand::Field {
2056 right,
2057 left_member,
2058 right_member,
2059 } => {
2060 value = read(term.position, *left_member)?;
2061 let rhs = read(*right, *right_member)?;
2062 if value == IndexValue::Absent || rhs == IndexValue::Absent {
2063 return Ok(term.comparison.accepts_absent(value == rhs));
2064 }
2065 if let Some(matches) = term.comparison.accepts_values(value, rhs) {
2066 return Ok(matches);
2067 }
2068 right_component.clear();
2069 rhs.append_component(false, &mut right_component);
2070
2071 (Some(right_component.as_slice()), false)
2072 }
2073 };
2074 if let QueryOperand::Literal(right) = supplied
2075 && let Some(matches) = term.comparison.accepts_values(value, *right)
2076 {
2077 return Ok(matches);
2078 }
2079 value.append_component(optional, &mut component);
2080
2081 Ok(term.comparison.accepts(
2082 (value != IndexValue::Absent).then_some(component.as_slice()),
2083 operand,
2084 optional,
2085 ))
2086 };
2087 let matches = 'matches: {
2088 let mut clause_matches = false;
2089 for (term, predicate) in plan.terms.iter().zip(&request.predicates) {
2090 clause_matches = clause_matches || accepts(term, &predicate.operand)?;
2091 if !term.or_next {
2092 if !clause_matches {
2093 break 'matches false;
2094 }
2095 clause_matches = false;
2096 }
2097 }
2098
2099 true
2100 };
2101 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
2102 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2103 if matches && let Some(accumulator) = aggregate.as_mut() {
2104 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2105 if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
2106 return Ok(page);
2108 }
2109 } else if matches && let Some(collection) = collected.as_mut() {
2110 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2111 if request.single_result_probe && collection.rows.len() == request.rows {
2114 break;
2115 }
2116 } else if matches && let Some(collection) = sorted.as_mut() {
2117 collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2118 } else if matches && !duplicate {
2119 let size = plan
2120 .projection
2121 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2122 if size > request.bytes {
2123 return Err(Error::RowTooLarge);
2124 }
2125 if size > request.bytes - page.output_bytes {
2126 page.next = Some(plan.cursor(stored_key, Resume::Retry));
2127
2128 return Ok(page);
2129 }
2130 page.output_bytes += size;
2131 if let Some(mask) = plan.projection {
2132 page.rows.push(copy_projection(&bytes, &spans, mask, size));
2133 } else {
2134 page.rows.push(bytes);
2135 }
2136 if plan.distinct == distinct::Strategy::FirstMatch {
2137 return Ok(page);
2138 }
2139 if let Some(boundary) = boundary {
2140 previous = Some(boundary.to_vec());
2141 }
2142 }
2143 if page.rows.len() == request.rows
2144 || page.examined == request.work
2145 || input_bytes
2146 .as_deref()
2147 .is_some_and(|used| *used > STEP_INPUT_BYTES - CANDIDATE_BYTES)
2148 {
2149 if terminal == Some(stored_key) {
2150 break;
2151 }
2152 if (aggregate.is_some() && input_bytes.is_none())
2153 || collected.is_some()
2154 || sorted.is_some()
2155 {
2156 return Err(Error::Limit);
2159 }
2160 let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
2161 Resume::AfterUnemittedClass
2162 } else {
2163 Resume::After
2164 };
2165 page.next = Some(plan.cursor(stored_key, resume));
2166
2167 return Ok(page);
2168 }
2169 }
2170 if let Some(collection) = collected {
2171 page.output_bytes = collection.output_bytes;
2172 page.rows = collection.rows;
2173 }
2174 if let Some(collection) = sorted {
2175 collection.finish(request.bytes, &mut page)?;
2176 }
2177
2178 Ok(page)
2179}