1mod aggregate;
3mod distinct;
4mod order;
5mod range;
6mod sort;
7pub use aggregate::jobs::{AggregateJobs, GroupCursor, GroupPage, JobHandle, JobOutcome, JobStep};
8pub use aggregate::{Aggregate, GroupCount, GroupOrder, GroupValue};
9
10use super::{Database, Map, prefix, row_key, validate_index_entry};
11use crate::{
12 Entity, EntitySchema, Error, FieldType, IndexSchema, IndexValue, TypeBody, TypeSchema, Value,
13 codec::Decoder, key, primary::RowKey, types::TypeGraph,
14};
15use ic_storage::Memory;
16use sha2::{Digest, Sha256};
17use std::marker::PhantomData;
18
19const MAX_TERMS: usize = 8;
20const MAX_WORK: usize = 512;
21const MAX_OUTPUT: usize = 128 * 1024;
22const MAX_COMPARISON_KEY: usize = 4096;
23const MAX_DISTINCT_VALUES: usize = 32;
24const MAX_STATE_BYTES: usize = 128 * 1024;
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum SortDirection {
29 Ascending,
31 Descending,
33}
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37#[repr(u8)]
38pub enum Comparison {
39 Eq = 0,
41 Ne = 1,
43 Lt = 2,
45 Le = 3,
47 Gt = 4,
49 Ge = 5,
51 StartsWith = 6,
55 EndsWith = 7,
58 Contains = 8,
62}
63
64impl Comparison {
65 fn is_relational(self) -> bool {
66 matches!(
67 self,
68 Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge
69 )
70 }
71
72 fn supports_scalar(self, field: FieldType) -> bool {
73 self.is_relational()
74 || matches!(
75 key::operand_type(field),
76 FieldType::Text { .. } | FieldType::Blob { .. }
77 )
78 }
79
80 fn admit(self, field: FieldType, optional: bool, value: IndexValue<'_>) -> Result<(), Error> {
81 value.admit(field, optional)?;
82 if !self.supports_scalar(field) {
83 return Err(Error::InvalidQuery);
84 }
85 if value == IndexValue::Absent && !matches!(self, Self::Eq | Self::Ne) {
86 return Err(Error::InvalidOperand);
87 }
88 Ok(())
89 }
90
91 fn accepts(self, actual: Option<&[u8]>, operand: Option<&[u8]>, optional: bool) -> bool {
92 if actual.is_none() {
93 return self.accepts_absent(operand.is_none());
94 }
95 match self {
96 Self::Eq => actual == operand,
97 Self::Ne => actual != operand,
98 Self::StartsWith | Self::EndsWith | Self::Contains => {
99 fn content(key: &[u8], optional: bool) -> Option<&[u8]> {
102 key.get(usize::from(optional)..)?.strip_suffix(&[0, 0])
103 }
104 actual
105 .and_then(|key| content(key, optional))
106 .zip(operand.and_then(|key| content(key, optional)))
107 .is_some_and(|(actual, operand)| match self {
108 Self::StartsWith => actual.starts_with(operand),
111 Self::EndsWith => actual
115 .strip_suffix(operand)
116 .is_some_and(|prefix| prefix.last() != Some(&0)),
117 _ => contains_component(actual, operand),
118 })
119 }
120 _ if actual.is_none() || operand.is_none() => false,
121 Self::Lt => actual < operand,
122 Self::Le => actual <= operand,
123 Self::Gt => actual > operand,
124 Self::Ge => actual >= operand,
125 }
126 }
127
128 fn accepts_absent(self, other_absent: bool) -> bool {
131 match self {
132 Self::Eq => other_absent,
133 Self::Ne => !other_absent,
134 _ => false,
135 }
136 }
137}
138
139fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
141 let Some(start) = memchr::memmem::find(actual, needle) else {
142 return false;
143 };
144 if start == 0 || actual[start - 1] != 0 {
145 return true;
146 }
147 fn raw(content: &[u8]) -> Vec<u8> {
151 let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
152 let mut encoded = content.iter();
153 while let Some(&byte) = encoded.next() {
154 bytes.push(byte);
155 if byte == 0 {
156 encoded.next();
157 }
158 }
159 bytes
160 }
161 memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
162}
163
164#[derive(Clone, Debug, PartialEq, Eq)]
168pub struct QueryCursor {
169 binding: [u8; 32],
170 position: Vec<u8>,
171 inclusive: bool,
172}
173impl QueryCursor {
174 pub(super) const MAX_ENCODED_BYTES: usize = 34 + crate::MAX_INDEX_KEY_BYTES;
175
176 #[must_use]
178 pub fn to_bytes(&self) -> Vec<u8> {
179 let mut bytes = vec![1, u8::from(self.inclusive)];
180 bytes.extend(self.binding);
181 bytes.extend(&self.position);
182 bytes
183 }
184 pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
188 if !(35..=Self::MAX_ENCODED_BYTES).contains(&bytes.len()) || bytes[0] != 1 || bytes[1] > 1 {
189 return Err(Error::InvalidCursor);
190 }
191 Ok(Self {
192 binding: bytes[2..34].try_into().map_err(|_| Error::InvalidCursor)?,
193 position: bytes[34..].to_vec(),
194 inclusive: bytes[1] == 1,
195 })
196 }
197}
198
199#[derive(Debug)]
202pub struct QueryPage<T> {
203 pub rows: Vec<T>,
205 pub next: Option<QueryCursor>,
207 pub examined: usize,
209 pub fetched: usize,
211 pub output_bytes: usize,
213}
214
215impl QueryPage<Vec<u8>> {
216 #[inline(never)]
217 pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
218 Ok(QueryPage {
219 rows: self
220 .rows
221 .iter()
222 .map(|bytes| E::decode(bytes))
223 .collect::<Result<_, _>>()?,
224 next: self.next,
225 examined: self.examined,
226 fetched: self.fetched,
227 output_bytes: self.output_bytes,
228 })
229 }
230
231 #[inline(never)]
232 fn decode_projection<R: Value>(self) -> Result<QueryPage<R>, Error> {
233 Ok(QueryPage {
234 rows: self
235 .rows
236 .iter()
237 .map(|bytes| {
238 let mut reader = Decoder::new(bytes)?;
239 let row = R::decode_from(&mut reader)?;
241 reader.finish()?;
242 Ok(row)
243 })
244 .collect::<Result<_, Error>>()?,
245 next: self.next,
246 examined: self.examined,
247 fetched: self.fetched,
248 output_bytes: self.output_bytes,
249 })
250 }
251}
252
253#[derive(Clone, Copy, Debug, PartialEq, Eq)]
255pub enum QueryOperand<'a> {
256 Literal(IndexValue<'a>),
258 Length(u32),
260 Field(&'a str),
262}
263
264struct Predicate<'a> {
265 field: &'a str,
266 comparison: Comparison,
267 operand: QueryOperand<'a>,
268 or_next: bool,
270}
271struct Request<'a> {
272 groups: aggregate::GroupRequest<'a>,
273 predicates: Vec<Predicate<'a>>,
274 index: Option<(&'a str, Vec<IndexValue<'a>>)>,
275 order: Option<Vec<&'a str>>,
276 order_descending: u8,
277 descending: bool,
278 distinct: bool,
279 rows: usize,
280 work: usize,
281 bytes: usize,
282 cursor: Option<&'a QueryCursor>,
283 over_limit: bool,
284}
285
286impl Default for Request<'_> {
287 fn default() -> Self {
288 Self {
289 groups: aggregate::GroupRequest::default(),
290 predicates: Vec::new(),
291 index: None,
292 order: None,
293 order_descending: 0,
294 descending: false,
295 distinct: false,
296 rows: 32,
297 work: 128,
298 bytes: MAX_OUTPUT,
299 cursor: None,
300 over_limit: false,
301 }
302 }
303}
304
305impl<'a> Request<'a> {
308 #[inline(never)]
309 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
310 if self.predicates.len() == MAX_TERMS {
311 self.over_limit = true;
312 } else {
313 self.predicates.push(Predicate {
314 field,
315 comparison,
316 operand,
317 or_next: false,
318 });
319 }
320 }
321
322 #[inline(never)]
323 fn or_clause(
324 &mut self,
325 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
326 ) {
327 let count = alternatives.len();
328 if count == 0 || count > MAX_TERMS - self.predicates.len() {
329 self.over_limit = true;
330 } else {
331 self.predicates.extend(alternatives.enumerate().map(
332 |(i, (field, comparison, operand))| Predicate {
333 field,
334 comparison,
335 operand,
336 or_next: i + 1 < count,
337 },
338 ));
339 }
340 }
341
342 #[inline(never)]
343 fn filter_not_in(&mut self, field: &'a str, values: &[IndexValue<'a>]) {
344 if values.is_empty() || values.len() > MAX_TERMS - self.predicates.len() {
345 self.over_limit = true;
346 return;
347 }
348 for &value in values {
349 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
350 }
351 }
352
353 #[inline(never)]
354 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
355 if values.len() > 4 {
356 self.over_limit = true;
357 } else {
358 self.index = Some((name, values.to_vec()));
359 }
360 }
361
362 #[inline(never)]
363 fn order_by(&mut self, fields: &[&'a str]) {
364 self.order_descending = 0;
365 if fields.len() > 4 {
366 self.over_limit = true;
367 } else {
368 self.order = Some(fields.to_vec());
369 }
370 }
371
372 #[inline(never)]
373 fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
374 if fields.len() > 4 {
375 self.over_limit = true;
376 return;
377 }
378 self.order = Some(fields.iter().map(|(name, _)| *name).collect());
379 self.order_descending = fields
380 .iter()
381 .enumerate()
382 .fold(0, |mask, (i, (_, direction))| {
383 mask | (u8::from(*direction == SortDirection::Descending) << i)
384 });
385 }
386
387 fn primary_descending(&self, entity: &EntitySchema) -> bool {
388 self.order_descending != 0
389 && self.order.as_ref().is_some_and(|fields| {
390 fields.last() == Some(&entity.primary_key)
391 && self.order_descending & (1 << (fields.len() - 1)) != 0
392 })
393 }
394}
395
396pub(super) fn source_page<M: Memory>(
398 map: &Map<M>,
399 entity: &EntitySchema,
400 binding: [u8; 32],
401 incarnation: [u8; 16],
402 cursor: Option<&QueryCursor>,
403 rows: usize,
404 bytes: usize,
405) -> Result<QueryPage<Vec<u8>>, Error> {
406 let request = Request {
407 rows,
408 work: rows,
409 bytes,
410 cursor,
411 ..Request::default()
412 };
413 let plan = Plan::admit(entity, &request, binding, incarnation, None, false)?;
414 execute(map, entity, &request, &plan, None)
415}
416
417pub struct Query<'a, E, M: Memory = ic_storage::DefaultMemoryImpl> {
421 db: &'a Database<M>,
422 request: Request<'a>,
423 entity: PhantomData<E>,
424}
425impl<M: Memory> Database<M> {
426 #[must_use]
428 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
429 Query {
430 db: self,
431 entity: PhantomData,
432 request: Request::default(),
433 }
434 }
435}
436impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
437 #[must_use]
448 pub fn distinct(mut self) -> Self {
449 self.request.distinct = true;
450 self
451 }
452 #[must_use]
462 pub fn filter(
463 mut self,
464 field: &'a str,
465 comparison: Comparison,
466 value: impl Into<IndexValue<'a>>,
467 ) -> Self {
468 self.request
469 .filter(field, comparison, QueryOperand::Literal(value.into()));
470 self
471 }
472 #[must_use]
477 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
478 self.request
479 .filter(left, comparison, QueryOperand::Field(right));
480 self
481 }
482 #[must_use]
486 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
487 self.request
488 .filter(field, comparison, QueryOperand::Length(length));
489 self
490 }
491 #[must_use]
494 pub fn filter_present(self, field: &'a str) -> Self {
495 self.filter(field, Comparison::Ne, IndexValue::Absent)
496 }
497 #[must_use]
500 pub fn filter_absent(self, field: &'a str) -> Self {
501 self.filter(field, Comparison::Eq, IndexValue::Absent)
502 }
503 #[must_use]
510 pub fn filter_between(
511 self,
512 field: &'a str,
513 lower: impl Into<IndexValue<'a>>,
514 upper: impl Into<IndexValue<'a>>,
515 ) -> Self {
516 self.filter(field, Comparison::Ge, lower)
517 .filter(field, Comparison::Le, upper)
518 }
519 #[must_use]
527 pub fn filter_not_between(
528 self,
529 field: &'a str,
530 lower: impl Into<IndexValue<'a>>,
531 upper: impl Into<IndexValue<'a>>,
532 ) -> Self {
533 self.filter_any(&[
534 (field, Comparison::Lt, lower.into()),
535 (field, Comparison::Gt, upper.into()),
536 ])
537 }
538 #[must_use]
545 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
546 self.request.or_clause(
547 alternatives
548 .iter()
549 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
550 );
551 self
552 }
553 #[must_use]
558 pub fn filter_any_operands(
559 mut self,
560 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
561 ) -> Self {
562 self.request.or_clause(alternatives.iter().copied());
563 self
564 }
565
566 #[must_use]
574 pub fn filter_in(mut self, field: &'a str, values: &[IndexValue<'a>]) -> Self {
575 self.request.or_clause(
576 values
577 .iter()
578 .copied()
579 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value))),
580 );
581 self
582 }
583
584 #[must_use]
592 pub fn filter_not_in(mut self, field: &'a str, values: &[IndexValue<'a>]) -> Self {
593 self.request.filter_not_in(field, values);
594 self
595 }
596 #[must_use]
601 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
602 self.request.using_index(name, values);
603 self
604 }
605 #[must_use]
615 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
616 self.request.order_by(fields);
617 self
618 }
619 #[must_use]
624 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
625 self.request.order_by_each(fields);
626 self
627 }
628 #[must_use]
630 pub fn descending(mut self) -> Self {
631 self.request.descending = true;
632 self
633 }
634 #[must_use]
641 pub fn limit(mut self, rows: usize) -> Self {
642 self.request.rows = rows;
643 self
644 }
645 #[must_use]
647 pub fn work_limit(mut self, candidates: usize) -> Self {
648 self.request.work = candidates;
649 self
650 }
651 #[must_use]
653 pub fn byte_limit(mut self, bytes: usize) -> Self {
654 self.request.bytes = bytes;
655 self
656 }
657 #[must_use]
659 pub fn after(mut self, cursor: &'a QueryCursor) -> Self {
660 self.request.cursor = Some(cursor);
661 self
662 }
663 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
670 fetch_rows(self.db, E::SCHEMA, self.request, None)?.decode_entities()
671 }
672 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
682 let raw = fetch_rows(self.db, E::SCHEMA, self.request, Some(R::definition()))?;
683 raw.decode_projection()
684 }
685}
686
687fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u16, Error> {
691 let TypeBody::Record(fields) = &output.body else {
692 return Err(Error::InvalidQuery);
693 };
694 if fields.is_empty()
695 || fields.len() > crate::schema::MAX_FIELDS
696 || fields.windows(2).any(|w| w[0].name >= w[1].name)
697 {
698 return Err(Error::InvalidQuery);
699 }
700 let mut source = TypeGraph::default();
701 let mut target = TypeGraph::default();
702 let mut mask = 0;
703 for field in *fields {
704 let position = entity
705 .fields
706 .iter()
707 .position(|f| f.name == field.name)
708 .ok_or(Error::InvalidQuery)?;
709 let stored = &entity.fields[position];
710 if stored.value != field.value || stored.optional != field.optional {
711 return Err(Error::InvalidQuery);
712 }
713 source
714 .include(stored.value)
715 .map_err(|_| Error::InvalidQuery)?;
716 target
717 .include(field.value)
718 .map_err(|_| Error::InvalidQuery)?;
719 mask |= 1 << position;
720 }
721 if !source.contains(&target) {
722 return Err(Error::InvalidQuery);
723 }
724 Ok(mask)
725}
726
727struct Term {
728 position: usize,
729 comparison: Comparison,
730 operand: TermOperand,
731 or_next: bool,
732}
733
734enum TermOperand {
735 Literal { bytes: Vec<u8>, absent: bool },
736 Member { item: FieldType, bytes: Vec<u8> },
737 Field(usize),
738 Length(u32),
739}
740
741fn member_type(field: FieldType) -> Option<FieldType> {
742 match key::operand_type(field) {
743 FieldType::List { item, .. } => Some(*item),
744 FieldType::Named(link) => match (link.definition)().body {
745 TypeBody::Set { item, .. } => Some(item),
746 _ => None,
747 },
748 _ => None,
749 }
750}
751
752fn contains_member(
754 span: &[u8],
755 optional: bool,
756 item: FieldType,
757 needle: &[u8],
758 scratch: &mut Vec<u8>,
759) -> Result<bool, Error> {
760 let mut reader = Decoder::new(span)?;
761 if optional && !reader.boolean()? {
762 return Ok(false);
763 }
764 for _ in 0..reader.nat32()? {
765 scratch.clear();
766 IndexValue::read(&mut reader, item)?.append_component(false, scratch);
767 if scratch.as_slice() == needle {
768 return Ok(true);
769 }
770 }
771 Ok(false)
772}
773
774fn admit_ordered_fields(entity: &EntitySchema, mask: u16) -> Result<(), Error> {
775 for (i, field) in entity.fields.iter().enumerate() {
776 if mask & (1 << i) != 0 && !key::supports(field.value) {
777 return Err(Error::InvalidQuery);
778 }
779 }
780 Ok(())
781}
782
783fn comparison_key(
785 entity: &EntitySchema,
786 mask: u16,
787 values: &[IndexValue<'_>],
788) -> Result<Vec<u8>, Error> {
789 let mut key = Vec::new();
790 for (i, field) in entity.fields.iter().enumerate() {
791 if mask & (1 << i) != 0 {
792 values[i].append_component(field.optional, &mut key);
793 if key.len() > MAX_COMPARISON_KEY {
794 return Err(Error::Limit);
795 }
796 }
797 }
798 Ok(key)
799}
800
801fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
802 if size > limit {
803 return Err(Error::RowTooLarge);
804 }
805 if size > limit - *used {
806 return Err(Error::Limit);
807 }
808 *used += size;
809 Ok(())
810}
811
812fn projection_size(spans: &[(u16, u16)], mask: u16) -> usize {
814 spans
815 .iter()
816 .enumerate()
817 .filter(|(i, _)| mask & (1 << i) != 0)
818 .map(|(_, (start, end))| usize::from(end - start))
819 .sum()
820}
821
822fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u16, size: usize) -> Vec<u8> {
823 let mut output = Vec::with_capacity(size);
824 for (i, &(start, end)) in spans.iter().enumerate() {
825 if mask & (1 << i) != 0 {
826 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
827 }
828 }
829 output
830}
831struct Plan<'a> {
832 index: Option<&'a IndexSchema>,
833 prefix: Vec<u8>,
834 fixed_components: usize,
835 terms: Vec<Term>,
836 selected: u16,
837 span_fields: u16,
839 binding: [u8; 32],
840 projection: Option<u16>,
841 distinct: distinct::Strategy,
842 sort: Option<Vec<(usize, bool)>>,
843 descending: bool,
844}
845impl<'a> Plan<'a> {
846 fn admit(
847 entity: &'a EntitySchema,
848 request: &Request<'_>,
849 schema: [u8; 32],
850 incarnation: [u8; 16],
851 projection: Option<&TypeSchema>,
852 group_output: bool,
853 ) -> Result<Self, Error> {
854 if request.over_limit
855 || !(1..=32).contains(&request.rows)
856 || !(1..=MAX_WORK).contains(&request.work)
857 || !(1..=MAX_OUTPUT).contains(&request.bytes)
858 {
859 return Err(Error::Limit);
860 }
861 if !group_output && !request.groups.is_empty() {
862 return Err(Error::InvalidQuery);
863 }
864 for value in request
866 .predicates
867 .iter()
868 .filter_map(|p| match &p.operand {
869 QueryOperand::Literal(value) => Some(value),
870 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
871 })
872 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
873 {
874 if match value {
875 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
876 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
877 _ => false,
878 } {
879 return Err(Error::Limit);
880 }
881 }
882 let primary = entity
883 .fields
884 .iter()
885 .position(|f| f.name == entity.primary_key)
886 .ok_or(Error::InvalidQuery)?;
887 let mut plan = Self {
888 index: None,
889 prefix: prefix(2, entity.id),
890 fixed_components: 0,
891 terms: Vec::new(),
892 selected: 1 << primary,
893 span_fields: 0,
894 binding: [0; 32],
895 projection: projection
896 .map(|output| admit_projection(entity, output))
897 .transpose()?,
898 distinct: distinct::Strategy::Identity,
899 sort: None,
900 descending: request.descending ^ request.primary_descending(entity),
901 };
902 for predicate in &request.predicates {
903 let position = entity
904 .fields
905 .iter()
906 .position(|f| f.name == predicate.field)
907 .ok_or(Error::InvalidQuery)?;
908 let field = &entity.fields[position];
909 let operand = match predicate.operand {
910 QueryOperand::Length(length) => {
911 let supported = match key::operand_type(field.value) {
912 FieldType::Text { .. }
913 | FieldType::Blob { .. }
914 | FieldType::List { .. } => true,
915 FieldType::Named(link) => matches!(
916 (link.definition)().body,
917 TypeBody::Map { .. } | TypeBody::Set { .. }
918 ),
919 _ => false,
920 };
921 if !supported || !predicate.comparison.is_relational() {
922 return Err(Error::InvalidQuery);
923 }
924 plan.span_fields |= 1 << position;
925 TermOperand::Length(length)
926 }
927 QueryOperand::Field(name) => {
928 let right = entity
929 .fields
930 .iter()
931 .position(|f| f.name == name)
932 .ok_or(Error::InvalidQuery)?;
933 let right_type = entity.fields[right].value;
934 let compatible = field.value == right_type
935 || matches!(
936 (field.value, right_type),
937 (FieldType::Text { .. }, FieldType::Text { .. })
938 | (FieldType::Blob { .. }, FieldType::Blob { .. })
939 );
940 if !compatible
941 || !key::supports(field.value)
942 || !predicate.comparison.supports_scalar(field.value)
943 {
944 return Err(Error::InvalidQuery);
945 }
946 plan.selected |= (1 << position) | (1 << right);
947 TermOperand::Field(right)
948 }
949 QueryOperand::Literal(value) => {
950 if predicate.comparison == Comparison::Contains
951 && let Some(item) = member_type(field.value)
952 {
953 if !key::supports(item) {
954 return Err(Error::InvalidQuery);
955 }
956 value.admit(item, false)?;
957 let mut bytes = Vec::new();
958 value.append_component(false, &mut bytes);
959 plan.span_fields |= 1 << position;
960 TermOperand::Member { item, bytes }
961 } else {
962 let absent = value == IndexValue::Absent;
963 if key::supports(field.value) {
964 plan.selected |= 1 << position;
965 } else if absent
966 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
967 {
968 plan.span_fields |= 1 << position;
969 } else {
970 return Err(Error::InvalidQuery);
971 }
972 predicate
973 .comparison
974 .admit(field.value, field.optional, value)?;
975 let mut bytes = Vec::new();
976 value.append_component(field.optional, &mut bytes);
977 TermOperand::Literal { bytes, absent }
978 }
979 }
980 };
981 plan.terms.push(Term {
982 position,
983 comparison: predicate.comparison,
984 operand,
985 or_next: predicate.or_next,
986 });
987 }
988 match order::select(entity, request)? {
991 order::Path::Primary => {}
992 order::Path::Index(path) => {
993 plan.index = Some(path.index);
994 plan.prefix = path.prefix;
995 plan.selected |= entity.key_fields();
996 plan.fixed_components = path.fixed;
997 }
998 order::Path::Sort(fields) => {
999 for &(position, _) in &fields {
1000 plan.selected |= 1 << position;
1001 }
1002 plan.sort = Some(fields);
1003 }
1004 }
1005 if request.distinct {
1006 plan.distinct = distinct::admit(
1007 entity,
1008 request,
1009 plan.projection,
1010 plan.index,
1011 plan.fixed_components,
1012 plan.sort.is_some(),
1013 )?;
1014 if plan.distinct == distinct::Strategy::Complete {
1015 plan.selected |= plan.projection.ok_or(Error::InvalidQuery)?;
1016 }
1017 }
1018 let mut hash = Sha256::new();
1019 hash.update(b"ic-db:query:v1\0");
1020 hash.update(schema);
1021 hash.update(incarnation);
1022 hash.update([u8::from(request.descending)]);
1023 hash.update((plan.prefix.len() as u32).to_le_bytes());
1024 hash.update(&plan.prefix);
1025 for term in &plan.terms {
1026 hash.update([term.position as u8, term.comparison as u8]);
1027 match &term.operand {
1028 TermOperand::Literal { bytes, .. } | TermOperand::Member { bytes, .. } => {
1029 hash.update((bytes.len() as u32).to_le_bytes());
1030 hash.update(bytes);
1031 }
1032 TermOperand::Length(length) => {
1033 hash.update((u32::MAX - 1).to_le_bytes());
1034 hash.update(length.to_le_bytes());
1035 }
1036 TermOperand::Field(right) => {
1037 hash.update(u32::MAX.to_le_bytes());
1039 hash.update([*right as u8]);
1040 }
1041 }
1042 }
1043 let clauses = plan
1046 .terms
1047 .iter()
1048 .enumerate()
1049 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1050 if clauses != 0 {
1051 hash.update(b"or-clauses\0");
1052 hash.update([clauses]);
1053 }
1054 if let Some(order) = &request.order {
1055 hash.update(b"order\0");
1056 hash.update([order.len() as u8]);
1057 for name in order {
1058 hash.update([entity
1060 .fields
1061 .iter()
1062 .position(|f| f.name == *name)
1063 .ok_or(Error::InvalidQuery)? as u8]);
1064 }
1065 }
1066 if request.order_descending != 0 {
1067 hash.update(b"order-directions\0");
1068 hash.update([request.order_descending]);
1069 }
1070 if let Some(mask) = plan.projection {
1073 hash.update(b"projection\0");
1074 hash.update(mask.to_le_bytes());
1075 }
1076 if request.distinct {
1077 hash.update(b"distinct\0");
1078 }
1079 plan.binding = hash.finalize().into();
1080 if let Some(cursor) = request.cursor {
1081 if cursor.binding != plan.binding {
1082 return Err(Error::InvalidCursor);
1083 }
1084 plan.validate_position(entity, &cursor.position)
1085 .map_err(|_| Error::InvalidCursor)?;
1086 }
1087 Ok(plan)
1088 }
1089 fn validate_position(&self, entity: &EntitySchema, bytes: &[u8]) -> Result<(), Error> {
1090 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
1091 return Err(Error::InvalidCursor);
1092 }
1093 if let Some(index) = self.index {
1094 let mut remaining = bytes.get(9..).ok_or(Error::InvalidCursor)?;
1095 for name in index.fields {
1096 consume_index_component(entity, index, name, &mut remaining)?;
1097 }
1098 if !index.unique {
1099 key::consume(&mut remaining, entity.key_type()?)?;
1100 }
1101 if !remaining.is_empty() {
1102 return Err(Error::InvalidCursor);
1103 }
1104 } else {
1105 RowKey::decode(
1106 bytes.get(5..).ok_or(Error::InvalidCursor)?,
1107 entity.key_type()?,
1108 )?;
1109 }
1110 Ok(())
1111 }
1112 fn cursor(&self, position: &[u8], inclusive: bool) -> QueryCursor {
1113 QueryCursor {
1114 binding: self.binding,
1115 position: position.to_vec(),
1116 inclusive,
1117 }
1118 }
1119}
1120
1121fn consume_index_component(
1123 entity: &EntitySchema,
1124 index: &IndexSchema,
1125 name: &str,
1126 remaining: &mut &[u8],
1127) -> Result<(), Error> {
1128 let field = entity
1129 .fields
1130 .iter()
1131 .find(|f| f.name == name)
1132 .ok_or(Error::InvalidQuery)?;
1133 if field.optional {
1134 let (&presence, rest) = remaining.split_first().ok_or(Error::InvalidCursor)?;
1135 *remaining = rest;
1136 match presence {
1137 0 if !index.present_only => return Ok(()),
1138 1 => {}
1139 _ => return Err(Error::InvalidCursor),
1140 }
1141 }
1142 key::consume(remaining, field.value)
1143}
1144
1145#[inline(never)]
1148#[expect(
1149 clippy::needless_pass_by_value,
1150 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1151)]
1152fn fetch_rows<M: Memory>(
1153 db: &Database<M>,
1154 entity: &EntitySchema,
1155 request: Request<'_>,
1156 projection: Option<&TypeSchema>,
1157) -> Result<QueryPage<Vec<u8>>, Error> {
1158 db.schema.admits(entity)?;
1159 let plan = Plan::admit(
1160 entity,
1161 &request,
1162 db.schema.fingerprint(),
1163 db.incarnation,
1164 projection,
1165 false,
1166 )?;
1167 execute(&db.map, entity, &request, &plan, None)
1168}
1169
1170fn execute<M: Memory>(
1171 map: &Map<M>,
1172 entity: &EntitySchema,
1173 request: &Request<'_>,
1174 plan: &Plan<'_>,
1175 mut aggregate: Option<aggregate::Accumulator<'_>>,
1176) -> Result<QueryPage<Vec<u8>>, Error> {
1177 execute_inner(map, entity, request, plan, aggregate.as_mut(), None)
1178}
1179
1180const STEP_INPUT_BYTES: usize = 64 * 1024;
1183const CANDIDATE_BYTES: usize = crate::codec::MAX_ROW_BYTES + 2 * crate::MAX_INDEX_KEY_BYTES;
1184
1185fn execute_inner<M: Memory>(
1186 map: &Map<M>,
1187 entity: &EntitySchema,
1188 request: &Request<'_>,
1189 plan: &Plan<'_>,
1190 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1191 mut input_bytes: Option<&mut usize>,
1192) -> Result<QueryPage<Vec<u8>>, Error> {
1193 let mut page = QueryPage {
1194 rows: Vec::new(),
1195 next: None,
1196 examined: 0,
1197 fetched: 0,
1198 output_bytes: 0,
1199 };
1200 let Some(bounds) = range::bounds(entity, request, plan)? else {
1201 return Ok(page);
1202 };
1203 let mut entries = map.range(bounds);
1204 let mut collected = if plan.distinct == distinct::Strategy::Complete {
1205 Some(distinct::Collection::new(
1206 plan.projection.ok_or(Error::InvalidQuery)?,
1207 ))
1208 } else {
1209 None
1210 };
1211 let mut sorted = plan
1212 .sort
1213 .as_ref()
1214 .map(|_| sort::Collection::new(request, plan.distinct == distinct::Strategy::Sorted));
1215 let mut component = Vec::new();
1216 let mut right_component = Vec::new();
1217 let mut previous = if let Some(cursor) = request.cursor.filter(|c| !c.inclusive) {
1220 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1221 } else {
1222 None
1223 };
1224 while let Some(entry) = if plan.descending {
1225 entries.next_back()
1226 } else {
1227 entries.next()
1228 } {
1229 if request.work == 0 {
1233 return Err(Error::Limit);
1234 }
1235 page.examined += 1;
1236 let stored_key = entry.key();
1237 let mut read_bytes = stored_key.len();
1238 let (owner, bytes) = if plan.index.is_some() {
1239 let owner_bytes = entry.value();
1240 read_bytes += owner_bytes.len();
1241 let owner = RowKey::decode(&owner_bytes, entity.key_type()?)?;
1242 let bytes = map.get(&row_key(entity.id, owner)).ok_or(Error::Corrupt)?;
1243 (owner, bytes)
1244 } else {
1245 (
1246 RowKey::decode(&stored_key[5..], entity.key_type()?)?,
1247 entry.value(),
1248 )
1249 };
1250 if let Some(used) = input_bytes.as_deref_mut() {
1251 read_bytes += bytes.len();
1252 if read_bytes > CANDIDATE_BYTES {
1253 return Err(Error::Corrupt);
1254 }
1255 *used += read_bytes;
1256 }
1257 page.fetched += 1;
1258 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
1259 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1260 entity.inspect_fields(
1261 &bytes,
1262 plan.selected,
1263 &mut values,
1264 (plan.span_fields != 0
1265 || plan.projection.is_some()
1266 || aggregate.as_ref().is_some_and(|a| a.needs_spans()))
1267 .then_some(&mut spans),
1268 )?;
1269 let primary = entity
1270 .fields
1271 .iter()
1272 .position(|f| f.name == entity.primary_key)
1273 .ok_or(Error::Corrupt)?;
1274 if RowKey::from_index(values[primary])? != owner {
1275 return Err(Error::Corrupt);
1276 }
1277 if plan.index.is_some() {
1278 validate_index_entry(entity, &entity.row_info(&values)?, owner, stored_key)?;
1279 }
1280 let mut accepts = |term: &Term| -> Result<bool, Error> {
1281 let value = values[term.position];
1282 component.clear();
1283 let (operand, optional) = match &term.operand {
1284 TermOperand::Literal { absent: true, .. }
1285 if plan.span_fields & (1 << term.position) != 0 =>
1286 {
1287 let absent = bytes[usize::from(spans[term.position].0)] == 0;
1288 return Ok(term.comparison.accepts_absent(absent));
1289 }
1290 TermOperand::Member {
1291 item,
1292 bytes: needle,
1293 } => {
1294 let (start, end) = spans[term.position];
1295 return contains_member(
1296 &bytes[usize::from(start)..usize::from(end)],
1297 entity.fields[term.position].optional,
1298 *item,
1299 needle,
1300 &mut component,
1301 );
1302 }
1303 TermOperand::Length(length) => {
1304 let (start, end) = spans[term.position];
1305 let span = &bytes[usize::from(start)..usize::from(end)];
1306 let actual =
1307 crate::codec::validated_length(span, entity.fields[term.position].optional)
1308 .map(u32::to_be_bytes);
1309 return Ok(term.comparison.accepts(
1310 actual.as_ref().map(|v| v.as_slice()),
1311 Some(&length.to_be_bytes()),
1312 false,
1313 ));
1314 }
1315 TermOperand::Literal { bytes, absent } => (
1316 (!absent).then_some(bytes.as_slice()),
1317 entity.fields[term.position].optional,
1318 ),
1319 TermOperand::Field(right) => {
1320 let rhs = values[*right];
1321 right_component.clear();
1322 rhs.append_component(false, &mut right_component);
1323 (
1324 (rhs != IndexValue::Absent).then_some(right_component.as_slice()),
1325 false,
1326 )
1327 }
1328 };
1329 value.append_component(optional, &mut component);
1330 Ok(term.comparison.accepts(
1331 (value != IndexValue::Absent).then_some(component.as_slice()),
1332 operand,
1333 optional,
1334 ))
1335 };
1336 let matches = 'matches: {
1337 'clause: for clause in plan.terms.split_inclusive(|term| !term.or_next) {
1338 for term in clause {
1339 if accepts(term)? {
1340 continue 'clause;
1341 }
1342 }
1343 break 'matches false;
1344 }
1345 true
1346 };
1347 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
1348 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
1349 if matches && let Some(accumulator) = aggregate.as_mut() {
1350 accumulator.push(entity, &values, &bytes, &spans)?;
1351 if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
1352 return Ok(page);
1354 }
1355 } else if matches && let Some(collection) = collected.as_mut() {
1356 collection.push(entity, request, &values, &bytes, &spans)?;
1357 } else if matches && let Some(collection) = sorted.as_mut() {
1358 collection.push(entity, plan, &values, &bytes, &spans)?;
1359 } else if matches && !duplicate {
1360 let size = plan
1361 .projection
1362 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
1363 if size > request.bytes {
1364 return Err(Error::RowTooLarge);
1365 }
1366 if size > request.bytes - page.output_bytes {
1367 page.next = Some(plan.cursor(stored_key, true));
1368 return Ok(page);
1369 }
1370 page.output_bytes += size;
1371 if let Some(mask) = plan.projection {
1372 page.rows.push(copy_projection(&bytes, &spans, mask, size));
1373 } else {
1374 page.rows.push(bytes);
1375 }
1376 if let Some(boundary) = boundary {
1377 previous = Some(boundary.to_vec());
1378 }
1379 }
1380 if page.rows.len() == request.rows
1381 || page.examined == request.work
1382 || input_bytes
1383 .as_deref()
1384 .is_some_and(|used| *used > STEP_INPUT_BYTES - CANDIDATE_BYTES)
1385 {
1386 if (aggregate.is_some() && input_bytes.is_none())
1387 || collected.is_some()
1388 || sorted.is_some()
1389 {
1390 return Err(Error::Limit);
1393 }
1394 page.next = Some(plan.cursor(stored_key, false));
1395 return Ok(page);
1396 }
1397 }
1398 if let Some(collection) = collected {
1399 page.output_bytes = collection.output_bytes;
1400 page.rows = collection.rows;
1401 }
1402 if let Some(collection) = sorted {
1403 collection.finish(request.bytes, &mut page)?;
1404 }
1405 Ok(page)
1406}