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]
532 pub fn distinct(mut self) -> Self {
533 self.request.distinct = true;
534 self
535 }
536
537 #[must_use]
547 pub fn filter(
548 mut self,
549 field: &'a str,
550 comparison: Comparison,
551 value: impl Into<IndexValue<'a>>,
552 ) -> Self {
553 self.request
554 .filter(field, comparison, QueryOperand::Literal(value.into()));
555 self
556 }
557
558 #[must_use]
560 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
561 self.filter(field, Comparison::Eq, value)
562 }
563
564 #[must_use]
566 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
567 self.filter(field, Comparison::Ne, value)
568 }
569
570 #[must_use]
572 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
573 self.filter(field, Comparison::Lt, value)
574 }
575
576 #[must_use]
578 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
579 self.filter(field, Comparison::Le, value)
580 }
581
582 #[must_use]
584 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
585 self.filter(field, Comparison::Gt, value)
586 }
587
588 #[must_use]
590 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
591 self.filter(field, Comparison::Ge, value)
592 }
593
594 #[must_use]
600 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
601 self.request
602 .filter(left, comparison, QueryOperand::Field(right));
603 self
604 }
605
606 #[must_use]
610 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
611 self.request
612 .filter(field, comparison, QueryOperand::Length(length));
613 self
614 }
615
616 #[must_use]
619 pub fn filter_present(self, field: &'a str) -> Self {
620 self.filter(field, Comparison::Ne, IndexValue::Absent)
621 }
622
623 #[must_use]
626 pub fn filter_absent(self, field: &'a str) -> Self {
627 self.filter(field, Comparison::Eq, IndexValue::Absent)
628 }
629
630 #[must_use]
637 pub fn filter_between(
638 self,
639 field: &'a str,
640 lower: impl Into<IndexValue<'a>>,
641 upper: impl Into<IndexValue<'a>>,
642 ) -> Self {
643 self.filter(field, Comparison::Ge, lower)
644 .filter(field, Comparison::Le, upper)
645 }
646
647 #[must_use]
655 pub fn filter_not_between(
656 self,
657 field: &'a str,
658 lower: impl Into<IndexValue<'a>>,
659 upper: impl Into<IndexValue<'a>>,
660 ) -> Self {
661 self.filter_any(&[
662 (field, Comparison::Lt, lower.into()),
663 (field, Comparison::Gt, upper.into()),
664 ])
665 }
666
667 #[must_use]
672 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
673 self.filter_fields(field, Comparison::Ge, lower)
674 .filter_fields(field, Comparison::Le, upper)
675 }
676
677 #[must_use]
682 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
683 self.filter_any_operands(&[
684 (field, Comparison::Lt, QueryOperand::Field(lower)),
685 (field, Comparison::Gt, QueryOperand::Field(upper)),
686 ])
687 }
688
689 #[must_use]
696 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
697 self.request.or_clause(
698 alternatives
699 .iter()
700 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
701 );
702 self
703 }
704
705 #[must_use]
710 pub fn filter_any_operands(
711 mut self,
712 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
713 ) -> Self {
714 self.request.or_clause(alternatives.iter().copied());
715 self
716 }
717
718 #[must_use]
728 pub fn filter_in(
729 mut self,
730 field: &'a str,
731 values: &[impl Copy + Into<IndexValue<'a>>],
732 ) -> Self {
733 self.request.or_clause(
734 values
735 .iter()
736 .copied()
737 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
738 );
739 self
740 }
741
742 #[must_use]
750 pub fn filter_not_in(
751 mut self,
752 field: &'a str,
753 values: &[impl Copy + Into<IndexValue<'a>>],
754 ) -> Self {
755 self.request
756 .filter_not_in(field, values.iter().copied().map(Into::into));
757 self
758 }
759
760 #[must_use]
765 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
766 self.request.using_index(name, values);
767 self
768 }
769
770 #[must_use]
773 pub fn order_asc(mut self, field: &'a str) -> Self {
774 self.request.append_order(field, SortDirection::Ascending);
775 self
776 }
777
778 #[must_use]
781 pub fn order_desc(mut self, field: &'a str) -> Self {
782 self.request.append_order(field, SortDirection::Descending);
783 self
784 }
785
786 #[must_use]
796 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
797 self.request.order_by(fields);
798 self
799 }
800
801 #[must_use]
806 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
807 self.request.order_by_each(fields);
808 self
809 }
810
811 #[must_use]
813 pub fn descending(mut self) -> Self {
814 self.request.descending = true;
815 self
816 }
817
818 #[must_use]
825 pub fn limit(mut self, rows: usize) -> Self {
826 self.request.rows = rows;
827 self
828 }
829
830 #[must_use]
832 pub fn work_limit(mut self, candidates: usize) -> Self {
833 self.request.work = candidates;
834 self
835 }
836
837 #[cfg(feature = "test-support")]
839 #[doc(hidden)]
840 #[must_use]
841 pub fn test_output_limit(mut self, bytes: usize) -> Self {
842 self.request.bytes = bytes;
843 self
844 }
845
846 #[must_use]
848 pub fn after(mut self, cursor: &'a QueryCursor) -> Self {
849 self.request.cursor = Some(cursor);
850 self
851 }
852
853 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
860 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
861 }
862
863 pub fn first(self) -> Result<Option<E>, Error> {
869 let mut page = self.probe_matches(1)?;
870 match page.rows.pop() {
871 None if page.next.is_some() => Err(Error::Limit),
872 result => Ok(result),
873 }
874 }
875
876 pub fn try_one(self) -> Result<Option<E>, Error> {
883 if self.request.cursor.is_some() {
884 return Err(Error::InvalidQuery);
885 }
886 let mut page = self.probe_matches(2)?;
887 if page.rows.len() == 2 {
888 return Err(Error::MultipleMatches);
889 }
890 if page.next.is_some() {
891 return Err(Error::Limit);
892 }
893 Ok(page.rows.pop())
894 }
895
896 fn probe_matches(self, rows: usize) -> Result<QueryPage<E>, Error> {
897 if !(1..=32).contains(&self.request.rows) {
898 return Err(Error::Limit);
899 }
900 self.limit(rows).fetch()
901 }
902
903 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
913 let raw = fetch_rows(
914 &*self.db.read()?,
915 E::SCHEMA,
916 self.request,
917 Some(R::definition()),
918 )?;
919 raw.decode_projection()
920 }
921}
922
923fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u16, Error> {
927 let TypeBody::Record(fields) = &output.body else {
928 return Err(Error::InvalidQuery);
929 };
930 if fields.is_empty()
931 || fields.len() > crate::schema::MAX_FIELDS
932 || fields.windows(2).any(|w| w[0].name >= w[1].name)
933 {
934 return Err(Error::InvalidQuery);
935 }
936 let mut source = TypeGraph::default();
937 let mut target = TypeGraph::default();
938 let mut mask = 0;
939 for field in *fields {
940 let position = entity
941 .field_position(field.name)
942 .ok_or(Error::InvalidQuery)?;
943 let stored = &entity.fields[position];
944 if stored.value != field.value || stored.optional != field.optional {
945 return Err(Error::InvalidQuery);
946 }
947 source
948 .include(stored.value)
949 .map_err(|_| Error::InvalidQuery)?;
950 target
951 .include(field.value)
952 .map_err(|_| Error::InvalidQuery)?;
953 mask |= 1 << position;
954 }
955 if !source.contains(&target) {
956 return Err(Error::InvalidQuery);
957 }
958 Ok(mask)
959}
960
961struct Term {
962 position: usize,
963 comparison: Comparison,
964 operand: TermOperand,
965 or_next: bool,
966}
967
968enum TermOperand {
969 Literal {
970 bytes: Vec<u8>,
971 absent: bool,
972 },
973 Member {
974 item: FieldType,
975 needle: MemberNeedle,
976 },
977 Field(usize),
978 Length(u32),
979}
980
981enum MemberNeedle {
982 Literal(Vec<u8>),
983 Field(usize),
984}
985
986fn member_type(field: FieldType) -> Option<FieldType> {
987 match key::operand_type(field) {
988 FieldType::List { item, .. } => Some(*item),
989 FieldType::Named(link) => match (link.definition)().body {
990 TypeBody::Set { item, .. } => Some(item),
991 _ => None,
992 },
993 _ => None,
994 }
995}
996
997fn contains_member(
999 span: &[u8],
1000 optional: bool,
1001 item: FieldType,
1002 needle: &[u8],
1003 scratch: &mut Vec<u8>,
1004) -> Result<bool, Error> {
1005 let mut reader = Decoder::new(span)?;
1006 if optional && !reader.boolean()? {
1007 return Ok(false);
1008 }
1009 for _ in 0..reader.nat32()? {
1010 scratch.clear();
1011 IndexValue::read(&mut reader, item)?.append_component(false, scratch);
1012 if scratch.as_slice() == needle {
1013 return Ok(true);
1014 }
1015 }
1016 Ok(false)
1017}
1018
1019fn admit_ordered_fields(entity: &EntitySchema, mask: u16) -> Result<(), Error> {
1020 for (i, field) in entity.fields.iter().enumerate() {
1021 if mask & (1 << i) != 0 && !key::supports(field.value) {
1022 return Err(Error::InvalidQuery);
1023 }
1024 }
1025 Ok(())
1026}
1027
1028fn comparison_key(
1030 entity: &EntitySchema,
1031 mask: u16,
1032 values: &[IndexValue<'_>],
1033) -> Result<Vec<u8>, Error> {
1034 let mut key = Vec::new();
1035 for (i, field) in entity.fields.iter().enumerate() {
1036 if mask & (1 << i) != 0 {
1037 values[i].append_component(field.optional, &mut key);
1038 if key.len() > MAX_COMPARISON_KEY {
1039 return Err(Error::Limit);
1040 }
1041 }
1042 }
1043 Ok(key)
1044}
1045
1046fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1047 if size > limit {
1048 return Err(Error::RowTooLarge);
1049 }
1050 if size > limit - *used {
1051 return Err(Error::Limit);
1052 }
1053 *used += size;
1054 Ok(())
1055}
1056
1057fn projection_size(spans: &[(u16, u16)], mask: u16) -> usize {
1059 spans
1060 .iter()
1061 .enumerate()
1062 .filter(|(i, _)| mask & (1 << i) != 0)
1063 .map(|(_, (start, end))| usize::from(end - start))
1064 .sum()
1065}
1066
1067fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u16, size: usize) -> Vec<u8> {
1068 let mut output = Vec::with_capacity(size);
1069 for (i, &(start, end)) in spans.iter().enumerate() {
1070 if mask & (1 << i) != 0 {
1071 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1072 }
1073 }
1074 output
1075}
1076#[derive(Clone, Copy)]
1077enum PlanOutput {
1078 Rows,
1079 Aggregate { grouped: bool },
1080}
1081
1082struct Plan<'a> {
1083 primary: usize,
1084 index: Option<&'a IndexSchema>,
1085 prefix: Vec<u8>,
1086 fixed_components: usize,
1087 terms: Vec<Term>,
1088 selected: u16,
1089 span_fields: u16,
1091 binding: [u8; 32],
1092 projection: Option<u16>,
1093 distinct: distinct::Strategy,
1094 sort: Option<Vec<(usize, bool)>>,
1095 descending: bool,
1096}
1097impl<'a> Plan<'a> {
1098 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1099 self.terms.split_inclusive(|term| !term.or_next)
1100 }
1101
1102 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1103 self.index = Some(path.index);
1104 self.prefix = path.prefix;
1105 self.fixed_components = path.fixed;
1106 self.selected |= entity.key_fields();
1107 }
1108
1109 fn admit(
1110 entity: &'a EntitySchema,
1111 request: &Request<'_>,
1112 schema: [u8; 32],
1113 incarnation: [u8; 16],
1114 projection: Option<&TypeSchema>,
1115 output: PlanOutput,
1116 ) -> Result<Self, Error> {
1117 if request.over_limit
1118 || !(1..=32).contains(&request.rows)
1119 || !(1..=MAX_WORK).contains(&request.work)
1120 || !(1..=MAX_OUTPUT).contains(&request.bytes)
1121 {
1122 return Err(Error::Limit);
1123 }
1124 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1125 {
1126 return Err(Error::InvalidQuery);
1127 }
1128 for value in request
1130 .predicates
1131 .iter()
1132 .filter_map(|p| match &p.operand {
1133 QueryOperand::Literal(value) => Some(value),
1134 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1135 })
1136 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1137 {
1138 if match value {
1139 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1140 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1141 _ => false,
1142 } {
1143 return Err(Error::Limit);
1144 }
1145 }
1146 let primary = entity
1147 .field_position(entity.primary_key)
1148 .filter(|&i| !entity.fields[i].optional)
1149 .ok_or(Error::InvalidQuery)?;
1150 let mut plan = Self {
1151 primary,
1152 index: None,
1153 prefix: prefix(2, entity.id),
1154 fixed_components: 0,
1155 terms: Vec::new(),
1156 selected: 1 << primary,
1157 span_fields: 0,
1158 binding: [0; 32],
1159 projection: projection
1160 .map(|output| admit_projection(entity, output))
1161 .transpose()?,
1162 distinct: distinct::Strategy::Identity,
1163 sort: None,
1164 descending: request.descending ^ request.primary_descending(entity),
1165 };
1166 for predicate in &request.predicates {
1167 let position = entity
1168 .field_position(predicate.field)
1169 .ok_or(Error::InvalidQuery)?;
1170 let field = &entity.fields[position];
1171 let member = if predicate.comparison == Comparison::Contains {
1172 member_type(field.value)
1173 } else {
1174 None
1175 };
1176 let operand = match predicate.operand {
1177 QueryOperand::Length(length) => {
1178 let supported = match key::operand_type(field.value) {
1179 FieldType::Text { .. }
1180 | FieldType::Blob { .. }
1181 | FieldType::List { .. } => true,
1182 FieldType::Named(link) => matches!(
1183 (link.definition)().body,
1184 TypeBody::Map { .. } | TypeBody::Set { .. }
1185 ),
1186 _ => false,
1187 };
1188 if !supported || !predicate.comparison.is_relational() {
1189 return Err(Error::InvalidQuery);
1190 }
1191 plan.span_fields |= 1 << position;
1192 TermOperand::Length(length)
1193 }
1194 QueryOperand::Field(name) => {
1195 let right = entity.field_position(name).ok_or(Error::InvalidQuery)?;
1196 let right_type = entity.fields[right].value;
1197 let left_type = member.unwrap_or(field.value);
1198 let compatible = left_type == right_type
1199 || matches!(
1200 (left_type, right_type),
1201 (FieldType::Text { .. }, FieldType::Text { .. })
1202 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1203 );
1204 if !compatible
1205 || !key::supports(left_type)
1206 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1207 {
1208 return Err(Error::InvalidQuery);
1209 }
1210 plan.selected |= 1 << right;
1211 if let Some(item) = member {
1212 plan.span_fields |= 1 << position;
1213 TermOperand::Member {
1214 item,
1215 needle: MemberNeedle::Field(right),
1216 }
1217 } else {
1218 plan.selected |= 1 << position;
1219 TermOperand::Field(right)
1220 }
1221 }
1222 QueryOperand::Literal(value) => {
1223 if let Some(item) = member {
1224 if !key::supports(item) {
1225 return Err(Error::InvalidQuery);
1226 }
1227 value.admit(item, false)?;
1228 let mut bytes = Vec::new();
1229 value.append_component(false, &mut bytes);
1230 plan.span_fields |= 1 << position;
1231 TermOperand::Member {
1232 item,
1233 needle: MemberNeedle::Literal(bytes),
1234 }
1235 } else {
1236 let absent = value == IndexValue::Absent;
1237 if key::supports(field.value) {
1238 plan.selected |= 1 << position;
1239 } else if absent
1240 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1241 {
1242 plan.span_fields |= 1 << position;
1243 } else {
1244 return Err(Error::InvalidQuery);
1245 }
1246 predicate
1247 .comparison
1248 .admit(field.value, field.optional, value)?;
1249 let mut bytes = Vec::new();
1250 value.append_component(field.optional, &mut bytes);
1251 TermOperand::Literal { bytes, absent }
1252 }
1253 }
1254 };
1255 plan.terms.push(Term {
1256 position,
1257 comparison: predicate.comparison,
1258 operand,
1259 or_next: predicate.or_next,
1260 });
1261 }
1262 match order::select(entity, request, output)? {
1265 order::Path::Primary => {}
1266 order::Path::Index(path) => plan.use_index(entity, path),
1267 order::Path::Sort(fields) => {
1268 for &(position, _) in &fields {
1269 plan.selected |= 1 << position;
1270 }
1271 plan.sort = Some(fields);
1272 }
1273 }
1274 if request.distinct {
1275 plan.distinct = distinct::admit(
1276 entity,
1277 request,
1278 plan.projection,
1279 plan.index,
1280 plan.fixed_components,
1281 plan.sort.is_some(),
1282 )?;
1283 if plan.distinct == distinct::Strategy::Complete {
1284 plan.selected |= plan.projection.ok_or(Error::InvalidQuery)?;
1285 }
1286 }
1287 let mut hash = Sha256::new();
1288 hash.update(b"ic-db:query:v1\0");
1289 hash.update(schema);
1290 hash.update(incarnation);
1291 hash.update([u8::from(request.descending)]);
1292 hash.update((plan.prefix.len() as u32).to_le_bytes());
1293 hash.update(&plan.prefix);
1294 for term in &plan.terms {
1295 hash.update([term.position as u8, term.comparison as u8]);
1296 match &term.operand {
1297 TermOperand::Literal { bytes, .. }
1298 | TermOperand::Member {
1299 needle: MemberNeedle::Literal(bytes),
1300 ..
1301 } => {
1302 hash.update((bytes.len() as u32).to_le_bytes());
1303 hash.update(bytes);
1304 }
1305 TermOperand::Length(length) => {
1306 hash.update((u32::MAX - 1).to_le_bytes());
1307 hash.update(length.to_le_bytes());
1308 }
1309 TermOperand::Field(right)
1310 | TermOperand::Member {
1311 needle: MemberNeedle::Field(right),
1312 ..
1313 } => {
1314 hash.update(u32::MAX.to_le_bytes());
1316 hash.update([*right as u8]);
1317 }
1318 }
1319 }
1320 let clauses = plan
1323 .terms
1324 .iter()
1325 .enumerate()
1326 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1327 if clauses != 0 {
1328 hash.update(b"or-clauses\0");
1329 hash.update([clauses]);
1330 }
1331 if let Some(order) = &request.order {
1332 hash.update(b"order\0");
1333 hash.update([order.len() as u8]);
1334 for name in order {
1335 hash.update([entity.field_position(name).ok_or(Error::InvalidQuery)? as u8]);
1337 }
1338 }
1339 if request.order_descending != 0 {
1340 hash.update(b"order-directions\0");
1341 hash.update([request.order_descending]);
1342 }
1343 if let Some(mask) = plan.projection {
1346 hash.update(b"projection\0");
1347 hash.update(mask.to_le_bytes());
1348 }
1349 if request.distinct {
1350 hash.update(b"distinct\0");
1351 }
1352 plan.binding = hash.finalize().into();
1353 if let Some(cursor) = request.cursor {
1354 if cursor.binding != plan.binding {
1355 return Err(Error::InvalidCursor);
1356 }
1357 plan.validate_position(entity, &cursor.position)
1358 .map_err(|_| Error::InvalidCursor)?;
1359 }
1360 Ok(plan)
1361 }
1362
1363 fn validate_position(&self, entity: &EntitySchema, bytes: &[u8]) -> Result<(), Error> {
1364 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
1365 return Err(Error::InvalidCursor);
1366 }
1367 if let Some(index) = self.index {
1368 let mut remaining = bytes.get(9..).ok_or(Error::InvalidCursor)?;
1369 for name in index.fields {
1370 consume_index_component(entity, index, name, &mut remaining)?;
1371 }
1372 if !index.unique {
1373 key::consume(&mut remaining, entity.key_type()?)?;
1374 }
1375 if !remaining.is_empty() {
1376 return Err(Error::InvalidCursor);
1377 }
1378 } else {
1379 RowKey::decode(
1380 bytes.get(5..).ok_or(Error::InvalidCursor)?,
1381 entity.key_type()?,
1382 )?;
1383 }
1384 Ok(())
1385 }
1386
1387 fn cursor(&self, position: &[u8], inclusive: bool) -> QueryCursor {
1388 QueryCursor {
1389 binding: self.binding,
1390 position: position.to_vec(),
1391 inclusive,
1392 }
1393 }
1394}
1395
1396fn consume_index_component(
1398 entity: &EntitySchema,
1399 index: &IndexSchema,
1400 name: &str,
1401 remaining: &mut &[u8],
1402) -> Result<(), Error> {
1403 let field = entity
1404 .fields
1405 .iter()
1406 .find(|f| f.name == name)
1407 .ok_or(Error::InvalidQuery)?;
1408 if field.optional {
1409 let (&presence, rest) = remaining.split_first().ok_or(Error::InvalidCursor)?;
1410 *remaining = rest;
1411 match presence {
1412 0 if !index.present_only => return Ok(()),
1413 1 => {}
1414 _ => return Err(Error::InvalidCursor),
1415 }
1416 }
1417 key::consume(remaining, field.value)
1418}
1419
1420#[inline(never)]
1423#[expect(
1424 clippy::needless_pass_by_value,
1425 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1426)]
1427fn fetch_rows<M: Memory>(
1428 db: &Database<M>,
1429 entity: &EntitySchema,
1430 request: Request<'_>,
1431 projection: Option<&TypeSchema>,
1432) -> Result<QueryPage<Vec<u8>>, Error> {
1433 db.schema.admits(entity)?;
1434 let plan = Plan::admit(
1435 entity,
1436 &request,
1437 db.schema.fingerprint(),
1438 db.incarnation,
1439 projection,
1440 PlanOutput::Rows,
1441 )?;
1442 execute(&db.map, entity, &request, &plan, None)
1443}
1444
1445fn execute<M: Memory>(
1446 map: &Map<M>,
1447 entity: &EntitySchema,
1448 request: &Request<'_>,
1449 plan: &Plan<'_>,
1450 mut aggregate: Option<aggregate::Accumulator<'_>>,
1451) -> Result<QueryPage<Vec<u8>>, Error> {
1452 execute_inner(map, entity, request, plan, aggregate.as_mut(), None)
1453}
1454
1455const STEP_INPUT_BYTES: usize = 64 * 1024;
1458const CANDIDATE_BYTES: usize = crate::codec::MAX_ROW_BYTES + 2 * crate::MAX_INDEX_KEY_BYTES;
1459
1460fn execute_inner<M: Memory>(
1461 map: &Map<M>,
1462 entity: &EntitySchema,
1463 request: &Request<'_>,
1464 plan: &Plan<'_>,
1465 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1466 mut input_bytes: Option<&mut usize>,
1467) -> Result<QueryPage<Vec<u8>>, Error> {
1468 let mut page = QueryPage {
1469 rows: Vec::new(),
1470 next: None,
1471 examined: 0,
1472 fetched: 0,
1473 output_bytes: 0,
1474 };
1475 let Some(bounds) = range::bounds(entity, request, plan)? else {
1476 return Ok(page);
1477 };
1478 let terminal = range::terminal_key(&bounds, plan.descending);
1479 let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
1480 let mut collected = if plan.distinct == distinct::Strategy::Complete {
1481 Some(distinct::Collection::new(
1482 plan.projection.ok_or(Error::InvalidQuery)?,
1483 ))
1484 } else {
1485 None
1486 };
1487 let mut sorted = plan
1488 .sort
1489 .as_ref()
1490 .map(|_| sort::Collection::new(request, plan.distinct));
1491 let mut component = Vec::new();
1492 let mut right_component = Vec::new();
1493 let mut previous = if let Some(cursor) = request.cursor.filter(|c| !c.inclusive) {
1496 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1497 } else {
1498 None
1499 };
1500 let primary_type = entity.fields[plan.primary].value;
1501 while let Some(entry) = if plan.descending {
1502 entries.next_back()
1503 } else {
1504 entries.next()
1505 } {
1506 if request.work == 0 {
1510 return Err(Error::Limit);
1511 }
1512 page.examined += 1;
1513 let stored_key = entry.key();
1514 let mut read_bytes = stored_key.len();
1515 let (owner, bytes) = if plan.index.is_some() {
1516 let owner_bytes = entry.value();
1517 read_bytes += owner_bytes.len();
1518 let owner = RowKey::decode(&owner_bytes, primary_type)?;
1519 let bytes = map.get(&row_key(entity.id, owner)).ok_or(Error::Corrupt)?;
1520 (owner, bytes)
1521 } else {
1522 (
1523 RowKey::decode(&stored_key[5..], primary_type)?,
1524 entry.value(),
1525 )
1526 };
1527 if let Some(used) = input_bytes.as_deref_mut() {
1528 read_bytes += bytes.len();
1529 if read_bytes > CANDIDATE_BYTES {
1530 return Err(Error::Corrupt);
1531 }
1532 *used += read_bytes;
1533 }
1534 page.fetched += 1;
1535 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
1536 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1537 entity.inspect_fields(
1538 &bytes,
1539 plan.selected,
1540 &mut values,
1541 (plan.span_fields != 0
1542 || plan.projection.is_some()
1543 || aggregate.as_ref().is_some_and(|a| a.needs_spans()))
1544 .then_some(&mut spans),
1545 )?;
1546 if RowKey::from_index(values[plan.primary])? != owner {
1547 return Err(Error::Corrupt);
1548 }
1549 if plan.index.is_some() {
1550 validate_index_entry(entity, &entity.row_info(&values)?, owner, stored_key)?;
1551 }
1552 let mut accepts = |term: &Term| -> Result<bool, Error> {
1553 let value = values[term.position];
1554 component.clear();
1555 let (operand, optional) = match &term.operand {
1556 TermOperand::Literal { absent: true, .. }
1557 if plan.span_fields & (1 << term.position) != 0 =>
1558 {
1559 let absent = bytes[usize::from(spans[term.position].0)] == 0;
1560 return Ok(term.comparison.accepts_absent(absent));
1561 }
1562 TermOperand::Member { item, needle } => {
1563 let needle = match needle {
1564 MemberNeedle::Literal(bytes) => bytes.as_slice(),
1565 MemberNeedle::Field(right) => {
1566 let value = values[*right];
1567 if value == IndexValue::Absent {
1568 return Ok(false);
1569 }
1570 right_component.clear();
1571 value.append_component(false, &mut right_component);
1572 &right_component
1573 }
1574 };
1575 let (start, end) = spans[term.position];
1576 return contains_member(
1577 &bytes[usize::from(start)..usize::from(end)],
1578 entity.fields[term.position].optional,
1579 *item,
1580 needle,
1581 &mut component,
1582 );
1583 }
1584 TermOperand::Length(length) => {
1585 let (start, end) = spans[term.position];
1586 let span = &bytes[usize::from(start)..usize::from(end)];
1587 let actual =
1588 crate::codec::validated_length(span, entity.fields[term.position].optional);
1589
1590 return Ok(term.comparison.accepts_length(actual, *length));
1591 }
1592 TermOperand::Literal { bytes, absent } => (
1593 (!absent).then_some(bytes.as_slice()),
1594 entity.fields[term.position].optional,
1595 ),
1596 TermOperand::Field(right) => {
1597 let rhs = values[*right];
1598 right_component.clear();
1599 rhs.append_component(false, &mut right_component);
1600 (
1601 (rhs != IndexValue::Absent).then_some(right_component.as_slice()),
1602 false,
1603 )
1604 }
1605 };
1606 value.append_component(optional, &mut component);
1607 Ok(term.comparison.accepts(
1608 (value != IndexValue::Absent).then_some(component.as_slice()),
1609 operand,
1610 optional,
1611 ))
1612 };
1613 let matches = 'matches: {
1614 'clause: for clause in plan.clauses() {
1615 for term in clause {
1616 if accepts(term)? {
1617 continue 'clause;
1618 }
1619 }
1620 break 'matches false;
1621 }
1622 true
1623 };
1624 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
1625 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
1626 if matches && let Some(accumulator) = aggregate.as_mut() {
1627 accumulator.push(entity, &values, &bytes, &spans)?;
1628 if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
1629 return Ok(page);
1631 }
1632 } else if matches && let Some(collection) = collected.as_mut() {
1633 collection.push(entity, request, &values, &bytes, &spans)?;
1634 } else if matches && let Some(collection) = sorted.as_mut() {
1635 collection.push(entity, plan, &values, &bytes, &spans)?;
1636 } else if matches && !duplicate {
1637 let size = plan
1638 .projection
1639 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
1640 if size > request.bytes {
1641 return Err(Error::RowTooLarge);
1642 }
1643 if size > request.bytes - page.output_bytes {
1644 page.next = Some(plan.cursor(stored_key, true));
1645 return Ok(page);
1646 }
1647 page.output_bytes += size;
1648 if let Some(mask) = plan.projection {
1649 page.rows.push(copy_projection(&bytes, &spans, mask, size));
1650 } else {
1651 page.rows.push(bytes);
1652 }
1653 if let Some(boundary) = boundary {
1654 previous = Some(boundary.to_vec());
1655 }
1656 }
1657 if page.rows.len() == request.rows
1658 || page.examined == request.work
1659 || input_bytes
1660 .as_deref()
1661 .is_some_and(|used| *used > STEP_INPUT_BYTES - CANDIDATE_BYTES)
1662 {
1663 if terminal == Some(stored_key) {
1664 break;
1665 }
1666 if (aggregate.is_some() && input_bytes.is_none())
1667 || collected.is_some()
1668 || sorted.is_some()
1669 {
1670 return Err(Error::Limit);
1673 }
1674 page.next = Some(plan.cursor(stored_key, false));
1675 return Ok(page);
1676 }
1677 }
1678 if let Some(collection) = collected {
1679 page.output_bytes = collection.output_bytes;
1680 page.rows = collection.rows;
1681 }
1682 if let Some(collection) = sorted {
1683 collection.finish(request.bytes, &mut page)?;
1684 }
1685 Ok(page)
1686}