1mod aggregate;
3mod distinct;
4mod order;
5mod range;
6mod sort;
7pub use aggregate::{
8 Aggregate, GroupCount, GroupOrder, GroupValue,
9 jobs::{AggregateJobs, GroupCursor, GroupPage, JobHandle, JobOutcome, JobStep},
10};
11
12use super::{Database, Map, prefix, row_key, validate_index_entry};
13use crate::{
14 Entity, EntitySchema, Error, FieldType, IndexSchema, IndexValue, TypeBody, TypeSchema, Value,
15 codec::Decoder, key, primary::RowKey, types::TypeGraph,
16};
17use ic_storage::Memory;
18use sha2::{Digest, Sha256};
19use std::{
20 cell::{Ref, RefCell},
21 marker::PhantomData,
22 ops::Deref,
23 rc::Rc,
24};
25
26const MAX_TERMS: usize = 8;
27const MAX_WORK: usize = 512;
28const MAX_OUTPUT: usize = 128 * 1024;
29const MAX_COMPARISON_KEY: usize = 4096;
30const MAX_DISTINCT_VALUES: usize = 32;
31const MAX_STATE_BYTES: usize = 128 * 1024;
32
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum SortDirection {
36 Ascending,
38 Descending,
40}
41
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44#[repr(u8)]
45pub enum Comparison {
46 Eq = 0,
48 Ne = 1,
50 Lt = 2,
52 Le = 3,
54 Gt = 4,
56 Ge = 5,
58 StartsWith = 6,
62 EndsWith = 7,
65 Contains = 8,
69}
70
71impl Comparison {
72 fn is_relational(self) -> bool {
73 matches!(
74 self,
75 Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge
76 )
77 }
78
79 fn supports_scalar(self, field: FieldType) -> bool {
80 self.is_relational()
81 || matches!(
82 key::operand_type(field),
83 FieldType::Text { .. } | FieldType::Blob { .. }
84 )
85 }
86
87 fn admit(self, field: FieldType, optional: bool, value: IndexValue<'_>) -> Result<(), Error> {
88 value.admit(field, optional)?;
89 if !self.supports_scalar(field) {
90 return Err(Error::InvalidQuery);
91 }
92 if value == IndexValue::Absent && !matches!(self, Self::Eq | Self::Ne) {
93 return Err(Error::InvalidOperand);
94 }
95 Ok(())
96 }
97
98 fn accepts(self, actual: Option<&[u8]>, operand: Option<&[u8]>, optional: bool) -> bool {
99 if actual.is_none() {
100 return self.accepts_absent(operand.is_none());
101 }
102 match self {
103 Self::Eq => actual == operand,
104 Self::Ne => actual != operand,
105 Self::StartsWith | Self::EndsWith | Self::Contains => {
106 fn content(key: &[u8], optional: bool) -> Option<&[u8]> {
109 key.get(usize::from(optional)..)?.strip_suffix(&[0, 0])
110 }
111 actual
112 .and_then(|key| content(key, optional))
113 .zip(operand.and_then(|key| content(key, optional)))
114 .is_some_and(|(actual, operand)| match self {
115 Self::StartsWith => actual.starts_with(operand),
118 Self::EndsWith => actual
122 .strip_suffix(operand)
123 .is_some_and(|prefix| prefix.last() != Some(&0)),
124 _ => contains_component(actual, operand),
125 })
126 }
127 _ if actual.is_none() || operand.is_none() => false,
128 Self::Lt => actual < operand,
129 Self::Le => actual <= operand,
130 Self::Gt => actual > operand,
131 Self::Ge => actual >= operand,
132 }
133 }
134
135 fn accepts_absent(self, other_absent: bool) -> bool {
138 match self {
139 Self::Eq => other_absent,
140 Self::Ne => !other_absent,
141 _ => false,
142 }
143 }
144}
145
146fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
148 let Some(start) = memchr::memmem::find(actual, needle) else {
149 return false;
150 };
151 if start == 0 || actual[start - 1] != 0 {
152 return true;
153 }
154 fn raw(content: &[u8]) -> Vec<u8> {
158 let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
159 let mut encoded = content.iter();
160 while let Some(&byte) = encoded.next() {
161 bytes.push(byte);
162 if byte == 0 {
163 encoded.next();
164 }
165 }
166 bytes
167 }
168 memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
169}
170
171#[derive(Clone, Debug, PartialEq, Eq)]
175pub struct QueryCursor {
176 binding: [u8; 32],
177 position: Vec<u8>,
178 inclusive: bool,
179}
180impl QueryCursor {
181 pub(super) const MAX_ENCODED_BYTES: usize = 34 + crate::MAX_INDEX_KEY_BYTES;
182
183 #[must_use]
185 pub fn to_bytes(&self) -> Vec<u8> {
186 let mut bytes = vec![1, u8::from(self.inclusive)];
187 bytes.extend(self.binding);
188 bytes.extend(&self.position);
189 bytes
190 }
191
192 pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
196 if !(35..=Self::MAX_ENCODED_BYTES).contains(&bytes.len()) || bytes[0] != 1 || bytes[1] > 1 {
197 return Err(Error::InvalidCursor);
198 }
199 Ok(Self {
200 binding: bytes[2..34].try_into().map_err(|_| Error::InvalidCursor)?,
201 position: bytes[34..].to_vec(),
202 inclusive: bytes[1] == 1,
203 })
204 }
205}
206
207#[derive(Debug)]
210pub struct QueryPage<T> {
211 pub rows: Vec<T>,
213 pub next: Option<QueryCursor>,
215 pub examined: usize,
217 pub fetched: usize,
219 pub output_bytes: usize,
221}
222
223impl QueryPage<Vec<u8>> {
224 #[inline(never)]
225 pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
226 Ok(QueryPage {
227 rows: self
228 .rows
229 .iter()
230 .map(|bytes| E::decode(bytes))
231 .collect::<Result<_, _>>()?,
232 next: self.next,
233 examined: self.examined,
234 fetched: self.fetched,
235 output_bytes: self.output_bytes,
236 })
237 }
238
239 #[inline(never)]
240 fn decode_projection<R: Value>(self) -> Result<QueryPage<R>, Error> {
241 Ok(QueryPage {
242 rows: self
243 .rows
244 .iter()
245 .map(|bytes| {
246 let mut reader = Decoder::new(bytes)?;
247 let row = R::decode_from(&mut reader)?;
249 reader.finish()?;
250 Ok(row)
251 })
252 .collect::<Result<_, Error>>()?,
253 next: self.next,
254 examined: self.examined,
255 fetched: self.fetched,
256 output_bytes: self.output_bytes,
257 })
258 }
259}
260
261#[derive(Clone, Copy, Debug, PartialEq, Eq)]
263pub enum QueryOperand<'a> {
264 Literal(IndexValue<'a>),
266 Length(u32),
268 Field(&'a str),
270}
271
272struct Predicate<'a> {
273 field: &'a str,
274 comparison: Comparison,
275 operand: QueryOperand<'a>,
276 or_next: bool,
278}
279struct Request<'a> {
280 groups: aggregate::GroupRequest<'a>,
281 predicates: Vec<Predicate<'a>>,
282 index: Option<(&'a str, Vec<IndexValue<'a>>)>,
283 order: Option<Vec<&'a str>>,
284 order_descending: u8,
285 descending: bool,
286 distinct: bool,
287 rows: usize,
288 work: usize,
289 bytes: usize,
290 cursor: Option<&'a QueryCursor>,
291 over_limit: bool,
292}
293
294impl Default for Request<'_> {
295 fn default() -> Self {
296 Self {
297 groups: aggregate::GroupRequest::default(),
298 predicates: Vec::new(),
299 index: None,
300 order: None,
301 order_descending: 0,
302 descending: false,
303 distinct: false,
304 rows: 32,
305 work: 128,
306 bytes: MAX_OUTPUT,
307 cursor: None,
308 over_limit: false,
309 }
310 }
311}
312
313impl<'a> Request<'a> {
316 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
317 self.predicates.split_inclusive(|p| !p.or_next)
318 }
319
320 #[inline(never)]
321 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
322 if self.predicates.len() == MAX_TERMS {
323 self.over_limit = true;
324 } else {
325 self.predicates.push(Predicate {
326 field,
327 comparison,
328 operand,
329 or_next: false,
330 });
331 }
332 }
333
334 #[inline(never)]
335 fn or_clause(
336 &mut self,
337 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
338 ) {
339 let count = alternatives.len();
340 if count == 0 || count > MAX_TERMS - self.predicates.len() {
341 self.over_limit = true;
342 } else {
343 self.predicates.extend(alternatives.enumerate().map(
344 |(i, (field, comparison, operand))| Predicate {
345 field,
346 comparison,
347 operand,
348 or_next: i + 1 < count,
349 },
350 ));
351 }
352 }
353
354 #[inline(never)]
355 fn filter_not_in(
356 &mut self,
357 field: &'a str,
358 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
359 ) {
360 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
361 self.over_limit = true;
362 return;
363 }
364 for value in values {
365 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
366 }
367 }
368
369 #[inline(never)]
370 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
371 if values.len() > 4 {
372 self.over_limit = true;
373 } else {
374 self.index = Some((name, values.to_vec()));
375 }
376 }
377
378 #[inline(never)]
379 fn order_by(&mut self, fields: &[&'a str]) {
380 self.order_descending = 0;
381 if fields.len() > 4 {
382 self.over_limit = true;
383 } else {
384 self.order = Some(fields.to_vec());
385 }
386 }
387
388 #[inline(never)]
389 fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
390 if fields.len() > 4 {
391 self.over_limit = true;
392 return;
393 }
394 self.order = Some(Vec::with_capacity(fields.len()));
395 self.order_descending = 0;
396 for &(field, direction) in fields {
397 self.append_order(field, direction);
398 }
399 }
400
401 fn append_order(&mut self, field: &'a str, direction: SortDirection) {
402 let fields = self.order.get_or_insert_with(Vec::new);
403 if fields.len() == 4 {
404 self.over_limit = true;
405 return;
406 }
407 if direction == SortDirection::Descending {
408 self.order_descending |= 1 << fields.len();
409 }
410 fields.push(field);
411 }
412
413 fn primary_descending(&self, entity: &EntitySchema) -> bool {
414 self.order_descending != 0
415 && self.order.as_ref().is_some_and(|fields| {
416 fields.last() == Some(&entity.primary_key)
417 && self.order_descending & (1 << (fields.len() - 1)) != 0
418 })
419 }
420}
421
422pub(super) fn source_page<M: Memory>(
424 map: &Map<M>,
425 entity: &EntitySchema,
426 binding: [u8; 32],
427 incarnation: [u8; 16],
428 cursor: Option<&QueryCursor>,
429 rows: usize,
430 bytes: usize,
431) -> Result<QueryPage<Vec<u8>>, Error> {
432 let request = Request {
433 rows,
434 work: rows,
435 bytes,
436 cursor,
437 ..Request::default()
438 };
439 let plan = Plan::admit(
440 entity,
441 &request,
442 binding,
443 incarnation,
444 None,
445 PlanOutput::Rows,
446 )?;
447 execute(map, entity, &request, &plan, None)
448}
449
450enum QuerySource<'a, M: Memory> {
451 Direct(&'a Database<M>),
452 Session(Rc<RefCell<Database<M>>>),
453}
454
455enum QueryRead<'a, M: Memory> {
456 Direct(&'a Database<M>),
457 Session(Ref<'a, Database<M>>),
458}
459
460impl<M: Memory> Deref for QueryRead<'_, M> {
461 type Target = Database<M>;
462
463 fn deref(&self) -> &Self::Target {
464 match self {
465 Self::Direct(db) => db,
466 Self::Session(db) => db,
467 }
468 }
469}
470
471impl<M: Memory> QuerySource<'_, M> {
472 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
473 match self {
474 Self::Direct(db) => Ok(QueryRead::Direct(db)),
475 Self::Session(db) => db
476 .try_borrow()
477 .map(QueryRead::Session)
478 .map_err(|_| Error::BorrowConflict),
479 }
480 }
481}
482
483pub struct Query<'a, E, M: Memory> {
487 db: QuerySource<'a, M>,
488 request: Request<'a>,
489 entity: PhantomData<E>,
490}
491impl<M: Memory> Database<M> {
492 #[must_use]
494 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
495 Query {
496 db: QuerySource::Direct(self),
497 entity: PhantomData,
498 request: Request::default(),
499 }
500 }
501}
502impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
503 pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
504 Self {
505 db: QuerySource::Session(db),
506 request: Request::default(),
507 entity: PhantomData,
508 }
509 }
510
511 #[must_use]
522 pub fn distinct(mut self) -> Self {
523 self.request.distinct = true;
524 self
525 }
526
527 #[must_use]
537 pub fn filter(
538 mut self,
539 field: &'a str,
540 comparison: Comparison,
541 value: impl Into<IndexValue<'a>>,
542 ) -> Self {
543 self.request
544 .filter(field, comparison, QueryOperand::Literal(value.into()));
545 self
546 }
547
548 #[must_use]
550 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
551 self.filter(field, Comparison::Eq, value)
552 }
553
554 #[must_use]
556 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
557 self.filter(field, Comparison::Ne, value)
558 }
559
560 #[must_use]
562 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
563 self.filter(field, Comparison::Lt, value)
564 }
565
566 #[must_use]
568 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
569 self.filter(field, Comparison::Le, value)
570 }
571
572 #[must_use]
574 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
575 self.filter(field, Comparison::Gt, value)
576 }
577
578 #[must_use]
580 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
581 self.filter(field, Comparison::Ge, value)
582 }
583
584 #[must_use]
590 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
591 self.request
592 .filter(left, comparison, QueryOperand::Field(right));
593 self
594 }
595
596 #[must_use]
600 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
601 self.request
602 .filter(field, comparison, QueryOperand::Length(length));
603 self
604 }
605
606 #[must_use]
609 pub fn filter_present(self, field: &'a str) -> Self {
610 self.filter(field, Comparison::Ne, IndexValue::Absent)
611 }
612
613 #[must_use]
616 pub fn filter_absent(self, field: &'a str) -> Self {
617 self.filter(field, Comparison::Eq, IndexValue::Absent)
618 }
619
620 #[must_use]
627 pub fn filter_between(
628 self,
629 field: &'a str,
630 lower: impl Into<IndexValue<'a>>,
631 upper: impl Into<IndexValue<'a>>,
632 ) -> Self {
633 self.filter(field, Comparison::Ge, lower)
634 .filter(field, Comparison::Le, upper)
635 }
636
637 #[must_use]
645 pub fn filter_not_between(
646 self,
647 field: &'a str,
648 lower: impl Into<IndexValue<'a>>,
649 upper: impl Into<IndexValue<'a>>,
650 ) -> Self {
651 self.filter_any(&[
652 (field, Comparison::Lt, lower.into()),
653 (field, Comparison::Gt, upper.into()),
654 ])
655 }
656
657 #[must_use]
662 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
663 self.filter_fields(field, Comparison::Ge, lower)
664 .filter_fields(field, Comparison::Le, upper)
665 }
666
667 #[must_use]
672 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
673 self.filter_any_operands(&[
674 (field, Comparison::Lt, QueryOperand::Field(lower)),
675 (field, Comparison::Gt, QueryOperand::Field(upper)),
676 ])
677 }
678
679 #[must_use]
686 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
687 self.request.or_clause(
688 alternatives
689 .iter()
690 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
691 );
692 self
693 }
694
695 #[must_use]
700 pub fn filter_any_operands(
701 mut self,
702 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
703 ) -> Self {
704 self.request.or_clause(alternatives.iter().copied());
705 self
706 }
707
708 #[must_use]
718 pub fn filter_in(
719 mut self,
720 field: &'a str,
721 values: &[impl Copy + Into<IndexValue<'a>>],
722 ) -> Self {
723 self.request.or_clause(
724 values
725 .iter()
726 .copied()
727 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
728 );
729 self
730 }
731
732 #[must_use]
740 pub fn filter_not_in(
741 mut self,
742 field: &'a str,
743 values: &[impl Copy + Into<IndexValue<'a>>],
744 ) -> Self {
745 self.request
746 .filter_not_in(field, values.iter().copied().map(Into::into));
747 self
748 }
749
750 #[must_use]
755 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
756 self.request.using_index(name, values);
757 self
758 }
759
760 #[must_use]
763 pub fn order_asc(mut self, field: &'a str) -> Self {
764 self.request.append_order(field, SortDirection::Ascending);
765 self
766 }
767
768 #[must_use]
771 pub fn order_desc(mut self, field: &'a str) -> Self {
772 self.request.append_order(field, SortDirection::Descending);
773 self
774 }
775
776 #[must_use]
786 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
787 self.request.order_by(fields);
788 self
789 }
790
791 #[must_use]
796 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
797 self.request.order_by_each(fields);
798 self
799 }
800
801 #[must_use]
803 pub fn descending(mut self) -> Self {
804 self.request.descending = true;
805 self
806 }
807
808 #[must_use]
815 pub fn limit(mut self, rows: usize) -> Self {
816 self.request.rows = rows;
817 self
818 }
819
820 #[must_use]
822 pub fn work_limit(mut self, candidates: usize) -> Self {
823 self.request.work = candidates;
824 self
825 }
826
827 #[cfg(feature = "test-support")]
829 #[doc(hidden)]
830 #[must_use]
831 pub fn test_output_limit(mut self, bytes: usize) -> Self {
832 self.request.bytes = bytes;
833 self
834 }
835
836 #[must_use]
838 pub fn after(mut self, cursor: &'a QueryCursor) -> Self {
839 self.request.cursor = Some(cursor);
840 self
841 }
842
843 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
850 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
851 }
852
853 pub fn first(self) -> Result<Option<E>, Error> {
859 let mut page = self.probe_matches(1)?;
860 match page.rows.pop() {
861 None if page.next.is_some() => Err(Error::Limit),
862 result => Ok(result),
863 }
864 }
865
866 pub fn try_one(self) -> Result<Option<E>, Error> {
873 if self.request.cursor.is_some() {
874 return Err(Error::InvalidQuery);
875 }
876 let mut page = self.probe_matches(2)?;
877 if page.rows.len() == 2 {
878 return Err(Error::MultipleMatches);
879 }
880 if page.next.is_some() {
881 return Err(Error::Limit);
882 }
883 Ok(page.rows.pop())
884 }
885
886 fn probe_matches(self, rows: usize) -> Result<QueryPage<E>, Error> {
887 if !(1..=32).contains(&self.request.rows) {
888 return Err(Error::Limit);
889 }
890 self.limit(rows).fetch()
891 }
892
893 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
903 let raw = fetch_rows(
904 &*self.db.read()?,
905 E::SCHEMA,
906 self.request,
907 Some(R::definition()),
908 )?;
909 raw.decode_projection()
910 }
911}
912
913fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u16, Error> {
917 let TypeBody::Record(fields) = &output.body else {
918 return Err(Error::InvalidQuery);
919 };
920 if fields.is_empty()
921 || fields.len() > crate::schema::MAX_FIELDS
922 || fields.windows(2).any(|w| w[0].name >= w[1].name)
923 {
924 return Err(Error::InvalidQuery);
925 }
926 let mut source = TypeGraph::default();
927 let mut target = TypeGraph::default();
928 let mut mask = 0;
929 for field in *fields {
930 let position = entity
931 .field_position(field.name)
932 .ok_or(Error::InvalidQuery)?;
933 let stored = &entity.fields[position];
934 if stored.value != field.value || stored.optional != field.optional {
935 return Err(Error::InvalidQuery);
936 }
937 source
938 .include(stored.value)
939 .map_err(|_| Error::InvalidQuery)?;
940 target
941 .include(field.value)
942 .map_err(|_| Error::InvalidQuery)?;
943 mask |= 1 << position;
944 }
945 if !source.contains(&target) {
946 return Err(Error::InvalidQuery);
947 }
948 Ok(mask)
949}
950
951struct Term {
952 position: usize,
953 comparison: Comparison,
954 operand: TermOperand,
955 or_next: bool,
956}
957
958enum TermOperand {
959 Literal {
960 bytes: Vec<u8>,
961 absent: bool,
962 },
963 Member {
964 item: FieldType,
965 needle: MemberNeedle,
966 },
967 Field(usize),
968 Length(u32),
969}
970
971enum MemberNeedle {
972 Literal(Vec<u8>),
973 Field(usize),
974}
975
976fn member_type(field: FieldType) -> Option<FieldType> {
977 match key::operand_type(field) {
978 FieldType::List { item, .. } => Some(*item),
979 FieldType::Named(link) => match (link.definition)().body {
980 TypeBody::Set { item, .. } => Some(item),
981 _ => None,
982 },
983 _ => None,
984 }
985}
986
987fn contains_member(
989 span: &[u8],
990 optional: bool,
991 item: FieldType,
992 needle: &[u8],
993 scratch: &mut Vec<u8>,
994) -> Result<bool, Error> {
995 let mut reader = Decoder::new(span)?;
996 if optional && !reader.boolean()? {
997 return Ok(false);
998 }
999 for _ in 0..reader.nat32()? {
1000 scratch.clear();
1001 IndexValue::read(&mut reader, item)?.append_component(false, scratch);
1002 if scratch.as_slice() == needle {
1003 return Ok(true);
1004 }
1005 }
1006 Ok(false)
1007}
1008
1009fn admit_ordered_fields(entity: &EntitySchema, mask: u16) -> Result<(), Error> {
1010 for (i, field) in entity.fields.iter().enumerate() {
1011 if mask & (1 << i) != 0 && !key::supports(field.value) {
1012 return Err(Error::InvalidQuery);
1013 }
1014 }
1015 Ok(())
1016}
1017
1018fn comparison_key(
1020 entity: &EntitySchema,
1021 mask: u16,
1022 values: &[IndexValue<'_>],
1023) -> Result<Vec<u8>, Error> {
1024 let mut key = Vec::new();
1025 for (i, field) in entity.fields.iter().enumerate() {
1026 if mask & (1 << i) != 0 {
1027 values[i].append_component(field.optional, &mut key);
1028 if key.len() > MAX_COMPARISON_KEY {
1029 return Err(Error::Limit);
1030 }
1031 }
1032 }
1033 Ok(key)
1034}
1035
1036fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1037 if size > limit {
1038 return Err(Error::RowTooLarge);
1039 }
1040 if size > limit - *used {
1041 return Err(Error::Limit);
1042 }
1043 *used += size;
1044 Ok(())
1045}
1046
1047fn projection_size(spans: &[(u16, u16)], mask: u16) -> usize {
1049 spans
1050 .iter()
1051 .enumerate()
1052 .filter(|(i, _)| mask & (1 << i) != 0)
1053 .map(|(_, (start, end))| usize::from(end - start))
1054 .sum()
1055}
1056
1057fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u16, size: usize) -> Vec<u8> {
1058 let mut output = Vec::with_capacity(size);
1059 for (i, &(start, end)) in spans.iter().enumerate() {
1060 if mask & (1 << i) != 0 {
1061 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1062 }
1063 }
1064 output
1065}
1066#[derive(Clone, Copy)]
1067enum PlanOutput {
1068 Rows,
1069 Aggregate { grouped: bool },
1070}
1071
1072struct Plan<'a> {
1073 primary: usize,
1074 index: Option<&'a IndexSchema>,
1075 prefix: Vec<u8>,
1076 fixed_components: usize,
1077 terms: Vec<Term>,
1078 selected: u16,
1079 span_fields: u16,
1081 binding: [u8; 32],
1082 projection: Option<u16>,
1083 distinct: distinct::Strategy,
1084 sort: Option<Vec<(usize, bool)>>,
1085 descending: bool,
1086}
1087impl<'a> Plan<'a> {
1088 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1089 self.terms.split_inclusive(|term| !term.or_next)
1090 }
1091
1092 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1093 self.index = Some(path.index);
1094 self.prefix = path.prefix;
1095 self.fixed_components = path.fixed;
1096 self.selected |= entity.key_fields();
1097 }
1098
1099 fn admit(
1100 entity: &'a EntitySchema,
1101 request: &Request<'_>,
1102 schema: [u8; 32],
1103 incarnation: [u8; 16],
1104 projection: Option<&TypeSchema>,
1105 output: PlanOutput,
1106 ) -> Result<Self, Error> {
1107 if request.over_limit
1108 || !(1..=32).contains(&request.rows)
1109 || !(1..=MAX_WORK).contains(&request.work)
1110 || !(1..=MAX_OUTPUT).contains(&request.bytes)
1111 {
1112 return Err(Error::Limit);
1113 }
1114 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1115 {
1116 return Err(Error::InvalidQuery);
1117 }
1118 for value in request
1120 .predicates
1121 .iter()
1122 .filter_map(|p| match &p.operand {
1123 QueryOperand::Literal(value) => Some(value),
1124 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1125 })
1126 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1127 {
1128 if match value {
1129 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1130 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1131 _ => false,
1132 } {
1133 return Err(Error::Limit);
1134 }
1135 }
1136 let primary = entity
1137 .field_position(entity.primary_key)
1138 .filter(|&i| !entity.fields[i].optional)
1139 .ok_or(Error::InvalidQuery)?;
1140 let mut plan = Self {
1141 primary,
1142 index: None,
1143 prefix: prefix(2, entity.id),
1144 fixed_components: 0,
1145 terms: Vec::new(),
1146 selected: 1 << primary,
1147 span_fields: 0,
1148 binding: [0; 32],
1149 projection: projection
1150 .map(|output| admit_projection(entity, output))
1151 .transpose()?,
1152 distinct: distinct::Strategy::Identity,
1153 sort: None,
1154 descending: request.descending ^ request.primary_descending(entity),
1155 };
1156 for predicate in &request.predicates {
1157 let position = entity
1158 .field_position(predicate.field)
1159 .ok_or(Error::InvalidQuery)?;
1160 let field = &entity.fields[position];
1161 let member = if predicate.comparison == Comparison::Contains {
1162 member_type(field.value)
1163 } else {
1164 None
1165 };
1166 let operand = match predicate.operand {
1167 QueryOperand::Length(length) => {
1168 let supported = match key::operand_type(field.value) {
1169 FieldType::Text { .. }
1170 | FieldType::Blob { .. }
1171 | FieldType::List { .. } => true,
1172 FieldType::Named(link) => matches!(
1173 (link.definition)().body,
1174 TypeBody::Map { .. } | TypeBody::Set { .. }
1175 ),
1176 _ => false,
1177 };
1178 if !supported || !predicate.comparison.is_relational() {
1179 return Err(Error::InvalidQuery);
1180 }
1181 plan.span_fields |= 1 << position;
1182 TermOperand::Length(length)
1183 }
1184 QueryOperand::Field(name) => {
1185 let right = entity.field_position(name).ok_or(Error::InvalidQuery)?;
1186 let right_type = entity.fields[right].value;
1187 let left_type = member.unwrap_or(field.value);
1188 let compatible = left_type == right_type
1189 || matches!(
1190 (left_type, right_type),
1191 (FieldType::Text { .. }, FieldType::Text { .. })
1192 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1193 );
1194 if !compatible
1195 || !key::supports(left_type)
1196 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1197 {
1198 return Err(Error::InvalidQuery);
1199 }
1200 plan.selected |= 1 << right;
1201 if let Some(item) = member {
1202 plan.span_fields |= 1 << position;
1203 TermOperand::Member {
1204 item,
1205 needle: MemberNeedle::Field(right),
1206 }
1207 } else {
1208 plan.selected |= 1 << position;
1209 TermOperand::Field(right)
1210 }
1211 }
1212 QueryOperand::Literal(value) => {
1213 if let Some(item) = member {
1214 if !key::supports(item) {
1215 return Err(Error::InvalidQuery);
1216 }
1217 value.admit(item, false)?;
1218 let mut bytes = Vec::new();
1219 value.append_component(false, &mut bytes);
1220 plan.span_fields |= 1 << position;
1221 TermOperand::Member {
1222 item,
1223 needle: MemberNeedle::Literal(bytes),
1224 }
1225 } else {
1226 let absent = value == IndexValue::Absent;
1227 if key::supports(field.value) {
1228 plan.selected |= 1 << position;
1229 } else if absent
1230 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1231 {
1232 plan.span_fields |= 1 << position;
1233 } else {
1234 return Err(Error::InvalidQuery);
1235 }
1236 predicate
1237 .comparison
1238 .admit(field.value, field.optional, value)?;
1239 let mut bytes = Vec::new();
1240 value.append_component(field.optional, &mut bytes);
1241 TermOperand::Literal { bytes, absent }
1242 }
1243 }
1244 };
1245 plan.terms.push(Term {
1246 position,
1247 comparison: predicate.comparison,
1248 operand,
1249 or_next: predicate.or_next,
1250 });
1251 }
1252 match order::select(entity, request, output)? {
1255 order::Path::Primary => {}
1256 order::Path::Index(path) => plan.use_index(entity, path),
1257 order::Path::Sort(fields) => {
1258 for &(position, _) in &fields {
1259 plan.selected |= 1 << position;
1260 }
1261 plan.sort = Some(fields);
1262 }
1263 }
1264 if request.distinct {
1265 plan.distinct = distinct::admit(
1266 entity,
1267 request,
1268 plan.projection,
1269 plan.index,
1270 plan.fixed_components,
1271 plan.sort.is_some(),
1272 )?;
1273 if plan.distinct == distinct::Strategy::Complete {
1274 plan.selected |= plan.projection.ok_or(Error::InvalidQuery)?;
1275 }
1276 }
1277 let mut hash = Sha256::new();
1278 hash.update(b"ic-db:query:v1\0");
1279 hash.update(schema);
1280 hash.update(incarnation);
1281 hash.update([u8::from(request.descending)]);
1282 hash.update((plan.prefix.len() as u32).to_le_bytes());
1283 hash.update(&plan.prefix);
1284 for term in &plan.terms {
1285 hash.update([term.position as u8, term.comparison as u8]);
1286 match &term.operand {
1287 TermOperand::Literal { bytes, .. }
1288 | TermOperand::Member {
1289 needle: MemberNeedle::Literal(bytes),
1290 ..
1291 } => {
1292 hash.update((bytes.len() as u32).to_le_bytes());
1293 hash.update(bytes);
1294 }
1295 TermOperand::Length(length) => {
1296 hash.update((u32::MAX - 1).to_le_bytes());
1297 hash.update(length.to_le_bytes());
1298 }
1299 TermOperand::Field(right)
1300 | TermOperand::Member {
1301 needle: MemberNeedle::Field(right),
1302 ..
1303 } => {
1304 hash.update(u32::MAX.to_le_bytes());
1306 hash.update([*right as u8]);
1307 }
1308 }
1309 }
1310 let clauses = plan
1313 .terms
1314 .iter()
1315 .enumerate()
1316 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1317 if clauses != 0 {
1318 hash.update(b"or-clauses\0");
1319 hash.update([clauses]);
1320 }
1321 if let Some(order) = &request.order {
1322 hash.update(b"order\0");
1323 hash.update([order.len() as u8]);
1324 for name in order {
1325 hash.update([entity.field_position(name).ok_or(Error::InvalidQuery)? as u8]);
1327 }
1328 }
1329 if request.order_descending != 0 {
1330 hash.update(b"order-directions\0");
1331 hash.update([request.order_descending]);
1332 }
1333 if let Some(mask) = plan.projection {
1336 hash.update(b"projection\0");
1337 hash.update(mask.to_le_bytes());
1338 }
1339 if request.distinct {
1340 hash.update(b"distinct\0");
1341 }
1342 plan.binding = hash.finalize().into();
1343 if let Some(cursor) = request.cursor {
1344 if cursor.binding != plan.binding {
1345 return Err(Error::InvalidCursor);
1346 }
1347 plan.validate_position(entity, &cursor.position)
1348 .map_err(|_| Error::InvalidCursor)?;
1349 }
1350 Ok(plan)
1351 }
1352
1353 fn validate_position(&self, entity: &EntitySchema, bytes: &[u8]) -> Result<(), Error> {
1354 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
1355 return Err(Error::InvalidCursor);
1356 }
1357 if let Some(index) = self.index {
1358 let mut remaining = bytes.get(9..).ok_or(Error::InvalidCursor)?;
1359 for name in index.fields {
1360 consume_index_component(entity, index, name, &mut remaining)?;
1361 }
1362 if !index.unique {
1363 key::consume(&mut remaining, entity.key_type()?)?;
1364 }
1365 if !remaining.is_empty() {
1366 return Err(Error::InvalidCursor);
1367 }
1368 } else {
1369 RowKey::decode(
1370 bytes.get(5..).ok_or(Error::InvalidCursor)?,
1371 entity.key_type()?,
1372 )?;
1373 }
1374 Ok(())
1375 }
1376
1377 fn cursor(&self, position: &[u8], inclusive: bool) -> QueryCursor {
1378 QueryCursor {
1379 binding: self.binding,
1380 position: position.to_vec(),
1381 inclusive,
1382 }
1383 }
1384}
1385
1386fn consume_index_component(
1388 entity: &EntitySchema,
1389 index: &IndexSchema,
1390 name: &str,
1391 remaining: &mut &[u8],
1392) -> Result<(), Error> {
1393 let field = entity
1394 .fields
1395 .iter()
1396 .find(|f| f.name == name)
1397 .ok_or(Error::InvalidQuery)?;
1398 if field.optional {
1399 let (&presence, rest) = remaining.split_first().ok_or(Error::InvalidCursor)?;
1400 *remaining = rest;
1401 match presence {
1402 0 if !index.present_only => return Ok(()),
1403 1 => {}
1404 _ => return Err(Error::InvalidCursor),
1405 }
1406 }
1407 key::consume(remaining, field.value)
1408}
1409
1410#[inline(never)]
1413#[expect(
1414 clippy::needless_pass_by_value,
1415 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1416)]
1417fn fetch_rows<M: Memory>(
1418 db: &Database<M>,
1419 entity: &EntitySchema,
1420 request: Request<'_>,
1421 projection: Option<&TypeSchema>,
1422) -> Result<QueryPage<Vec<u8>>, Error> {
1423 db.schema.admits(entity)?;
1424 let plan = Plan::admit(
1425 entity,
1426 &request,
1427 db.schema.fingerprint(),
1428 db.incarnation,
1429 projection,
1430 PlanOutput::Rows,
1431 )?;
1432 execute(&db.map, entity, &request, &plan, None)
1433}
1434
1435fn execute<M: Memory>(
1436 map: &Map<M>,
1437 entity: &EntitySchema,
1438 request: &Request<'_>,
1439 plan: &Plan<'_>,
1440 mut aggregate: Option<aggregate::Accumulator<'_>>,
1441) -> Result<QueryPage<Vec<u8>>, Error> {
1442 execute_inner(map, entity, request, plan, aggregate.as_mut(), None)
1443}
1444
1445const STEP_INPUT_BYTES: usize = 64 * 1024;
1448const CANDIDATE_BYTES: usize = crate::codec::MAX_ROW_BYTES + 2 * crate::MAX_INDEX_KEY_BYTES;
1449
1450fn execute_inner<M: Memory>(
1451 map: &Map<M>,
1452 entity: &EntitySchema,
1453 request: &Request<'_>,
1454 plan: &Plan<'_>,
1455 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1456 mut input_bytes: Option<&mut usize>,
1457) -> Result<QueryPage<Vec<u8>>, Error> {
1458 let mut page = QueryPage {
1459 rows: Vec::new(),
1460 next: None,
1461 examined: 0,
1462 fetched: 0,
1463 output_bytes: 0,
1464 };
1465 let Some(bounds) = range::bounds(entity, request, plan)? else {
1466 return Ok(page);
1467 };
1468 let terminal = range::terminal_key(&bounds, plan.descending);
1469 let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
1470 let mut collected = if plan.distinct == distinct::Strategy::Complete {
1471 Some(distinct::Collection::new(
1472 plan.projection.ok_or(Error::InvalidQuery)?,
1473 ))
1474 } else {
1475 None
1476 };
1477 let mut sorted = plan
1478 .sort
1479 .as_ref()
1480 .map(|_| sort::Collection::new(request, plan.distinct));
1481 let mut component = Vec::new();
1482 let mut right_component = Vec::new();
1483 let mut previous = if let Some(cursor) = request.cursor.filter(|c| !c.inclusive) {
1486 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1487 } else {
1488 None
1489 };
1490 let primary_type = entity.fields[plan.primary].value;
1491 while let Some(entry) = if plan.descending {
1492 entries.next_back()
1493 } else {
1494 entries.next()
1495 } {
1496 if request.work == 0 {
1500 return Err(Error::Limit);
1501 }
1502 page.examined += 1;
1503 let stored_key = entry.key();
1504 let mut read_bytes = stored_key.len();
1505 let (owner, bytes) = if plan.index.is_some() {
1506 let owner_bytes = entry.value();
1507 read_bytes += owner_bytes.len();
1508 let owner = RowKey::decode(&owner_bytes, primary_type)?;
1509 let bytes = map.get(&row_key(entity.id, owner)).ok_or(Error::Corrupt)?;
1510 (owner, bytes)
1511 } else {
1512 (
1513 RowKey::decode(&stored_key[5..], primary_type)?,
1514 entry.value(),
1515 )
1516 };
1517 if let Some(used) = input_bytes.as_deref_mut() {
1518 read_bytes += bytes.len();
1519 if read_bytes > CANDIDATE_BYTES {
1520 return Err(Error::Corrupt);
1521 }
1522 *used += read_bytes;
1523 }
1524 page.fetched += 1;
1525 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
1526 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1527 entity.inspect_fields(
1528 &bytes,
1529 plan.selected,
1530 &mut values,
1531 (plan.span_fields != 0
1532 || plan.projection.is_some()
1533 || aggregate.as_ref().is_some_and(|a| a.needs_spans()))
1534 .then_some(&mut spans),
1535 )?;
1536 if RowKey::from_index(values[plan.primary])? != owner {
1537 return Err(Error::Corrupt);
1538 }
1539 if plan.index.is_some() {
1540 validate_index_entry(entity, &entity.row_info(&values)?, owner, stored_key)?;
1541 }
1542 let mut accepts = |term: &Term| -> Result<bool, Error> {
1543 let value = values[term.position];
1544 component.clear();
1545 let (operand, optional) = match &term.operand {
1546 TermOperand::Literal { absent: true, .. }
1547 if plan.span_fields & (1 << term.position) != 0 =>
1548 {
1549 let absent = bytes[usize::from(spans[term.position].0)] == 0;
1550 return Ok(term.comparison.accepts_absent(absent));
1551 }
1552 TermOperand::Member { item, needle } => {
1553 let needle = match needle {
1554 MemberNeedle::Literal(bytes) => bytes.as_slice(),
1555 MemberNeedle::Field(right) => {
1556 let value = values[*right];
1557 if value == IndexValue::Absent {
1558 return Ok(false);
1559 }
1560 right_component.clear();
1561 value.append_component(false, &mut right_component);
1562 &right_component
1563 }
1564 };
1565 let (start, end) = spans[term.position];
1566 return contains_member(
1567 &bytes[usize::from(start)..usize::from(end)],
1568 entity.fields[term.position].optional,
1569 *item,
1570 needle,
1571 &mut component,
1572 );
1573 }
1574 TermOperand::Length(length) => {
1575 let (start, end) = spans[term.position];
1576 let span = &bytes[usize::from(start)..usize::from(end)];
1577 let actual =
1578 crate::codec::validated_length(span, entity.fields[term.position].optional)
1579 .map(u32::to_be_bytes);
1580 return Ok(term.comparison.accepts(
1581 actual.as_ref().map(|v| v.as_slice()),
1582 Some(&length.to_be_bytes()),
1583 false,
1584 ));
1585 }
1586 TermOperand::Literal { bytes, absent } => (
1587 (!absent).then_some(bytes.as_slice()),
1588 entity.fields[term.position].optional,
1589 ),
1590 TermOperand::Field(right) => {
1591 let rhs = values[*right];
1592 right_component.clear();
1593 rhs.append_component(false, &mut right_component);
1594 (
1595 (rhs != IndexValue::Absent).then_some(right_component.as_slice()),
1596 false,
1597 )
1598 }
1599 };
1600 value.append_component(optional, &mut component);
1601 Ok(term.comparison.accepts(
1602 (value != IndexValue::Absent).then_some(component.as_slice()),
1603 operand,
1604 optional,
1605 ))
1606 };
1607 let matches = 'matches: {
1608 'clause: for clause in plan.clauses() {
1609 for term in clause {
1610 if accepts(term)? {
1611 continue 'clause;
1612 }
1613 }
1614 break 'matches false;
1615 }
1616 true
1617 };
1618 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
1619 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
1620 if matches && let Some(accumulator) = aggregate.as_mut() {
1621 accumulator.push(entity, &values, &bytes, &spans)?;
1622 if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
1623 return Ok(page);
1625 }
1626 } else if matches && let Some(collection) = collected.as_mut() {
1627 collection.push(entity, request, &values, &bytes, &spans)?;
1628 } else if matches && let Some(collection) = sorted.as_mut() {
1629 collection.push(entity, plan, &values, &bytes, &spans)?;
1630 } else if matches && !duplicate {
1631 let size = plan
1632 .projection
1633 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
1634 if size > request.bytes {
1635 return Err(Error::RowTooLarge);
1636 }
1637 if size > request.bytes - page.output_bytes {
1638 page.next = Some(plan.cursor(stored_key, true));
1639 return Ok(page);
1640 }
1641 page.output_bytes += size;
1642 if let Some(mask) = plan.projection {
1643 page.rows.push(copy_projection(&bytes, &spans, mask, size));
1644 } else {
1645 page.rows.push(bytes);
1646 }
1647 if let Some(boundary) = boundary {
1648 previous = Some(boundary.to_vec());
1649 }
1650 }
1651 if page.rows.len() == request.rows
1652 || page.examined == request.work
1653 || input_bytes
1654 .as_deref()
1655 .is_some_and(|used| *used > STEP_INPUT_BYTES - CANDIDATE_BYTES)
1656 {
1657 if terminal == Some(stored_key) {
1658 break;
1659 }
1660 if (aggregate.is_some() && input_bytes.is_none())
1661 || collected.is_some()
1662 || sorted.is_some()
1663 {
1664 return Err(Error::Limit);
1667 }
1668 page.next = Some(plan.cursor(stored_key, false));
1669 return Ok(page);
1670 }
1671 }
1672 if let Some(collection) = collected {
1673 page.output_bytes = collection.output_bytes;
1674 page.rows = collection.rows;
1675 }
1676 if let Some(collection) = sorted {
1677 collection.finish(request.bytes, &mut page)?;
1678 }
1679 Ok(page)
1680}