1mod aggregate;
4mod distinct;
5mod order;
6mod probe;
7mod range;
8mod sort;
9
10pub use aggregate::{
11 Aggregate, GroupCount, GroupOrder, GroupSummaries, GroupSummary, GroupSummaryPage, GroupValue,
12 SummaryMeasure,
13 jobs::{AggregateJobs, GroupCursor, GroupPage, JobHandle, JobOutcome, JobStep},
14};
15
16use super::{
17 Database, ENTITY_PREFIX_BYTES, INDEX_PREFIX_BYTES, Map, prefix, row_key, validate_index_entry,
18};
19use crate::{
20 Entity, EntitySchema, Error, FieldType, IndexSchema, IndexValue, TypeBody, TypeSchema, Value,
21 codec::Decoder, key, primary::RowKey, types::TypeGraph,
22};
23use ic_storage::Memory;
24use sha2::{Digest, Sha256};
25use std::{
26 cell::{Ref, RefCell},
27 marker::PhantomData,
28 ops::Deref,
29 rc::Rc,
30};
31
32const MAX_TERMS: usize = 8;
33const MAX_WORK: usize = 512;
34const MAX_OUTPUT: usize = 128 * 1024;
35const MAX_COMPARISON_KEY: usize = 4096;
36const MAX_DISTINCT_VALUES: usize = 32;
37const MAX_STATE_BYTES: usize = 128 * 1024;
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum SortDirection {
42 Ascending,
44 Descending,
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50#[repr(u8)]
51pub enum Comparison {
52 Eq = 0,
54 Ne = 1,
56 Lt = 2,
58 Le = 3,
60 Gt = 4,
62 Ge = 5,
64 StartsWith = 6,
68 EndsWith = 7,
71 Contains = 8,
75}
76
77impl Comparison {
78 fn supports_record_member(self) -> bool {
79 self.is_relational() || matches!(self, Self::StartsWith | Self::EndsWith)
80 }
81
82 fn is_relational(self) -> bool {
83 matches!(
84 self,
85 Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge
86 )
87 }
88
89 fn supports_scalar(self, field: FieldType) -> bool {
90 self.is_relational()
91 || matches!(
92 key::operand_type(field),
93 FieldType::Text { .. } | FieldType::Blob { .. }
94 )
95 }
96
97 fn admit(self, field: FieldType, optional: bool, value: IndexValue<'_>) -> Result<(), Error> {
98 value.admit(field, optional)?;
99 if !self.supports_scalar(field) {
100 return Err(Error::InvalidQuery);
101 }
102 if value == IndexValue::Absent && !matches!(self, Self::Eq | Self::Ne) {
103 return Err(Error::InvalidOperand);
104 }
105
106 Ok(())
107 }
108
109 fn accepts(self, actual: Option<&[u8]>, operand: Option<&[u8]>, optional: bool) -> bool {
110 if actual.is_none() {
111 return self.accepts_absent(operand.is_none());
112 }
113
114 match self {
115 Self::Eq => actual == operand,
116 Self::Ne => actual != operand,
117 Self::StartsWith | Self::EndsWith | Self::Contains => {
118 fn content(key: &[u8], optional: bool) -> Option<&[u8]> {
121 crate::key::bytes_prefix(key.get(usize::from(optional)..)?)
122 }
123
124 actual
125 .and_then(|key| content(key, optional))
126 .zip(operand.and_then(|key| content(key, optional)))
127 .is_some_and(|(actual, operand)| match self {
128 Self::StartsWith => actual.starts_with(operand),
131 Self::EndsWith => actual
135 .strip_suffix(operand)
136 .is_some_and(|prefix| prefix.last() != Some(&0)),
137 _ => contains_component(actual, operand),
138 })
139 }
140 _ if actual.is_none() || operand.is_none() => false,
141 Self::Lt => actual < operand,
142 Self::Le => actual <= operand,
143 Self::Gt => actual > operand,
144 Self::Ge => actual >= operand,
145 }
146 }
147
148 fn accepts_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
150 match self {
151 Self::Eq => Some(equal_values(left, right)),
152 Self::Ne => Some(!equal_values(left, right)),
153 _ => Some(self.accepts_bytes(scalar_bytes(left)?, scalar_bytes(right)?)),
154 }
155 }
156
157 fn accepts_bytes(self, actual: &[u8], operand: &[u8]) -> bool {
159 match self {
160 Self::StartsWith => actual.starts_with(operand),
161 Self::EndsWith => actual.ends_with(operand),
162 Self::Contains => memchr::memmem::find(actual, operand).is_some(),
163 _ => self.accepts(Some(actual), Some(operand), false),
164 }
165 }
166
167 fn accepts_length(self, actual: Option<u32>, threshold: u32) -> bool {
168 let encoded = actual.map(u32::to_be_bytes);
169
170 self.accepts(
171 encoded.as_ref().map(|v| v.as_slice()),
172 Some(&threshold.to_be_bytes()),
173 false,
174 )
175 }
176
177 fn empty_length_value(self, threshold: u32, field: FieldType) -> Option<IndexValue<'static>> {
179 if !matches!((self, threshold), (Self::Eq | Self::Le, 0) | (Self::Lt, 1)) {
180 return None;
181 }
182 match key::operand_type(field) {
183 FieldType::Text { .. } => Some(IndexValue::Text("")),
184 FieldType::Blob { .. } => Some(IndexValue::Blob(&[])),
185 _ => None,
186 }
187 }
188
189 fn uniform_length_result(self, min: u32, max: u32, n: u32) -> Option<bool> {
191 match self {
192 Self::Eq | Self::Ne if min == max || n < min || n > max => {
193 Some(self.accepts_length(Some(min), n))
194 }
195 Self::Lt | Self::Ge if max < n || min >= n => Some(self.accepts_length(Some(min), n)),
196 Self::Le | Self::Gt if max <= n || min > n => Some(self.accepts_length(Some(min), n)),
197 _ => None,
198 }
199 }
200
201 fn accepts_absent(self, other_absent: bool) -> bool {
204 match self {
205 Self::Eq => other_absent,
206 Self::Ne => !other_absent,
207 _ => false,
208 }
209 }
210}
211
212fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
214 let Some(start) = memchr::memmem::find(actual, needle) else {
215 return false;
216 };
217 if start == 0 || actual[start - 1] != 0 {
218 return true;
219 }
220 fn raw(content: &[u8]) -> Vec<u8> {
224 let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
225 let mut encoded = content.iter();
226 while let Some(&byte) = encoded.next() {
227 bytes.push(byte);
228 if byte == 0 {
229 encoded.next();
230 }
231 }
232
233 bytes
234 }
235
236 memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
237}
238
239#[derive(Clone, Debug, PartialEq, Eq)]
243pub struct QueryCursor {
244 binding: [u8; 32],
245 position: Vec<u8>,
246 resume: Resume,
247}
248
249#[derive(Clone, Copy, Debug, PartialEq, Eq)]
250enum Resume {
251 After = 0,
252 Retry = 1,
253 AfterUnemittedClass = 2,
254}
255impl QueryCursor {
256 pub(super) const MAX_ENCODED_BYTES: usize = 34 + crate::MAX_INDEX_KEY_BYTES;
257
258 #[must_use]
260 pub fn to_bytes(&self) -> Vec<u8> {
261 let mut bytes = vec![1, self.resume as u8];
262 bytes.extend(self.binding);
263 bytes.extend(&self.position);
264
265 bytes
266 }
267
268 pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
272 if !(35..=Self::MAX_ENCODED_BYTES).contains(&bytes.len()) || bytes[0] != 1 {
273 return Err(Error::InvalidCursor);
274 }
275
276 Ok(Self {
277 binding: bytes[2..34].try_into().map_err(|_| Error::InvalidCursor)?,
278 position: bytes[34..].to_vec(),
279 resume: match bytes[1] {
280 0 => Resume::After,
281 1 => Resume::Retry,
282 2 => Resume::AfterUnemittedClass,
283 _ => return Err(Error::InvalidCursor),
284 },
285 })
286 }
287}
288
289impl serde::Serialize for QueryCursor {
290 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
291 self.to_bytes().serialize(serializer)
292 }
293}
294
295impl<'de> serde::Deserialize<'de> for QueryCursor {
296 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
297 struct Frame;
298
299 impl<'de> serde::de::Visitor<'de> for Frame {
300 type Value = QueryCursor;
301
302 fn expecting(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
303 fmt.write_str("a bounded IC DB query cursor frame")
304 }
305
306 fn visit_seq<A: serde::de::SeqAccess<'de>>(
307 self,
308 mut seq: A,
309 ) -> Result<QueryCursor, A::Error> {
310 let size = seq.size_hint().unwrap_or(0);
311 if size > QueryCursor::MAX_ENCODED_BYTES {
312 return Err(serde::de::Error::custom(Error::InvalidCursor));
313 }
314 let mut frame = Vec::with_capacity(size);
315 while let Some(byte) = seq.next_element()? {
316 if frame.len() == QueryCursor::MAX_ENCODED_BYTES {
317 return Err(serde::de::Error::custom(Error::InvalidCursor));
318 }
319 frame.push(byte);
320 }
321 QueryCursor::from_bytes(&frame).map_err(serde::de::Error::custom)
322 }
323 }
324
325 deserializer.deserialize_seq(Frame)
326 }
327}
328
329#[derive(Debug)]
332pub struct QueryPage<T> {
333 pub rows: Vec<T>,
335 pub next: Option<QueryCursor>,
337 pub examined: usize,
339 pub fetched: usize,
341 pub output_bytes: usize,
343}
344
345impl QueryPage<Vec<u8>> {
346 #[inline(never)]
347 pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
348 Ok(QueryPage {
349 rows: self
350 .rows
351 .iter()
352 .map(|bytes| E::decode(bytes))
353 .collect::<Result<_, _>>()?,
354 next: self.next,
355 examined: self.examined,
356 fetched: self.fetched,
357 output_bytes: self.output_bytes,
358 })
359 }
360
361 #[inline(never)]
362 fn decode_projection<R: Value>(self) -> Result<QueryPage<R>, Error> {
363 Ok(QueryPage {
364 rows: self
365 .rows
366 .iter()
367 .map(|bytes| {
368 let mut reader = Decoder::new(bytes)?;
369 let row = R::decode_from(&mut reader)?;
371 reader.finish()?;
372
373 Ok(row)
374 })
375 .collect::<Result<_, Error>>()?,
376 next: self.next,
377 examined: self.examined,
378 fetched: self.fetched,
379 output_bytes: self.output_bytes,
380 })
381 }
382}
383
384#[derive(Clone, Copy, Debug, PartialEq, Eq)]
386pub enum QueryOperand<'a> {
387 Literal(IndexValue<'a>),
389 Length(u32),
391 Field(&'a str),
393}
394
395struct Predicate<'a> {
396 field: &'a str,
397 comparison: Comparison,
398 operand: QueryOperand<'a>,
399 or_next: bool,
401}
402
403impl<'a> Predicate<'a> {
404 fn fixed_equality(&self, entity: &EntitySchema) -> Option<(&'a str, IndexValue<'a>)> {
406 if let QueryOperand::Length(n) = self.operand {
407 let empty = self
408 .comparison
409 .empty_length_value(n, entity.index_field(self.field)?.value)?;
410 return Some((self.field, empty));
411 }
412 let QueryOperand::Literal(value) = self.operand else {
413 return None;
414 };
415 let fixed = match (self.comparison, value) {
417 (Comparison::Eq, _) => value,
418 (Comparison::Ne, IndexValue::Bool(excluded))
419 if entity.field_is_required(self.field) =>
420 {
421 IndexValue::Bool(!excluded)
422 }
423 (Comparison::Le, _) if scalar_bytes(value).is_some_and(<[u8]>::is_empty) => value,
424 (Comparison::Gt, IndexValue::Bool(false))
425 | (Comparison::Ge, IndexValue::Bool(true)) => IndexValue::Bool(true),
426 (Comparison::Lt, IndexValue::Bool(true))
427 | (Comparison::Le, IndexValue::Bool(false)) => IndexValue::Bool(false),
428 _ => return None,
429 };
430 Some((self.field, fixed))
431 }
432
433 fn tests_presence(&self, entity: &EntitySchema, operand: &TermOperand) -> bool {
435 match (self.comparison, self.operand) {
436 (Comparison::Ne, QueryOperand::Literal(IndexValue::Absent))
437 | (Comparison::Ge, QueryOperand::Literal(IndexValue::Bool(false)))
438 | (Comparison::Le, QueryOperand::Literal(IndexValue::Bool(true))) => true,
439 (_, QueryOperand::Length(_)) => {
440 self.present_length_result(entity) == Some(true)
441 && self.comparison != Comparison::Ne
442 }
443 (
444 Comparison::Le
445 | Comparison::Ge
446 | Comparison::StartsWith
447 | Comparison::EndsWith
448 | Comparison::Contains,
449 QueryOperand::Field(right),
450 ) => right == self.field,
451 (
452 Comparison::Ge
453 | Comparison::StartsWith
454 | Comparison::EndsWith
455 | Comparison::Contains,
456 QueryOperand::Literal(needle),
457 ) => {
458 !matches!(operand, TermOperand::Member { .. })
460 && scalar_bytes(needle).is_some_and(<[u8]>::is_empty)
461 }
462 _ => false,
463 }
464 }
465
466 fn present_length_result(&self, entity: &EntitySchema) -> Option<bool> {
468 let QueryOperand::Length(n) = self.operand else {
469 return None;
470 };
471 let max = length_limit(entity.index_field(self.field)?.value)?;
472 self.comparison.uniform_length_result(0, max, n)
473 }
474
475 fn constant_comparison(&self, entity: &EntitySchema) -> Option<bool> {
476 if let QueryOperand::Literal(value) = self.operand {
477 return match (self.comparison, value) {
479 (Comparison::Lt, IndexValue::Bool(false))
480 | (Comparison::Gt, IndexValue::Bool(true)) => Some(false),
481 (Comparison::Lt, _) if scalar_bytes(value).is_some_and(<[u8]>::is_empty) => {
482 Some(false)
483 }
484 _ => None,
485 };
486 }
487 if matches!(self.operand, QueryOperand::Length(_)) {
488 let result = self.present_length_result(entity)?;
489 return (result == self.comparison.accepts_absent(false)
490 || entity.field_is_required(self.field))
491 .then_some(result);
492 }
493 if !matches!(self.operand, QueryOperand::Field(right) if right == self.field) {
494 return None;
495 }
496 match self.comparison {
497 Comparison::Eq => Some(true),
498 Comparison::Ne | Comparison::Lt | Comparison::Gt => Some(false),
499 _ => None,
500 }
501 }
502}
503
504struct Request<'a> {
505 groups: aggregate::GroupRequest<'a>,
506 predicates: Vec<Predicate<'a>>,
507 index: Option<(&'a str, Vec<IndexValue<'a>>)>,
508 order: Option<Vec<&'a str>>,
509 order_descending: u8,
510 descending: bool,
511 distinct: bool,
512 single_result_probe: bool,
513 rows: usize,
514 work: usize,
515 bytes: usize,
516 cursor: Option<&'a QueryCursor>,
517 over_limit: bool,
518}
519
520impl Default for Request<'_> {
521 fn default() -> Self {
522 Self {
523 groups: aggregate::GroupRequest::default(),
524 predicates: Vec::new(),
525 index: None,
526 order: None,
527 order_descending: 0,
528 descending: false,
529 distinct: false,
530 single_result_probe: false,
531 rows: 32,
532 work: 128,
533 bytes: MAX_OUTPUT,
534 cursor: None,
535 over_limit: false,
536 }
537 }
538}
539
540impl<'a> Request<'a> {
543 fn fixed_equalities<'r>(
545 &'r self,
546 entity: &'r EntitySchema,
547 ) -> impl Iterator<Item = (&'a str, IndexValue<'a>)> + 'r {
548 self.clauses().filter_map(move |clause| {
549 let (predicate, rest) = clause.split_first()?;
550 let equality = predicate.fixed_equality(entity)?;
551 rest.iter()
552 .all(|other| other.fixed_equality(entity) == Some(equality))
553 .then_some(equality)
554 })
555 }
556
557 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
558 self.predicates.split_inclusive(|p| !p.or_next)
559 }
560
561 #[inline(never)]
562 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
563 if self.predicates.len() == MAX_TERMS {
564 self.over_limit = true;
565 } else {
566 self.predicates.push(Predicate {
567 field,
568 comparison,
569 operand,
570 or_next: false,
571 });
572 }
573 }
574
575 #[inline(never)]
576 fn or_clause(
577 &mut self,
578 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
579 ) {
580 let count = alternatives.len();
581
582 if count == 0 || count > MAX_TERMS - self.predicates.len() {
583 self.over_limit = true;
584 } else {
585 self.predicates.extend(alternatives.enumerate().map(
586 |(i, (field, comparison, operand))| Predicate {
587 field,
588 comparison,
589 operand,
590 or_next: i + 1 < count,
591 },
592 ));
593 }
594 }
595
596 #[inline(never)]
597 fn filter_not_in(
598 &mut self,
599 field: &'a str,
600 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
601 ) {
602 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
603 self.over_limit = true;
604
605 return;
606 }
607 for value in values {
608 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
609 }
610 }
611
612 #[inline(never)]
613 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
614 if values.len() > 4 {
615 self.over_limit = true;
616 } else {
617 self.index = Some((name, values.to_vec()));
618 }
619 }
620
621 #[inline(never)]
622 fn order_by(&mut self, fields: &[&'a str]) {
623 self.order_descending = 0;
624
625 if fields.len() > 4 {
626 self.over_limit = true;
627 } else {
628 self.order = Some(fields.to_vec());
629 }
630 }
631
632 #[inline(never)]
633 fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
634 if fields.len() > 4 {
635 self.over_limit = true;
636
637 return;
638 }
639 self.order = Some(Vec::with_capacity(fields.len()));
640 self.order_descending = 0;
641 for &(field, direction) in fields {
642 self.append_order(field, direction);
643 }
644 }
645
646 fn append_order(&mut self, field: &'a str, direction: SortDirection) {
647 let fields = self.order.get_or_insert_with(Vec::new);
648 if fields.len() == 4 {
649 self.over_limit = true;
650
651 return;
652 }
653 if direction == SortDirection::Descending {
654 self.order_descending |= 1 << fields.len();
655 }
656 fields.push(field);
657 }
658
659 fn primary_descending(&self, entity: &EntitySchema) -> bool {
660 self.order_descending != 0
661 && self.order.as_ref().is_some_and(|fields| {
662 fields.last() == Some(&entity.primary_key)
663 && self.order_descending & (1 << (fields.len() - 1)) != 0
664 })
665 }
666}
667
668pub(super) fn source_page<M: Memory>(
670 map: &Map<M>,
671 entity: &EntitySchema,
672 binding: [u8; 32],
673 incarnation: [u8; 16],
674 cursor: Option<&QueryCursor>,
675 rows: usize,
676 bytes: usize,
677) -> Result<QueryPage<Vec<u8>>, Error> {
678 let request = Request {
679 rows,
680 work: rows,
681 bytes,
682 cursor,
683 ..Request::default()
684 };
685 let plan = Plan::admit(
686 entity,
687 &request,
688 binding,
689 incarnation,
690 None,
691 PlanOutput::Rows,
692 )?;
693
694 execute(map, entity, &request, &plan, None)
695}
696
697enum QuerySource<'a, M: Memory> {
698 Direct(&'a Database<M>),
699 Session(Rc<RefCell<Database<M>>>),
700}
701
702enum QueryRead<'a, M: Memory> {
703 Direct(&'a Database<M>),
704 Session(Ref<'a, Database<M>>),
705}
706
707impl<M: Memory> Deref for QueryRead<'_, M> {
708 type Target = Database<M>;
709
710 fn deref(&self) -> &Self::Target {
711 match self {
712 Self::Direct(db) => db,
713 Self::Session(db) => db,
714 }
715 }
716}
717
718impl<M: Memory> QuerySource<'_, M> {
719 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
720 match self {
721 Self::Direct(db) => Ok(QueryRead::Direct(db)),
722 Self::Session(db) => db
723 .try_borrow()
724 .map(QueryRead::Session)
725 .map_err(|_| Error::BorrowConflict),
726 }
727 }
728}
729
730pub struct Query<'a, E, M: Memory> {
734 db: QuerySource<'a, M>,
735 request: Request<'a>,
736 entity: PhantomData<E>,
737}
738impl<M: Memory> Database<M> {
739 #[must_use]
741 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
742 Query {
743 db: QuerySource::Direct(self),
744 entity: PhantomData,
745 request: Request::default(),
746 }
747 }
748}
749impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
750 pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
751 Self {
752 db: QuerySource::Session(db),
753 request: Request::default(),
754 entity: PhantomData,
755 }
756 }
757
758 #[must_use]
772 pub fn distinct(mut self) -> Self {
773 self.request.distinct = true;
774
775 self
776 }
777
778 #[must_use]
791 pub fn filter(
792 mut self,
793 field: &'a str,
794 comparison: Comparison,
795 value: impl Into<IndexValue<'a>>,
796 ) -> Self {
797 self.request
798 .filter(field, comparison, QueryOperand::Literal(value.into()));
799
800 self
801 }
802
803 #[must_use]
805 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
806 self.filter(field, Comparison::Eq, value)
807 }
808
809 #[must_use]
811 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
812 self.filter(field, Comparison::Ne, value)
813 }
814
815 #[must_use]
817 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
818 self.filter(field, Comparison::Lt, value)
819 }
820
821 #[must_use]
823 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
824 self.filter(field, Comparison::Le, value)
825 }
826
827 #[must_use]
829 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
830 self.filter(field, Comparison::Gt, value)
831 }
832
833 #[must_use]
835 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
836 self.filter(field, Comparison::Ge, value)
837 }
838
839 #[must_use]
847 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
848 self.request
849 .filter(left, comparison, QueryOperand::Field(right));
850
851 self
852 }
853
854 #[must_use]
859 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
860 self.request
861 .filter(field, comparison, QueryOperand::Length(length));
862
863 self
864 }
865
866 #[must_use]
869 pub fn filter_present(self, field: &'a str) -> Self {
870 self.filter(field, Comparison::Ne, IndexValue::Absent)
871 }
872
873 #[must_use]
876 pub fn filter_absent(self, field: &'a str) -> Self {
877 self.filter(field, Comparison::Eq, IndexValue::Absent)
878 }
879
880 #[must_use]
887 pub fn filter_between(
888 self,
889 field: &'a str,
890 lower: impl Into<IndexValue<'a>>,
891 upper: impl Into<IndexValue<'a>>,
892 ) -> Self {
893 self.filter(field, Comparison::Ge, lower)
894 .filter(field, Comparison::Le, upper)
895 }
896
897 #[must_use]
905 pub fn filter_not_between(
906 self,
907 field: &'a str,
908 lower: impl Into<IndexValue<'a>>,
909 upper: impl Into<IndexValue<'a>>,
910 ) -> Self {
911 self.filter_any(&[
912 (field, Comparison::Lt, lower.into()),
913 (field, Comparison::Gt, upper.into()),
914 ])
915 }
916
917 #[must_use]
922 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
923 self.filter_fields(field, Comparison::Ge, lower)
924 .filter_fields(field, Comparison::Le, upper)
925 }
926
927 #[must_use]
932 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
933 self.filter_any_operands(&[
934 (field, Comparison::Lt, QueryOperand::Field(lower)),
935 (field, Comparison::Gt, QueryOperand::Field(upper)),
936 ])
937 }
938
939 #[must_use]
947 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
948 self.request.or_clause(
949 alternatives
950 .iter()
951 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
952 );
953
954 self
955 }
956
957 #[must_use]
962 pub fn filter_any_operands(
963 mut self,
964 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
965 ) -> Self {
966 self.request.or_clause(alternatives.iter().copied());
967
968 self
969 }
970
971 #[must_use]
981 pub fn filter_in(
982 mut self,
983 field: &'a str,
984 values: &[impl Copy + Into<IndexValue<'a>>],
985 ) -> Self {
986 self.request.or_clause(
987 values
988 .iter()
989 .copied()
990 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
991 );
992
993 self
994 }
995
996 #[must_use]
1004 pub fn filter_not_in(
1005 mut self,
1006 field: &'a str,
1007 values: &[impl Copy + Into<IndexValue<'a>>],
1008 ) -> Self {
1009 self.request
1010 .filter_not_in(field, values.iter().copied().map(Into::into));
1011
1012 self
1013 }
1014
1015 #[must_use]
1020 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
1021 self.request.using_index(name, values);
1022
1023 self
1024 }
1025
1026 #[must_use]
1029 pub fn order_asc(mut self, field: &'a str) -> Self {
1030 self.request.append_order(field, SortDirection::Ascending);
1031
1032 self
1033 }
1034
1035 #[must_use]
1038 pub fn order_desc(mut self, field: &'a str) -> Self {
1039 self.request.append_order(field, SortDirection::Descending);
1040
1041 self
1042 }
1043
1044 #[must_use]
1055 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
1056 self.request.order_by(fields);
1057
1058 self
1059 }
1060
1061 #[must_use]
1066 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
1067 self.request.order_by_each(fields);
1068
1069 self
1070 }
1071
1072 #[must_use]
1074 pub fn descending(mut self) -> Self {
1075 self.request.descending = true;
1076
1077 self
1078 }
1079
1080 #[must_use]
1087 pub fn limit(mut self, rows: usize) -> Self {
1088 self.request.rows = rows;
1089
1090 self
1091 }
1092
1093 #[must_use]
1095 pub fn work_limit(mut self, candidates: usize) -> Self {
1096 self.request.work = candidates;
1097
1098 self
1099 }
1100
1101 #[cfg(feature = "test-support")]
1103 #[doc(hidden)]
1104 #[must_use]
1105 pub fn test_output_limit(mut self, bytes: usize) -> Self {
1106 self.request.bytes = bytes;
1107
1108 self
1109 }
1110
1111 #[must_use]
1113 pub fn after(mut self, cursor: &'a QueryCursor) -> Self {
1114 self.request.cursor = Some(cursor);
1115
1116 self
1117 }
1118
1119 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
1126 observe!(query, { self.entity_page() })
1127 }
1128
1129 fn entity_page(self) -> Result<QueryPage<E>, Error> {
1130 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
1131 }
1132
1133 pub fn first(self) -> Result<Option<E>, Error> {
1139 self.first_with(Self::entity_page)
1140 }
1141
1142 pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
1146 self.first_with(Self::projected_page::<R>)
1147 }
1148
1149 fn first_with<R>(
1150 self,
1151 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1152 ) -> Result<Option<R>, Error> {
1153 observe!(query, {
1154 let page = fetch(self.probe_matches(1)?)?;
1155 if page.rows.is_empty() && page.next.is_some() {
1156 return Err(Error::Limit);
1157 }
1158 Ok(page)
1159 })
1160 .map(|mut page| page.rows.pop())
1161 }
1162
1163 pub fn try_one(self) -> Result<Option<E>, Error> {
1170 self.try_one_with(Self::entity_page)
1171 }
1172
1173 pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
1179 self.try_one_with(Self::projected_page::<R>)
1180 }
1181
1182 fn try_one_with<R>(
1183 self,
1184 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1185 ) -> Result<Option<R>, Error> {
1186 observe!(query, {
1187 if self.request.cursor.is_some() {
1188 return Err(Error::InvalidQuery);
1189 }
1190 let page = fetch(self.probe_matches(2)?)?;
1191 if page.rows.len() == 2 {
1192 return Err(Error::MultipleMatches);
1193 }
1194 if page.next.is_some() {
1195 return Err(Error::Limit);
1196 }
1197
1198 Ok(page)
1199 })
1200 .map(|mut page| page.rows.pop())
1201 }
1202
1203 fn probe_matches(mut self, rows: usize) -> Result<Self, Error> {
1204 if !(1..=32).contains(&self.request.rows) {
1205 return Err(Error::Limit);
1206 }
1207
1208 self.request.single_result_probe = true;
1209
1210 Ok(self.limit(rows))
1211 }
1212
1213 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1223 observe!(query, { self.projected_page() })
1224 }
1225
1226 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1227 let raw = fetch_rows(
1228 &*self.db.read()?,
1229 E::SCHEMA,
1230 self.request,
1231 Some(R::definition()),
1232 )?;
1233
1234 raw.decode_projection()
1235 }
1236}
1237
1238fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u16, Error> {
1242 let TypeBody::Record(fields) = &output.body else {
1243 return Err(Error::InvalidQuery);
1244 };
1245 if fields.is_empty()
1246 || fields.len() > crate::schema::MAX_FIELDS
1247 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1248 {
1249 return Err(Error::InvalidQuery);
1250 }
1251 let mut source = TypeGraph::default();
1252 let mut target = TypeGraph::default();
1253 let mut mask = 0;
1254 for field in *fields {
1255 let position = entity
1256 .field_position(field.name)
1257 .ok_or(Error::InvalidQuery)?;
1258 let stored = &entity.fields[position];
1259 if stored.value != field.value || stored.optional != field.optional {
1260 return Err(Error::InvalidQuery);
1261 }
1262 source
1263 .include(stored.value)
1264 .map_err(|_| Error::InvalidQuery)?;
1265 target
1266 .include(field.value)
1267 .map_err(|_| Error::InvalidQuery)?;
1268 mask |= 1 << position;
1269 }
1270 if !source.contains(&target) {
1271 return Err(Error::InvalidQuery);
1272 }
1273
1274 Ok(mask)
1275}
1276
1277struct Term {
1278 tests_presence: bool,
1279 position: usize,
1280 comparison: Comparison,
1281 operand: TermOperand,
1282 or_next: bool,
1283}
1284
1285enum TermOperand {
1286 Literal {
1287 bytes: Vec<u8>,
1288 absent: bool,
1289 },
1290 Member {
1291 item: FieldType,
1292 needle: MemberNeedle,
1293 },
1294 Nested {
1295 member: crate::member::RecordMember,
1296 literal: Vec<u8>,
1297 absent: bool,
1298 },
1299 Field {
1300 right: usize,
1301 left_member: Option<crate::member::RecordMember>,
1302 right_member: Option<crate::member::RecordMember>,
1303 },
1304 Length {
1305 member: Option<crate::member::RecordMember>,
1306 threshold: u32,
1307 },
1308}
1309
1310enum MemberNeedle {
1311 Literal(Vec<u8>),
1312 Field(usize, Option<crate::member::RecordMember>),
1313}
1314
1315fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1318 match value {
1319 IndexValue::Text(text) => Some(text.as_bytes()),
1320 IndexValue::Blob(bytes) => Some(bytes),
1321 _ => None,
1322 }
1323}
1324
1325fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1326 match (left, right) {
1328 (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1329 a == b
1330 }
1331 _ => left == right,
1332 }
1333}
1334
1335fn length_limit(field: FieldType) -> Option<u32> {
1336 match key::operand_type(field) {
1337 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1338 FieldType::List { max_items, .. } => Some(max_items),
1339 FieldType::Named(link) => match (link.definition)().body {
1340 TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1341 _ => None,
1342 },
1343 _ => None,
1344 }
1345}
1346
1347fn member_type(field: FieldType) -> Option<FieldType> {
1348 match key::operand_type(field) {
1349 FieldType::List { item, .. } => Some(*item),
1350 FieldType::Named(link) => match (link.definition)().body {
1351 TypeBody::Set { item, .. } => Some(item),
1352 _ => None,
1353 },
1354 _ => None,
1355 }
1356}
1357
1358fn contains_member(
1360 span: &[u8],
1361 optional: bool,
1362 item: FieldType,
1363 needle: IndexValue<'_>,
1364) -> Result<bool, Error> {
1365 let mut reader = Decoder::new(span)?;
1366 if optional && !reader.boolean()? {
1367 return Ok(false);
1368 }
1369 for _ in 0..reader.nat32()? {
1370 let value = IndexValue::read(&mut reader, item)?;
1371 if equal_values(value, needle) {
1372 return Ok(true);
1373 }
1374 }
1375
1376 Ok(false)
1377}
1378
1379fn projection_positions(mut mask: u16) -> impl Iterator<Item = usize> {
1382 std::iter::from_fn(move || {
1383 if mask == 0 {
1384 return None;
1385 }
1386 let position = mask.trailing_zeros() as usize;
1387 mask &= mask - 1;
1388 Some(position)
1389 })
1390}
1391
1392fn admit_ordered_fields(entity: &EntitySchema, mask: u16) -> Result<(), Error> {
1393 for i in projection_positions(mask) {
1394 if !key::supports(entity.fields[i].value) {
1395 return Err(Error::InvalidQuery);
1396 }
1397 }
1398
1399 Ok(())
1400}
1401
1402fn comparison_key(
1404 entity: &EntitySchema,
1405 mask: u16,
1406 values: &[IndexValue<'_>],
1407 scratch: &mut Vec<u8>,
1408) -> Result<(), Error> {
1409 build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1410}
1411
1412fn build_comparison_key<'a>(
1413 entity: &EntitySchema,
1414 mask: u16,
1415 key: &mut Vec<u8>,
1416 mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1417) -> Result<(), Error> {
1418 key.clear();
1419 for i in projection_positions(mask) {
1420 let field = &entity.fields[i];
1421 value(i, field)?.append_component(field.optional, key);
1422 if key.len() > MAX_COMPARISON_KEY {
1423 return Err(Error::Limit);
1424 }
1425 }
1426
1427 Ok(())
1428}
1429
1430fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1431 if size > limit {
1432 return Err(Error::RowTooLarge);
1433 }
1434 if size > limit - *used {
1435 return Err(Error::Limit);
1436 }
1437 *used += size;
1438
1439 Ok(())
1440}
1441
1442fn projection_size(spans: &[(u16, u16)], mask: u16) -> usize {
1444 projection_positions(mask)
1445 .map(|i| {
1446 let (start, end) = spans[i];
1447 usize::from(end - start)
1448 })
1449 .sum()
1450}
1451
1452fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u16, size: usize) -> Vec<u8> {
1453 let mut output = Vec::with_capacity(size);
1454 for i in projection_positions(mask) {
1455 let (start, end) = spans[i];
1456 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1457 }
1458
1459 output
1460}
1461#[derive(Clone, Copy)]
1462enum PlanOutput {
1463 Rows,
1464 Aggregate { grouped: bool },
1465}
1466
1467struct Plan<'a> {
1468 primary: usize,
1469 index: Option<&'a IndexSchema>,
1470 prefix: Vec<u8>,
1471 fixed_components: usize,
1472 terms: Vec<Term>,
1473 selected: u16,
1474 span_fields: u16,
1476 binding: [u8; 32],
1477 projection: Option<u16>,
1478 distinct: distinct::Strategy,
1479 sort: Option<Vec<order::SortField>>,
1480 descending: bool,
1481}
1482impl<'a> Plan<'a> {
1483 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1484 self.terms.split_inclusive(|term| !term.or_next)
1485 }
1486
1487 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1488 self.index = Some(path.index);
1489 self.prefix = path.prefix;
1490 self.fixed_components = path.fixed;
1491 self.selected |= entity.key_fields();
1492 }
1493
1494 fn admit(
1495 entity: &'a EntitySchema,
1496 request: &Request<'_>,
1497 schema: [u8; 32],
1498 incarnation: [u8; 16],
1499 projection: Option<&TypeSchema>,
1500 output: PlanOutput,
1501 ) -> Result<Self, Error> {
1502 if request.over_limit
1503 || !(1..=32).contains(&request.rows)
1504 || !(1..=MAX_WORK).contains(&request.work)
1505 || !(1..=MAX_OUTPUT).contains(&request.bytes)
1506 {
1507 return Err(Error::Limit);
1508 }
1509 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1510 {
1511 return Err(Error::InvalidQuery);
1512 }
1513 for value in request
1515 .predicates
1516 .iter()
1517 .filter_map(|p| match &p.operand {
1518 QueryOperand::Literal(value) => Some(value),
1519 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1520 })
1521 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1522 {
1523 if match value {
1524 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1525 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1526 _ => false,
1527 } {
1528 return Err(Error::Limit);
1529 }
1530 }
1531 let primary = entity
1532 .field_position(entity.primary_key)
1533 .filter(|&i| !entity.fields[i].optional)
1534 .ok_or(Error::InvalidQuery)?;
1535 let mut plan = Self {
1536 primary,
1537 index: None,
1538 prefix: prefix(2, entity.id),
1539 fixed_components: 0,
1540 terms: Vec::new(),
1541 selected: 1 << primary,
1542 span_fields: 0,
1543 binding: [0; 32],
1544 projection: projection
1545 .map(|output| admit_projection(entity, output))
1546 .transpose()?,
1547 distinct: distinct::Strategy::Identity,
1548 sort: None,
1549 descending: request.descending ^ request.primary_descending(entity),
1550 };
1551 for predicate in &request.predicates {
1552 let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
1553 let field = &entity.fields[position];
1554 let member = if predicate.comparison == Comparison::Contains {
1555 member_type(field.value)
1556 } else {
1557 None
1558 };
1559 let operand = match (predicate.operand, record_member) {
1560 (QueryOperand::Literal(value), Some(member)) => {
1561 if !predicate.comparison.supports_record_member() {
1562 return Err(Error::InvalidQuery);
1563 }
1564 let leaf = member.field();
1565 predicate.comparison.admit(
1566 leaf.value,
1567 field.optional || leaf.optional,
1568 value,
1569 )?;
1570 let mut literal = Vec::new();
1571 value.append_component(false, &mut literal);
1572 plan.span_fields |= 1 << position;
1573 TermOperand::Nested {
1574 member,
1575 literal,
1576 absent: value == IndexValue::Absent,
1577 }
1578 }
1579 (QueryOperand::Length(length), member) => {
1580 let selected = member.map_or(field.value, |m| m.field().value);
1581 if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1582 return Err(Error::InvalidQuery);
1583 }
1584 plan.span_fields |= 1 << position;
1585
1586 TermOperand::Length {
1587 member,
1588 threshold: length,
1589 }
1590 }
1591 (QueryOperand::Field(name), left_member) => {
1592 let (right, right_member) = crate::member::resolve_field(entity, name)?;
1593 if (left_member.is_some() || right_member.is_some())
1594 && member.is_none()
1595 && !predicate.comparison.supports_record_member()
1596 {
1597 return Err(Error::InvalidQuery);
1598 }
1599 let right_type =
1600 right_member.map_or(entity.fields[right].value, |m| m.field().value);
1601 let left_type =
1602 left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1603 let compatible = left_type == right_type
1604 || matches!(
1605 (left_type, right_type),
1606 (FieldType::Text { .. }, FieldType::Text { .. })
1607 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1608 );
1609 if !compatible
1610 || !key::supports(left_type)
1611 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1612 {
1613 return Err(Error::InvalidQuery);
1614 }
1615 if right_member.is_some() {
1616 plan.span_fields |= 1 << right;
1617 } else {
1618 plan.selected |= 1 << right;
1619 }
1620
1621 if let Some(item) = member {
1622 plan.span_fields |= 1 << position;
1623
1624 TermOperand::Member {
1625 item,
1626 needle: MemberNeedle::Field(right, right_member),
1627 }
1628 } else {
1629 if left_member.is_some() {
1630 plan.span_fields |= 1 << position;
1631 } else {
1632 plan.selected |= 1 << position;
1633 }
1634 TermOperand::Field {
1635 right,
1636 left_member,
1637 right_member,
1638 }
1639 }
1640 }
1641 (QueryOperand::Literal(value), None) => {
1642 if let Some(item) = member {
1643 if !key::supports(item) {
1644 return Err(Error::InvalidQuery);
1645 }
1646 value.admit(item, false)?;
1647 let mut bytes = Vec::new();
1648 value.append_component(false, &mut bytes);
1649 plan.span_fields |= 1 << position;
1650
1651 TermOperand::Member {
1652 item,
1653 needle: MemberNeedle::Literal(bytes),
1654 }
1655 } else {
1656 let absent = value == IndexValue::Absent;
1657 if key::supports(field.value) {
1658 plan.selected |= 1 << position;
1659 } else if absent
1660 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1661 {
1662 plan.span_fields |= 1 << position;
1663 } else {
1664 return Err(Error::InvalidQuery);
1665 }
1666 predicate
1667 .comparison
1668 .admit(field.value, field.optional, value)?;
1669 let mut bytes = Vec::new();
1670 value.append_component(field.optional, &mut bytes);
1671
1672 TermOperand::Literal { bytes, absent }
1673 }
1674 }
1675 };
1676 plan.terms.push(Term {
1677 tests_presence: predicate.tests_presence(entity, &operand),
1678 position,
1679 comparison: predicate.comparison,
1680 operand,
1681 or_next: predicate.or_next,
1682 });
1683 }
1684 match order::select(entity, request, output)? {
1687 order::Path::Primary => {}
1688 order::Path::Index(path) => plan.use_index(entity, path),
1689 order::Path::Sort(fields) => {
1690 order::select_filtered_path(entity, request, &mut plan, None)?;
1691 for field in &fields {
1692 if field.member.is_some() {
1693 plan.span_fields |= 1 << field.position;
1694 } else {
1695 plan.selected |= 1 << field.position;
1696 }
1697 }
1698 plan.sort = Some(fields);
1699 }
1700 }
1701 if request.distinct {
1702 plan.distinct = distinct::admit(entity, request, &plan)?;
1703 if let distinct::Strategy::Complete { key_fields } = plan.distinct {
1704 plan.selected |= key_fields;
1705 }
1706 }
1707 let mut hash = Sha256::new();
1708 hash.update(b"ic-db:query:v1\0");
1709 hash.update(schema);
1710 hash.update(incarnation);
1711 hash.update([u8::from(request.descending)]);
1712 hash.update((plan.prefix.len() as u32).to_le_bytes());
1713 hash.update(&plan.prefix);
1714 for term in &plan.terms {
1715 hash.update([term.position as u8, term.comparison as u8]);
1716
1717 match &term.operand {
1718 TermOperand::Nested {
1719 member,
1720 literal,
1721 absent,
1722 } => {
1723 hash.update((u32::MAX - 2).to_le_bytes());
1724 hash.update([member.position() as u8, u8::from(*absent)]);
1725 hash.update((literal.len() as u32).to_le_bytes());
1726 hash.update(literal);
1727 }
1728 TermOperand::Literal { bytes, .. }
1729 | TermOperand::Member {
1730 needle: MemberNeedle::Literal(bytes),
1731 ..
1732 } => {
1733 hash.update((bytes.len() as u32).to_le_bytes());
1734 hash.update(bytes);
1735 }
1736 TermOperand::Length { member, threshold } => {
1737 if let Some(member) = member {
1738 hash.update((u32::MAX - 3).to_le_bytes());
1739 hash.update([member.position() as u8]);
1740 } else {
1741 hash.update((u32::MAX - 1).to_le_bytes());
1742 }
1743 hash.update(threshold.to_le_bytes());
1744 }
1745 TermOperand::Field {
1746 right,
1747 left_member: None,
1748 right_member: None,
1749 }
1750 | TermOperand::Member {
1751 needle: MemberNeedle::Field(right, None),
1752 ..
1753 } => {
1754 hash.update(u32::MAX.to_le_bytes());
1756 hash.update([*right as u8]);
1757 }
1758 TermOperand::Member {
1759 needle: MemberNeedle::Field(right, Some(member)),
1760 ..
1761 } => {
1762 hash.update((u32::MAX - 4).to_le_bytes());
1763 hash.update([u8::MAX, *right as u8, member.position() as u8]);
1764 }
1765 TermOperand::Field {
1766 right,
1767 left_member,
1768 right_member,
1769 } => {
1770 hash.update((u32::MAX - 4).to_le_bytes());
1771 let slot = |member: &Option<crate::member::RecordMember>| {
1772 member.map_or(u8::MAX, |m| m.position() as u8)
1773 };
1774 hash.update([slot(left_member), *right as u8, slot(right_member)]);
1775 }
1776 }
1777 }
1778 let clauses = plan
1781 .terms
1782 .iter()
1783 .enumerate()
1784 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1785 if clauses != 0 {
1786 hash.update(b"or-clauses\0");
1787 hash.update([clauses]);
1788 }
1789 if let Some(order) = &request.order {
1790 hash.update(b"order\0");
1791 hash.update([order.len() as u8]);
1792 for name in order {
1793 if let Some(position) = entity.field_position(name) {
1795 hash.update([position as u8]);
1796 } else {
1797 hash.update([u8::MAX, name.len() as u8]);
1799 hash.update(name.as_bytes());
1800 }
1801 }
1802 }
1803 if request.order_descending != 0 {
1804 hash.update(b"order-directions\0");
1805 hash.update([request.order_descending]);
1806 }
1807 if let Some(mask) = plan.projection {
1810 hash.update(b"projection\0");
1811 hash.update(mask.to_le_bytes());
1812 }
1813 if request.distinct {
1814 hash.update(b"distinct\0");
1815 }
1816 plan.binding = hash.finalize().into();
1817 if let Some(cursor) = request.cursor {
1818 if cursor.binding != plan.binding {
1819 return Err(Error::InvalidCursor);
1820 }
1821 plan.validate_position(entity, cursor)
1822 .map_err(|_| Error::InvalidCursor)?;
1823 }
1824
1825 Ok(plan)
1826 }
1827
1828 fn validate_position(&self, entity: &EntitySchema, cursor: &QueryCursor) -> Result<(), Error> {
1829 if cursor.resume == Resume::AfterUnemittedClass
1830 && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
1831 {
1832 return Err(Error::InvalidCursor);
1833 }
1834 let bytes = cursor.position.as_slice();
1835 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
1836 return Err(Error::InvalidCursor);
1837 }
1838 if let Some(index) = self.index {
1839 let mut remaining = bytes
1840 .get(INDEX_PREFIX_BYTES..)
1841 .ok_or(Error::InvalidCursor)?;
1842 for name in index.fields {
1843 consume_index_component(entity, index, name, &mut remaining)?;
1844 }
1845 if !index.unique {
1846 key::consume(&mut remaining, entity.key_type()?)?;
1847 }
1848 if !remaining.is_empty() {
1849 return Err(Error::InvalidCursor);
1850 }
1851 } else {
1852 RowKey::decode(
1853 bytes
1854 .get(ENTITY_PREFIX_BYTES..)
1855 .ok_or(Error::InvalidCursor)?,
1856 entity.key_type()?,
1857 )?;
1858 }
1859
1860 Ok(())
1861 }
1862
1863 fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
1864 QueryCursor {
1865 binding: self.binding,
1866 position: position.to_vec(),
1867 resume,
1868 }
1869 }
1870}
1871
1872fn consume_index_component(
1874 entity: &EntitySchema,
1875 index: &IndexSchema,
1876 name: &str,
1877 remaining: &mut &[u8],
1878) -> Result<(), Error> {
1879 let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
1880
1881 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
1882}
1883
1884#[inline(never)]
1887#[expect(
1888 clippy::needless_pass_by_value,
1889 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1890)]
1891fn fetch_rows<M: Memory>(
1892 db: &Database<M>,
1893 entity: &EntitySchema,
1894 request: Request<'_>,
1895 projection: Option<&TypeSchema>,
1896) -> Result<QueryPage<Vec<u8>>, Error> {
1897 db.schema.admits(entity)?;
1898 let plan = Plan::admit(
1899 entity,
1900 &request,
1901 db.schema.fingerprint(),
1902 db.incarnation,
1903 projection,
1904 PlanOutput::Rows,
1905 )?;
1906
1907 execute(&db.map, entity, &request, &plan, None)
1908}
1909
1910fn execute<M: Memory>(
1911 map: &Map<M>,
1912 entity: &EntitySchema,
1913 request: &Request<'_>,
1914 plan: &Plan<'_>,
1915 mut aggregate: Option<aggregate::Accumulator<'_>>,
1916) -> Result<QueryPage<Vec<u8>>, Error> {
1917 execute_inner(
1918 map,
1919 entity,
1920 request,
1921 plan,
1922 range::bounds(entity, request, plan)?,
1923 aggregate.as_mut(),
1924 None,
1925 )
1926}
1927
1928const STEP_INPUT_BYTES: usize = 64 * 1024;
1931const CANDIDATE_BYTES: usize = crate::codec::MAX_ROW_BYTES + 2 * crate::MAX_INDEX_KEY_BYTES;
1932
1933fn execute_inner<M: Memory>(
1934 map: &Map<M>,
1935 entity: &EntitySchema,
1936 request: &Request<'_>,
1937 plan: &Plan<'_>,
1938 bounds: Option<range::Bounds>,
1939 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1940 mut input_bytes: Option<&mut usize>,
1941) -> Result<QueryPage<Vec<u8>>, Error> {
1942 let mut page = QueryPage {
1943 rows: Vec::new(),
1944 next: None,
1945 examined: 0,
1946 fetched: 0,
1947 output_bytes: 0,
1948 };
1949 let Some(bounds) = bounds else {
1950 return Ok(page);
1951 };
1952 let terminal = range::terminal_key(&bounds, plan.descending);
1953 let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
1954 let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
1955 Some(distinct::Collection::new(
1956 plan.projection.ok_or(Error::InvalidQuery)?,
1957 key_fields,
1958 ))
1959 } else {
1960 None
1961 };
1962 let mut sorted = plan
1963 .sort
1964 .as_ref()
1965 .map(|_| sort::Collection::new(request, plan.distinct));
1966 let mut component = Vec::new();
1967 let mut right_component = Vec::new();
1968 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
1970 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1971 } else {
1972 None
1973 };
1974 let primary_type = entity.fields[plan.primary].value;
1975 let needs_spans = plan.index.is_some()
1976 || plan.span_fields != 0
1977 || match &aggregate {
1978 Some(accumulator) => accumulator.needs_spans(),
1979 None => plan.projection.is_some(),
1980 };
1981 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1983 while let Some(entry) = if plan.descending {
1984 entries.next_back()
1985 } else {
1986 entries.next()
1987 } {
1988 if request.work == 0 {
1992 return Err(Error::Limit);
1993 }
1994 page.examined += 1;
1995 let stored_key = entry.key();
1996 let mut read_bytes = stored_key.len();
1997 let (owner, bytes) = if plan.index.is_some() {
1998 let owner_bytes = entry.value();
1999 read_bytes += owner_bytes.len();
2000 let owner = RowKey::decode(&owner_bytes, primary_type)?;
2001 let bytes = map.get(&row_key(entity.id, owner)).ok_or(Error::Corrupt)?;
2002
2003 (owner, bytes)
2004 } else {
2005 (
2006 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
2007 entry.value(),
2008 )
2009 };
2010 if let Some(used) = input_bytes.as_deref_mut() {
2011 read_bytes += bytes.len();
2012 if read_bytes > CANDIDATE_BYTES {
2013 return Err(Error::Corrupt);
2014 }
2015 *used += read_bytes;
2016 }
2017 page.fetched += 1;
2018 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
2019 entity.inspect_fields(
2020 &bytes,
2021 plan.selected,
2022 &mut values,
2023 needs_spans.then_some(&mut spans),
2024 )?;
2025 if RowKey::from_index(values[plan.primary])? != owner {
2026 return Err(Error::Corrupt);
2027 }
2028 if plan.index.is_some() {
2029 validate_index_entry(
2030 entity,
2031 &entity.row_info(&values, &bytes, &spans)?,
2032 owner,
2033 stored_key,
2034 )?;
2035 }
2036 let read = |position: usize, member: Option<crate::member::RecordMember>| {
2037 if let Some(member) = member {
2038 let (start, end) = spans[position];
2039 member.read(
2040 &bytes[usize::from(start)..usize::from(end)],
2041 entity.fields[position].optional,
2042 )
2043 } else {
2044 Ok(values[position])
2045 }
2046 };
2047 let mut accepts = |term: &Term, supplied: &QueryOperand<'_>| -> Result<bool, Error> {
2048 let mut value = values[term.position];
2049 component.clear();
2050 let (operand, optional) = match &term.operand {
2051 TermOperand::Nested {
2052 member,
2053 literal,
2054 absent,
2055 } => {
2056 value = read(term.position, Some(*member))?;
2057 if *absent {
2058 return Ok(term.comparison.accepts_absent(value == IndexValue::Absent));
2059 }
2060 (Some(literal.as_slice()), false)
2061 }
2062 TermOperand::Literal { absent: true, .. } => {
2063 let absent = if plan.span_fields & (1 << term.position) != 0 {
2064 bytes[usize::from(spans[term.position].0)] == 0
2065 } else {
2066 value == IndexValue::Absent
2067 };
2068
2069 return Ok(term.comparison.accepts_absent(absent));
2070 }
2071 TermOperand::Member { item, needle } => {
2072 let needle = match (needle, supplied) {
2073 (MemberNeedle::Literal(_), QueryOperand::Literal(value)) => *value,
2074 (MemberNeedle::Field(right, member), QueryOperand::Field(_)) => {
2075 read(*right, *member)?
2076 }
2077 _ => return Err(Error::Corrupt),
2078 };
2079 if needle == IndexValue::Absent {
2080 return Ok(false);
2081 }
2082 let (start, end) = spans[term.position];
2083
2084 return contains_member(
2085 &bytes[usize::from(start)..usize::from(end)],
2086 entity.fields[term.position].optional,
2087 *item,
2088 needle,
2089 );
2090 }
2091 TermOperand::Length { member, threshold } => {
2092 let (start, end) = spans[term.position];
2093 let span = &bytes[usize::from(start)..usize::from(end)];
2094 let optional = entity.fields[term.position].optional;
2095 let actual = if let Some(member) = member {
2096 match member.read(span, optional)? {
2097 IndexValue::Absent => None,
2098 value => Some(scalar_bytes(value).ok_or(Error::Corrupt)?.len() as u32),
2099 }
2100 } else {
2101 crate::codec::validated_length(span, optional)
2102 };
2103
2104 return Ok(term.comparison.accepts_length(actual, *threshold));
2105 }
2106 TermOperand::Literal {
2107 bytes,
2108 absent: false,
2109 } => (
2110 Some(bytes.as_slice()),
2111 entity.fields[term.position].optional,
2112 ),
2113 TermOperand::Field {
2114 right,
2115 left_member,
2116 right_member,
2117 } => {
2118 value = read(term.position, *left_member)?;
2119 let rhs = read(*right, *right_member)?;
2120 if value == IndexValue::Absent || rhs == IndexValue::Absent {
2121 return Ok(term.comparison.accepts_absent(value == rhs));
2122 }
2123 if let Some(matches) = term.comparison.accepts_values(value, rhs) {
2124 return Ok(matches);
2125 }
2126 right_component.clear();
2127 rhs.append_component(false, &mut right_component);
2128
2129 (Some(right_component.as_slice()), false)
2130 }
2131 };
2132 if let QueryOperand::Literal(right) = supplied
2133 && let Some(matches) = term.comparison.accepts_values(value, *right)
2134 {
2135 return Ok(matches);
2136 }
2137 value.append_component(optional, &mut component);
2138
2139 Ok(term.comparison.accepts(
2140 (value != IndexValue::Absent).then_some(component.as_slice()),
2141 operand,
2142 optional,
2143 ))
2144 };
2145 let matches = 'matches: {
2146 let mut clause_matches = false;
2147 for (term, predicate) in plan.terms.iter().zip(&request.predicates) {
2148 clause_matches = clause_matches || accepts(term, &predicate.operand)?;
2149 if !term.or_next {
2150 if !clause_matches {
2151 break 'matches false;
2152 }
2153 clause_matches = false;
2154 }
2155 }
2156
2157 true
2158 };
2159 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
2160 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2161 if matches && let Some(accumulator) = aggregate.as_mut() {
2162 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2163 if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
2164 return Ok(page);
2166 }
2167 } else if matches && let Some(collection) = collected.as_mut() {
2168 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2169 if request.single_result_probe && collection.rows.len() == request.rows {
2172 break;
2173 }
2174 } else if matches && let Some(collection) = sorted.as_mut() {
2175 collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2176 } else if matches && !duplicate {
2177 let size = plan
2178 .projection
2179 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2180 if size > request.bytes {
2181 return Err(Error::RowTooLarge);
2182 }
2183 if size > request.bytes - page.output_bytes {
2184 page.next = Some(plan.cursor(stored_key, Resume::Retry));
2185
2186 return Ok(page);
2187 }
2188 page.output_bytes += size;
2189 if let Some(mask) = plan.projection {
2190 page.rows.push(copy_projection(&bytes, &spans, mask, size));
2191 } else {
2192 page.rows.push(bytes);
2193 }
2194 if plan.distinct == distinct::Strategy::FirstMatch {
2195 return Ok(page);
2196 }
2197 if let Some(boundary) = boundary {
2198 previous = Some(boundary.to_vec());
2199 }
2200 }
2201 if page.rows.len() == request.rows
2202 || page.examined == request.work
2203 || input_bytes
2204 .as_deref()
2205 .is_some_and(|used| *used > STEP_INPUT_BYTES - CANDIDATE_BYTES)
2206 {
2207 if terminal == Some(stored_key) {
2208 break;
2209 }
2210 if (aggregate.is_some() && input_bytes.is_none())
2211 || collected.is_some()
2212 || sorted.is_some()
2213 {
2214 return Err(Error::Limit);
2217 }
2218 let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
2219 Resume::AfterUnemittedClass
2220 } else {
2221 Resume::After
2222 };
2223 page.next = Some(plan.cursor(stored_key, resume));
2224
2225 return Ok(page);
2226 }
2227 }
2228 if let Some(collection) = collected {
2229 page.output_bytes = collection.output_bytes;
2230 page.rows = collection.rows;
2231 }
2232 if let Some(collection) = sorted {
2233 collection.finish(request.bytes, &mut page)?;
2234 }
2235
2236 Ok(page)
2237}