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