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_length(self, actual: Option<u32>, threshold: u32) -> bool {
136 let encoded = actual.map(u32::to_be_bytes);
137
138 self.accepts(
139 encoded.as_ref().map(|v| v.as_slice()),
140 Some(&threshold.to_be_bytes()),
141 false,
142 )
143 }
144
145 fn accepts_absent(self, other_absent: bool) -> bool {
148 match self {
149 Self::Eq => other_absent,
150 Self::Ne => !other_absent,
151 _ => false,
152 }
153 }
154}
155
156fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
158 let Some(start) = memchr::memmem::find(actual, needle) else {
159 return false;
160 };
161 if start == 0 || actual[start - 1] != 0 {
162 return true;
163 }
164 fn raw(content: &[u8]) -> Vec<u8> {
168 let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
169 let mut encoded = content.iter();
170 while let Some(&byte) = encoded.next() {
171 bytes.push(byte);
172 if byte == 0 {
173 encoded.next();
174 }
175 }
176 bytes
177 }
178 memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
179}
180
181#[derive(Clone, Debug, PartialEq, Eq)]
185pub struct QueryCursor {
186 binding: [u8; 32],
187 position: Vec<u8>,
188 inclusive: bool,
189}
190impl QueryCursor {
191 pub(super) const MAX_ENCODED_BYTES: usize = 34 + crate::MAX_INDEX_KEY_BYTES;
192
193 #[must_use]
195 pub fn to_bytes(&self) -> Vec<u8> {
196 let mut bytes = vec![1, u8::from(self.inclusive)];
197 bytes.extend(self.binding);
198 bytes.extend(&self.position);
199 bytes
200 }
201
202 pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
206 if !(35..=Self::MAX_ENCODED_BYTES).contains(&bytes.len()) || bytes[0] != 1 || bytes[1] > 1 {
207 return Err(Error::InvalidCursor);
208 }
209 Ok(Self {
210 binding: bytes[2..34].try_into().map_err(|_| Error::InvalidCursor)?,
211 position: bytes[34..].to_vec(),
212 inclusive: bytes[1] == 1,
213 })
214 }
215}
216
217#[derive(Debug)]
220pub struct QueryPage<T> {
221 pub rows: Vec<T>,
223 pub next: Option<QueryCursor>,
225 pub examined: usize,
227 pub fetched: usize,
229 pub output_bytes: usize,
231}
232
233impl QueryPage<Vec<u8>> {
234 #[inline(never)]
235 pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
236 Ok(QueryPage {
237 rows: self
238 .rows
239 .iter()
240 .map(|bytes| E::decode(bytes))
241 .collect::<Result<_, _>>()?,
242 next: self.next,
243 examined: self.examined,
244 fetched: self.fetched,
245 output_bytes: self.output_bytes,
246 })
247 }
248
249 #[inline(never)]
250 fn decode_projection<R: Value>(self) -> Result<QueryPage<R>, Error> {
251 Ok(QueryPage {
252 rows: self
253 .rows
254 .iter()
255 .map(|bytes| {
256 let mut reader = Decoder::new(bytes)?;
257 let row = R::decode_from(&mut reader)?;
259 reader.finish()?;
260 Ok(row)
261 })
262 .collect::<Result<_, Error>>()?,
263 next: self.next,
264 examined: self.examined,
265 fetched: self.fetched,
266 output_bytes: self.output_bytes,
267 })
268 }
269}
270
271#[derive(Clone, Copy, Debug, PartialEq, Eq)]
273pub enum QueryOperand<'a> {
274 Literal(IndexValue<'a>),
276 Length(u32),
278 Field(&'a str),
280}
281
282struct Predicate<'a> {
283 field: &'a str,
284 comparison: Comparison,
285 operand: QueryOperand<'a>,
286 or_next: bool,
288}
289struct Request<'a> {
290 groups: aggregate::GroupRequest<'a>,
291 predicates: Vec<Predicate<'a>>,
292 index: Option<(&'a str, Vec<IndexValue<'a>>)>,
293 order: Option<Vec<&'a str>>,
294 order_descending: u8,
295 descending: bool,
296 distinct: bool,
297 rows: usize,
298 work: usize,
299 bytes: usize,
300 cursor: Option<&'a QueryCursor>,
301 over_limit: bool,
302}
303
304impl Default for Request<'_> {
305 fn default() -> Self {
306 Self {
307 groups: aggregate::GroupRequest::default(),
308 predicates: Vec::new(),
309 index: None,
310 order: None,
311 order_descending: 0,
312 descending: false,
313 distinct: false,
314 rows: 32,
315 work: 128,
316 bytes: MAX_OUTPUT,
317 cursor: None,
318 over_limit: false,
319 }
320 }
321}
322
323impl<'a> Request<'a> {
326 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
327 self.predicates.split_inclusive(|p| !p.or_next)
328 }
329
330 #[inline(never)]
331 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
332 if self.predicates.len() == MAX_TERMS {
333 self.over_limit = true;
334 } else {
335 self.predicates.push(Predicate {
336 field,
337 comparison,
338 operand,
339 or_next: false,
340 });
341 }
342 }
343
344 #[inline(never)]
345 fn or_clause(
346 &mut self,
347 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
348 ) {
349 let count = alternatives.len();
350 if count == 0 || count > MAX_TERMS - self.predicates.len() {
351 self.over_limit = true;
352 } else {
353 self.predicates.extend(alternatives.enumerate().map(
354 |(i, (field, comparison, operand))| Predicate {
355 field,
356 comparison,
357 operand,
358 or_next: i + 1 < count,
359 },
360 ));
361 }
362 }
363
364 #[inline(never)]
365 fn filter_not_in(
366 &mut self,
367 field: &'a str,
368 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
369 ) {
370 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
371 self.over_limit = true;
372 return;
373 }
374 for value in values {
375 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
376 }
377 }
378
379 #[inline(never)]
380 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
381 if values.len() > 4 {
382 self.over_limit = true;
383 } else {
384 self.index = Some((name, values.to_vec()));
385 }
386 }
387
388 #[inline(never)]
389 fn order_by(&mut self, fields: &[&'a str]) {
390 self.order_descending = 0;
391 if fields.len() > 4 {
392 self.over_limit = true;
393 } else {
394 self.order = Some(fields.to_vec());
395 }
396 }
397
398 #[inline(never)]
399 fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
400 if fields.len() > 4 {
401 self.over_limit = true;
402 return;
403 }
404 self.order = Some(Vec::with_capacity(fields.len()));
405 self.order_descending = 0;
406 for &(field, direction) in fields {
407 self.append_order(field, direction);
408 }
409 }
410
411 fn append_order(&mut self, field: &'a str, direction: SortDirection) {
412 let fields = self.order.get_or_insert_with(Vec::new);
413 if fields.len() == 4 {
414 self.over_limit = true;
415 return;
416 }
417 if direction == SortDirection::Descending {
418 self.order_descending |= 1 << fields.len();
419 }
420 fields.push(field);
421 }
422
423 fn primary_descending(&self, entity: &EntitySchema) -> bool {
424 self.order_descending != 0
425 && self.order.as_ref().is_some_and(|fields| {
426 fields.last() == Some(&entity.primary_key)
427 && self.order_descending & (1 << (fields.len() - 1)) != 0
428 })
429 }
430}
431
432pub(super) fn source_page<M: Memory>(
434 map: &Map<M>,
435 entity: &EntitySchema,
436 binding: [u8; 32],
437 incarnation: [u8; 16],
438 cursor: Option<&QueryCursor>,
439 rows: usize,
440 bytes: usize,
441) -> Result<QueryPage<Vec<u8>>, Error> {
442 let request = Request {
443 rows,
444 work: rows,
445 bytes,
446 cursor,
447 ..Request::default()
448 };
449 let plan = Plan::admit(
450 entity,
451 &request,
452 binding,
453 incarnation,
454 None,
455 PlanOutput::Rows,
456 )?;
457 execute(map, entity, &request, &plan, None)
458}
459
460enum QuerySource<'a, M: Memory> {
461 Direct(&'a Database<M>),
462 Session(Rc<RefCell<Database<M>>>),
463}
464
465enum QueryRead<'a, M: Memory> {
466 Direct(&'a Database<M>),
467 Session(Ref<'a, Database<M>>),
468}
469
470impl<M: Memory> Deref for QueryRead<'_, M> {
471 type Target = Database<M>;
472
473 fn deref(&self) -> &Self::Target {
474 match self {
475 Self::Direct(db) => db,
476 Self::Session(db) => db,
477 }
478 }
479}
480
481impl<M: Memory> QuerySource<'_, M> {
482 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
483 match self {
484 Self::Direct(db) => Ok(QueryRead::Direct(db)),
485 Self::Session(db) => db
486 .try_borrow()
487 .map(QueryRead::Session)
488 .map_err(|_| Error::BorrowConflict),
489 }
490 }
491}
492
493pub struct Query<'a, E, M: Memory> {
497 db: QuerySource<'a, M>,
498 request: Request<'a>,
499 entity: PhantomData<E>,
500}
501impl<M: Memory> Database<M> {
502 #[must_use]
504 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
505 Query {
506 db: QuerySource::Direct(self),
507 entity: PhantomData,
508 request: Request::default(),
509 }
510 }
511}
512impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
513 pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
514 Self {
515 db: QuerySource::Session(db),
516 request: Request::default(),
517 entity: PhantomData,
518 }
519 }
520
521 #[must_use]
533 pub fn distinct(mut self) -> Self {
534 self.request.distinct = true;
535 self
536 }
537
538 #[must_use]
548 pub fn filter(
549 mut self,
550 field: &'a str,
551 comparison: Comparison,
552 value: impl Into<IndexValue<'a>>,
553 ) -> Self {
554 self.request
555 .filter(field, comparison, QueryOperand::Literal(value.into()));
556 self
557 }
558
559 #[must_use]
561 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
562 self.filter(field, Comparison::Eq, value)
563 }
564
565 #[must_use]
567 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
568 self.filter(field, Comparison::Ne, value)
569 }
570
571 #[must_use]
573 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
574 self.filter(field, Comparison::Lt, value)
575 }
576
577 #[must_use]
579 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
580 self.filter(field, Comparison::Le, value)
581 }
582
583 #[must_use]
585 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
586 self.filter(field, Comparison::Gt, value)
587 }
588
589 #[must_use]
591 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
592 self.filter(field, Comparison::Ge, value)
593 }
594
595 #[must_use]
601 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
602 self.request
603 .filter(left, comparison, QueryOperand::Field(right));
604 self
605 }
606
607 #[must_use]
611 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
612 self.request
613 .filter(field, comparison, QueryOperand::Length(length));
614 self
615 }
616
617 #[must_use]
620 pub fn filter_present(self, field: &'a str) -> Self {
621 self.filter(field, Comparison::Ne, IndexValue::Absent)
622 }
623
624 #[must_use]
627 pub fn filter_absent(self, field: &'a str) -> Self {
628 self.filter(field, Comparison::Eq, IndexValue::Absent)
629 }
630
631 #[must_use]
638 pub fn filter_between(
639 self,
640 field: &'a str,
641 lower: impl Into<IndexValue<'a>>,
642 upper: impl Into<IndexValue<'a>>,
643 ) -> Self {
644 self.filter(field, Comparison::Ge, lower)
645 .filter(field, Comparison::Le, upper)
646 }
647
648 #[must_use]
656 pub fn filter_not_between(
657 self,
658 field: &'a str,
659 lower: impl Into<IndexValue<'a>>,
660 upper: impl Into<IndexValue<'a>>,
661 ) -> Self {
662 self.filter_any(&[
663 (field, Comparison::Lt, lower.into()),
664 (field, Comparison::Gt, upper.into()),
665 ])
666 }
667
668 #[must_use]
673 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
674 self.filter_fields(field, Comparison::Ge, lower)
675 .filter_fields(field, Comparison::Le, upper)
676 }
677
678 #[must_use]
683 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
684 self.filter_any_operands(&[
685 (field, Comparison::Lt, QueryOperand::Field(lower)),
686 (field, Comparison::Gt, QueryOperand::Field(upper)),
687 ])
688 }
689
690 #[must_use]
697 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
698 self.request.or_clause(
699 alternatives
700 .iter()
701 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
702 );
703 self
704 }
705
706 #[must_use]
711 pub fn filter_any_operands(
712 mut self,
713 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
714 ) -> Self {
715 self.request.or_clause(alternatives.iter().copied());
716 self
717 }
718
719 #[must_use]
729 pub fn filter_in(
730 mut self,
731 field: &'a str,
732 values: &[impl Copy + Into<IndexValue<'a>>],
733 ) -> Self {
734 self.request.or_clause(
735 values
736 .iter()
737 .copied()
738 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
739 );
740 self
741 }
742
743 #[must_use]
751 pub fn filter_not_in(
752 mut self,
753 field: &'a str,
754 values: &[impl Copy + Into<IndexValue<'a>>],
755 ) -> Self {
756 self.request
757 .filter_not_in(field, values.iter().copied().map(Into::into));
758 self
759 }
760
761 #[must_use]
766 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
767 self.request.using_index(name, values);
768 self
769 }
770
771 #[must_use]
774 pub fn order_asc(mut self, field: &'a str) -> Self {
775 self.request.append_order(field, SortDirection::Ascending);
776 self
777 }
778
779 #[must_use]
782 pub fn order_desc(mut self, field: &'a str) -> Self {
783 self.request.append_order(field, SortDirection::Descending);
784 self
785 }
786
787 #[must_use]
797 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
798 self.request.order_by(fields);
799 self
800 }
801
802 #[must_use]
807 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
808 self.request.order_by_each(fields);
809 self
810 }
811
812 #[must_use]
814 pub fn descending(mut self) -> Self {
815 self.request.descending = true;
816 self
817 }
818
819 #[must_use]
826 pub fn limit(mut self, rows: usize) -> Self {
827 self.request.rows = rows;
828 self
829 }
830
831 #[must_use]
833 pub fn work_limit(mut self, candidates: usize) -> Self {
834 self.request.work = candidates;
835 self
836 }
837
838 #[cfg(feature = "test-support")]
840 #[doc(hidden)]
841 #[must_use]
842 pub fn test_output_limit(mut self, bytes: usize) -> Self {
843 self.request.bytes = bytes;
844 self
845 }
846
847 #[must_use]
849 pub fn after(mut self, cursor: &'a QueryCursor) -> Self {
850 self.request.cursor = Some(cursor);
851 self
852 }
853
854 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
861 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
862 }
863
864 pub fn first(self) -> Result<Option<E>, Error> {
870 let mut page = self.probe_matches(1)?;
871 match page.rows.pop() {
872 None if page.next.is_some() => Err(Error::Limit),
873 result => Ok(result),
874 }
875 }
876
877 pub fn try_one(self) -> Result<Option<E>, Error> {
884 if self.request.cursor.is_some() {
885 return Err(Error::InvalidQuery);
886 }
887 let mut page = self.probe_matches(2)?;
888 if page.rows.len() == 2 {
889 return Err(Error::MultipleMatches);
890 }
891 if page.next.is_some() {
892 return Err(Error::Limit);
893 }
894 Ok(page.rows.pop())
895 }
896
897 fn probe_matches(self, rows: usize) -> Result<QueryPage<E>, Error> {
898 if !(1..=32).contains(&self.request.rows) {
899 return Err(Error::Limit);
900 }
901 self.limit(rows).fetch()
902 }
903
904 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
914 let raw = fetch_rows(
915 &*self.db.read()?,
916 E::SCHEMA,
917 self.request,
918 Some(R::definition()),
919 )?;
920 raw.decode_projection()
921 }
922}
923
924fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u16, Error> {
928 let TypeBody::Record(fields) = &output.body else {
929 return Err(Error::InvalidQuery);
930 };
931 if fields.is_empty()
932 || fields.len() > crate::schema::MAX_FIELDS
933 || fields.windows(2).any(|w| w[0].name >= w[1].name)
934 {
935 return Err(Error::InvalidQuery);
936 }
937 let mut source = TypeGraph::default();
938 let mut target = TypeGraph::default();
939 let mut mask = 0;
940 for field in *fields {
941 let position = entity
942 .field_position(field.name)
943 .ok_or(Error::InvalidQuery)?;
944 let stored = &entity.fields[position];
945 if stored.value != field.value || stored.optional != field.optional {
946 return Err(Error::InvalidQuery);
947 }
948 source
949 .include(stored.value)
950 .map_err(|_| Error::InvalidQuery)?;
951 target
952 .include(field.value)
953 .map_err(|_| Error::InvalidQuery)?;
954 mask |= 1 << position;
955 }
956 if !source.contains(&target) {
957 return Err(Error::InvalidQuery);
958 }
959 Ok(mask)
960}
961
962struct Term {
963 position: usize,
964 comparison: Comparison,
965 operand: TermOperand,
966 or_next: bool,
967}
968
969enum TermOperand {
970 Literal {
971 bytes: Vec<u8>,
972 absent: bool,
973 },
974 Member {
975 item: FieldType,
976 needle: MemberNeedle,
977 },
978 Field(usize),
979 Length(u32),
980}
981
982enum MemberNeedle {
983 Literal(Vec<u8>),
984 Field(usize),
985}
986
987fn member_type(field: FieldType) -> Option<FieldType> {
988 match key::operand_type(field) {
989 FieldType::List { item, .. } => Some(*item),
990 FieldType::Named(link) => match (link.definition)().body {
991 TypeBody::Set { item, .. } => Some(item),
992 _ => None,
993 },
994 _ => None,
995 }
996}
997
998fn contains_member(
1000 span: &[u8],
1001 optional: bool,
1002 item: FieldType,
1003 needle: &[u8],
1004 scratch: &mut Vec<u8>,
1005) -> Result<bool, Error> {
1006 let mut reader = Decoder::new(span)?;
1007 if optional && !reader.boolean()? {
1008 return Ok(false);
1009 }
1010 for _ in 0..reader.nat32()? {
1011 scratch.clear();
1012 IndexValue::read(&mut reader, item)?.append_component(false, scratch);
1013 if scratch.as_slice() == needle {
1014 return Ok(true);
1015 }
1016 }
1017 Ok(false)
1018}
1019
1020fn admit_ordered_fields(entity: &EntitySchema, mask: u16) -> Result<(), Error> {
1021 for (i, field) in entity.fields.iter().enumerate() {
1022 if mask & (1 << i) != 0 && !key::supports(field.value) {
1023 return Err(Error::InvalidQuery);
1024 }
1025 }
1026 Ok(())
1027}
1028
1029fn comparison_key(
1031 entity: &EntitySchema,
1032 mask: u16,
1033 values: &[IndexValue<'_>],
1034) -> Result<Vec<u8>, Error> {
1035 let mut key = Vec::new();
1036 for (i, field) in entity.fields.iter().enumerate() {
1037 if mask & (1 << i) != 0 {
1038 values[i].append_component(field.optional, &mut key);
1039 if key.len() > MAX_COMPARISON_KEY {
1040 return Err(Error::Limit);
1041 }
1042 }
1043 }
1044 Ok(key)
1045}
1046
1047fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1048 if size > limit {
1049 return Err(Error::RowTooLarge);
1050 }
1051 if size > limit - *used {
1052 return Err(Error::Limit);
1053 }
1054 *used += size;
1055 Ok(())
1056}
1057
1058fn projection_size(spans: &[(u16, u16)], mask: u16) -> usize {
1060 spans
1061 .iter()
1062 .enumerate()
1063 .filter(|(i, _)| mask & (1 << i) != 0)
1064 .map(|(_, (start, end))| usize::from(end - start))
1065 .sum()
1066}
1067
1068fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u16, size: usize) -> Vec<u8> {
1069 let mut output = Vec::with_capacity(size);
1070 for (i, &(start, end)) in spans.iter().enumerate() {
1071 if mask & (1 << i) != 0 {
1072 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1073 }
1074 }
1075 output
1076}
1077#[derive(Clone, Copy)]
1078enum PlanOutput {
1079 Rows,
1080 Aggregate { grouped: bool },
1081}
1082
1083struct Plan<'a> {
1084 primary: usize,
1085 index: Option<&'a IndexSchema>,
1086 prefix: Vec<u8>,
1087 fixed_components: usize,
1088 terms: Vec<Term>,
1089 selected: u16,
1090 span_fields: u16,
1092 binding: [u8; 32],
1093 projection: Option<u16>,
1094 distinct: distinct::Strategy,
1095 sort: Option<Vec<(usize, bool)>>,
1096 descending: bool,
1097}
1098impl<'a> Plan<'a> {
1099 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1100 self.terms.split_inclusive(|term| !term.or_next)
1101 }
1102
1103 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1104 self.index = Some(path.index);
1105 self.prefix = path.prefix;
1106 self.fixed_components = path.fixed;
1107 self.selected |= entity.key_fields();
1108 }
1109
1110 fn admit(
1111 entity: &'a EntitySchema,
1112 request: &Request<'_>,
1113 schema: [u8; 32],
1114 incarnation: [u8; 16],
1115 projection: Option<&TypeSchema>,
1116 output: PlanOutput,
1117 ) -> Result<Self, Error> {
1118 if request.over_limit
1119 || !(1..=32).contains(&request.rows)
1120 || !(1..=MAX_WORK).contains(&request.work)
1121 || !(1..=MAX_OUTPUT).contains(&request.bytes)
1122 {
1123 return Err(Error::Limit);
1124 }
1125 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1126 {
1127 return Err(Error::InvalidQuery);
1128 }
1129 for value in request
1131 .predicates
1132 .iter()
1133 .filter_map(|p| match &p.operand {
1134 QueryOperand::Literal(value) => Some(value),
1135 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1136 })
1137 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1138 {
1139 if match value {
1140 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1141 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1142 _ => false,
1143 } {
1144 return Err(Error::Limit);
1145 }
1146 }
1147 let primary = entity
1148 .field_position(entity.primary_key)
1149 .filter(|&i| !entity.fields[i].optional)
1150 .ok_or(Error::InvalidQuery)?;
1151 let mut plan = Self {
1152 primary,
1153 index: None,
1154 prefix: prefix(2, entity.id),
1155 fixed_components: 0,
1156 terms: Vec::new(),
1157 selected: 1 << primary,
1158 span_fields: 0,
1159 binding: [0; 32],
1160 projection: projection
1161 .map(|output| admit_projection(entity, output))
1162 .transpose()?,
1163 distinct: distinct::Strategy::Identity,
1164 sort: None,
1165 descending: request.descending ^ request.primary_descending(entity),
1166 };
1167 for predicate in &request.predicates {
1168 let position = entity
1169 .field_position(predicate.field)
1170 .ok_or(Error::InvalidQuery)?;
1171 let field = &entity.fields[position];
1172 let member = if predicate.comparison == Comparison::Contains {
1173 member_type(field.value)
1174 } else {
1175 None
1176 };
1177 let operand = match predicate.operand {
1178 QueryOperand::Length(length) => {
1179 let supported = match key::operand_type(field.value) {
1180 FieldType::Text { .. }
1181 | FieldType::Blob { .. }
1182 | FieldType::List { .. } => true,
1183 FieldType::Named(link) => matches!(
1184 (link.definition)().body,
1185 TypeBody::Map { .. } | TypeBody::Set { .. }
1186 ),
1187 _ => false,
1188 };
1189 if !supported || !predicate.comparison.is_relational() {
1190 return Err(Error::InvalidQuery);
1191 }
1192 plan.span_fields |= 1 << position;
1193 TermOperand::Length(length)
1194 }
1195 QueryOperand::Field(name) => {
1196 let right = entity.field_position(name).ok_or(Error::InvalidQuery)?;
1197 let right_type = entity.fields[right].value;
1198 let left_type = member.unwrap_or(field.value);
1199 let compatible = left_type == right_type
1200 || matches!(
1201 (left_type, right_type),
1202 (FieldType::Text { .. }, FieldType::Text { .. })
1203 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1204 );
1205 if !compatible
1206 || !key::supports(left_type)
1207 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1208 {
1209 return Err(Error::InvalidQuery);
1210 }
1211 plan.selected |= 1 << right;
1212 if let Some(item) = member {
1213 plan.span_fields |= 1 << position;
1214 TermOperand::Member {
1215 item,
1216 needle: MemberNeedle::Field(right),
1217 }
1218 } else {
1219 plan.selected |= 1 << position;
1220 TermOperand::Field(right)
1221 }
1222 }
1223 QueryOperand::Literal(value) => {
1224 if let Some(item) = member {
1225 if !key::supports(item) {
1226 return Err(Error::InvalidQuery);
1227 }
1228 value.admit(item, false)?;
1229 let mut bytes = Vec::new();
1230 value.append_component(false, &mut bytes);
1231 plan.span_fields |= 1 << position;
1232 TermOperand::Member {
1233 item,
1234 needle: MemberNeedle::Literal(bytes),
1235 }
1236 } else {
1237 let absent = value == IndexValue::Absent;
1238 if key::supports(field.value) {
1239 plan.selected |= 1 << position;
1240 } else if absent
1241 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1242 {
1243 plan.span_fields |= 1 << position;
1244 } else {
1245 return Err(Error::InvalidQuery);
1246 }
1247 predicate
1248 .comparison
1249 .admit(field.value, field.optional, value)?;
1250 let mut bytes = Vec::new();
1251 value.append_component(field.optional, &mut bytes);
1252 TermOperand::Literal { bytes, absent }
1253 }
1254 }
1255 };
1256 plan.terms.push(Term {
1257 position,
1258 comparison: predicate.comparison,
1259 operand,
1260 or_next: predicate.or_next,
1261 });
1262 }
1263 match order::select(entity, request, output)? {
1266 order::Path::Primary => {}
1267 order::Path::Index(path) => plan.use_index(entity, path),
1268 order::Path::Sort(fields) => {
1269 for &(position, _) in &fields {
1270 plan.selected |= 1 << position;
1271 }
1272 plan.sort = Some(fields);
1273 }
1274 }
1275 if request.distinct {
1276 plan.distinct = distinct::admit(
1277 entity,
1278 request,
1279 plan.projection,
1280 plan.index,
1281 plan.fixed_components,
1282 plan.sort.is_some(),
1283 )?;
1284 if plan.distinct == distinct::Strategy::Complete {
1285 plan.selected |= plan.projection.ok_or(Error::InvalidQuery)?;
1286 }
1287 }
1288 let mut hash = Sha256::new();
1289 hash.update(b"ic-db:query:v1\0");
1290 hash.update(schema);
1291 hash.update(incarnation);
1292 hash.update([u8::from(request.descending)]);
1293 hash.update((plan.prefix.len() as u32).to_le_bytes());
1294 hash.update(&plan.prefix);
1295 for term in &plan.terms {
1296 hash.update([term.position as u8, term.comparison as u8]);
1297 match &term.operand {
1298 TermOperand::Literal { bytes, .. }
1299 | TermOperand::Member {
1300 needle: MemberNeedle::Literal(bytes),
1301 ..
1302 } => {
1303 hash.update((bytes.len() as u32).to_le_bytes());
1304 hash.update(bytes);
1305 }
1306 TermOperand::Length(length) => {
1307 hash.update((u32::MAX - 1).to_le_bytes());
1308 hash.update(length.to_le_bytes());
1309 }
1310 TermOperand::Field(right)
1311 | TermOperand::Member {
1312 needle: MemberNeedle::Field(right),
1313 ..
1314 } => {
1315 hash.update(u32::MAX.to_le_bytes());
1317 hash.update([*right as u8]);
1318 }
1319 }
1320 }
1321 let clauses = plan
1324 .terms
1325 .iter()
1326 .enumerate()
1327 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1328 if clauses != 0 {
1329 hash.update(b"or-clauses\0");
1330 hash.update([clauses]);
1331 }
1332 if let Some(order) = &request.order {
1333 hash.update(b"order\0");
1334 hash.update([order.len() as u8]);
1335 for name in order {
1336 hash.update([entity.field_position(name).ok_or(Error::InvalidQuery)? as u8]);
1338 }
1339 }
1340 if request.order_descending != 0 {
1341 hash.update(b"order-directions\0");
1342 hash.update([request.order_descending]);
1343 }
1344 if let Some(mask) = plan.projection {
1347 hash.update(b"projection\0");
1348 hash.update(mask.to_le_bytes());
1349 }
1350 if request.distinct {
1351 hash.update(b"distinct\0");
1352 }
1353 plan.binding = hash.finalize().into();
1354 if let Some(cursor) = request.cursor {
1355 if cursor.binding != plan.binding {
1356 return Err(Error::InvalidCursor);
1357 }
1358 plan.validate_position(entity, &cursor.position)
1359 .map_err(|_| Error::InvalidCursor)?;
1360 }
1361 Ok(plan)
1362 }
1363
1364 fn validate_position(&self, entity: &EntitySchema, bytes: &[u8]) -> Result<(), Error> {
1365 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
1366 return Err(Error::InvalidCursor);
1367 }
1368 if let Some(index) = self.index {
1369 let mut remaining = bytes.get(9..).ok_or(Error::InvalidCursor)?;
1370 for name in index.fields {
1371 consume_index_component(entity, index, name, &mut remaining)?;
1372 }
1373 if !index.unique {
1374 key::consume(&mut remaining, entity.key_type()?)?;
1375 }
1376 if !remaining.is_empty() {
1377 return Err(Error::InvalidCursor);
1378 }
1379 } else {
1380 RowKey::decode(
1381 bytes.get(5..).ok_or(Error::InvalidCursor)?,
1382 entity.key_type()?,
1383 )?;
1384 }
1385 Ok(())
1386 }
1387
1388 fn cursor(&self, position: &[u8], inclusive: bool) -> QueryCursor {
1389 QueryCursor {
1390 binding: self.binding,
1391 position: position.to_vec(),
1392 inclusive,
1393 }
1394 }
1395}
1396
1397fn consume_index_component(
1399 entity: &EntitySchema,
1400 index: &IndexSchema,
1401 name: &str,
1402 remaining: &mut &[u8],
1403) -> Result<(), Error> {
1404 let field = entity
1405 .fields
1406 .iter()
1407 .find(|f| f.name == name)
1408 .ok_or(Error::InvalidQuery)?;
1409 if field.optional {
1410 let (&presence, rest) = remaining.split_first().ok_or(Error::InvalidCursor)?;
1411 *remaining = rest;
1412 match presence {
1413 0 if !index.present_only => return Ok(()),
1414 1 => {}
1415 _ => return Err(Error::InvalidCursor),
1416 }
1417 }
1418 key::consume(remaining, field.value)
1419}
1420
1421#[inline(never)]
1424#[expect(
1425 clippy::needless_pass_by_value,
1426 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1427)]
1428fn fetch_rows<M: Memory>(
1429 db: &Database<M>,
1430 entity: &EntitySchema,
1431 request: Request<'_>,
1432 projection: Option<&TypeSchema>,
1433) -> Result<QueryPage<Vec<u8>>, Error> {
1434 db.schema.admits(entity)?;
1435 let plan = Plan::admit(
1436 entity,
1437 &request,
1438 db.schema.fingerprint(),
1439 db.incarnation,
1440 projection,
1441 PlanOutput::Rows,
1442 )?;
1443 execute(&db.map, entity, &request, &plan, None)
1444}
1445
1446fn execute<M: Memory>(
1447 map: &Map<M>,
1448 entity: &EntitySchema,
1449 request: &Request<'_>,
1450 plan: &Plan<'_>,
1451 mut aggregate: Option<aggregate::Accumulator<'_>>,
1452) -> Result<QueryPage<Vec<u8>>, Error> {
1453 execute_inner(map, entity, request, plan, aggregate.as_mut(), None)
1454}
1455
1456const STEP_INPUT_BYTES: usize = 64 * 1024;
1459const CANDIDATE_BYTES: usize = crate::codec::MAX_ROW_BYTES + 2 * crate::MAX_INDEX_KEY_BYTES;
1460
1461fn execute_inner<M: Memory>(
1462 map: &Map<M>,
1463 entity: &EntitySchema,
1464 request: &Request<'_>,
1465 plan: &Plan<'_>,
1466 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1467 mut input_bytes: Option<&mut usize>,
1468) -> Result<QueryPage<Vec<u8>>, Error> {
1469 let mut page = QueryPage {
1470 rows: Vec::new(),
1471 next: None,
1472 examined: 0,
1473 fetched: 0,
1474 output_bytes: 0,
1475 };
1476 let Some(bounds) = range::bounds(entity, request, plan)? else {
1477 return Ok(page);
1478 };
1479 let terminal = range::terminal_key(&bounds, plan.descending);
1480 let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
1481 let mut collected = if plan.distinct == distinct::Strategy::Complete {
1482 Some(distinct::Collection::new(
1483 plan.projection.ok_or(Error::InvalidQuery)?,
1484 ))
1485 } else {
1486 None
1487 };
1488 let mut sorted = plan
1489 .sort
1490 .as_ref()
1491 .map(|_| sort::Collection::new(request, plan.distinct));
1492 let mut component = Vec::new();
1493 let mut right_component = Vec::new();
1494 let mut previous = if let Some(cursor) = request.cursor.filter(|c| !c.inclusive) {
1497 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1498 } else {
1499 None
1500 };
1501 let primary_type = entity.fields[plan.primary].value;
1502 while let Some(entry) = if plan.descending {
1503 entries.next_back()
1504 } else {
1505 entries.next()
1506 } {
1507 if request.work == 0 {
1511 return Err(Error::Limit);
1512 }
1513 page.examined += 1;
1514 let stored_key = entry.key();
1515 let mut read_bytes = stored_key.len();
1516 let (owner, bytes) = if plan.index.is_some() {
1517 let owner_bytes = entry.value();
1518 read_bytes += owner_bytes.len();
1519 let owner = RowKey::decode(&owner_bytes, primary_type)?;
1520 let bytes = map.get(&row_key(entity.id, owner)).ok_or(Error::Corrupt)?;
1521 (owner, bytes)
1522 } else {
1523 (
1524 RowKey::decode(&stored_key[5..], primary_type)?,
1525 entry.value(),
1526 )
1527 };
1528 if let Some(used) = input_bytes.as_deref_mut() {
1529 read_bytes += bytes.len();
1530 if read_bytes > CANDIDATE_BYTES {
1531 return Err(Error::Corrupt);
1532 }
1533 *used += read_bytes;
1534 }
1535 page.fetched += 1;
1536 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
1537 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1538 entity.inspect_fields(
1539 &bytes,
1540 plan.selected,
1541 &mut values,
1542 (plan.span_fields != 0
1543 || plan.projection.is_some()
1544 || aggregate.as_ref().is_some_and(|a| a.needs_spans()))
1545 .then_some(&mut spans),
1546 )?;
1547 if RowKey::from_index(values[plan.primary])? != owner {
1548 return Err(Error::Corrupt);
1549 }
1550 if plan.index.is_some() {
1551 validate_index_entry(entity, &entity.row_info(&values)?, owner, stored_key)?;
1552 }
1553 let mut accepts = |term: &Term| -> Result<bool, Error> {
1554 let value = values[term.position];
1555 component.clear();
1556 let (operand, optional) = match &term.operand {
1557 TermOperand::Literal { absent: true, .. }
1558 if plan.span_fields & (1 << term.position) != 0 =>
1559 {
1560 let absent = bytes[usize::from(spans[term.position].0)] == 0;
1561 return Ok(term.comparison.accepts_absent(absent));
1562 }
1563 TermOperand::Member { item, needle } => {
1564 let needle = match needle {
1565 MemberNeedle::Literal(bytes) => bytes.as_slice(),
1566 MemberNeedle::Field(right) => {
1567 let value = values[*right];
1568 if value == IndexValue::Absent {
1569 return Ok(false);
1570 }
1571 right_component.clear();
1572 value.append_component(false, &mut right_component);
1573 &right_component
1574 }
1575 };
1576 let (start, end) = spans[term.position];
1577 return contains_member(
1578 &bytes[usize::from(start)..usize::from(end)],
1579 entity.fields[term.position].optional,
1580 *item,
1581 needle,
1582 &mut component,
1583 );
1584 }
1585 TermOperand::Length(length) => {
1586 let (start, end) = spans[term.position];
1587 let span = &bytes[usize::from(start)..usize::from(end)];
1588 let actual =
1589 crate::codec::validated_length(span, entity.fields[term.position].optional);
1590
1591 return Ok(term.comparison.accepts_length(actual, *length));
1592 }
1593 TermOperand::Literal { bytes, absent } => (
1594 (!absent).then_some(bytes.as_slice()),
1595 entity.fields[term.position].optional,
1596 ),
1597 TermOperand::Field(right) => {
1598 let rhs = values[*right];
1599 right_component.clear();
1600 rhs.append_component(false, &mut right_component);
1601 (
1602 (rhs != IndexValue::Absent).then_some(right_component.as_slice()),
1603 false,
1604 )
1605 }
1606 };
1607 value.append_component(optional, &mut component);
1608 Ok(term.comparison.accepts(
1609 (value != IndexValue::Absent).then_some(component.as_slice()),
1610 operand,
1611 optional,
1612 ))
1613 };
1614 let matches = 'matches: {
1615 'clause: for clause in plan.clauses() {
1616 for term in clause {
1617 if accepts(term)? {
1618 continue 'clause;
1619 }
1620 }
1621 break 'matches false;
1622 }
1623 true
1624 };
1625 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
1626 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
1627 if matches && let Some(accumulator) = aggregate.as_mut() {
1628 accumulator.push(entity, &values, &bytes, &spans)?;
1629 if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
1630 return Ok(page);
1632 }
1633 } else if matches && let Some(collection) = collected.as_mut() {
1634 collection.push(entity, request, &values, &bytes, &spans)?;
1635 } else if matches && let Some(collection) = sorted.as_mut() {
1636 collection.push(entity, plan, &values, &bytes, &spans)?;
1637 } else if matches && !duplicate {
1638 let size = plan
1639 .projection
1640 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
1641 if size > request.bytes {
1642 return Err(Error::RowTooLarge);
1643 }
1644 if size > request.bytes - page.output_bytes {
1645 page.next = Some(plan.cursor(stored_key, true));
1646 return Ok(page);
1647 }
1648 page.output_bytes += size;
1649 if let Some(mask) = plan.projection {
1650 page.rows.push(copy_projection(&bytes, &spans, mask, size));
1651 } else {
1652 page.rows.push(bytes);
1653 }
1654 if let Some(boundary) = boundary {
1655 previous = Some(boundary.to_vec());
1656 }
1657 }
1658 if page.rows.len() == request.rows
1659 || page.examined == request.work
1660 || input_bytes
1661 .as_deref()
1662 .is_some_and(|used| *used > STEP_INPUT_BYTES - CANDIDATE_BYTES)
1663 {
1664 if terminal == Some(stored_key) {
1665 break;
1666 }
1667 if (aggregate.is_some() && input_bytes.is_none())
1668 || collected.is_some()
1669 || sorted.is_some()
1670 {
1671 return Err(Error::Limit);
1674 }
1675 page.next = Some(plan.cursor(stored_key, false));
1676 return Ok(page);
1677 }
1678 }
1679 if let Some(collection) = collected {
1680 page.output_bytes = collection.output_bytes;
1681 page.rows = collection.rows;
1682 }
1683 if let Some(collection) = sorted {
1684 collection.finish(request.bytes, &mut page)?;
1685 }
1686 Ok(page)
1687}