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 if let Some(equality) = predicate.fixed_equality(entity) {
551 return rest
552 .iter()
553 .all(|other| other.fixed_equality(entity) == Some(equality))
554 .then_some(equality);
555 }
556 let ([], Comparison::Ge, QueryOperand::Literal(lower)) =
559 (rest, predicate.comparison, predicate.operand)
560 else {
561 return None;
562 };
563 self.clauses()
564 .any(|clause| {
565 let [upper] = clause else { return false };
566 upper.comparison == Comparison::Le
567 && upper.field == predicate.field
568 && upper.operand == QueryOperand::Literal(lower)
569 })
570 .then_some((predicate.field, lower))
571 })
572 }
573
574 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
575 self.predicates.split_inclusive(|p| !p.or_next)
576 }
577
578 #[inline(never)]
579 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
580 if self.predicates.len() == MAX_TERMS {
581 self.over_limit = true;
582 } else {
583 self.predicates.push(Predicate {
584 field,
585 comparison,
586 operand,
587 or_next: false,
588 });
589 }
590 }
591
592 #[inline(never)]
593 fn or_clause(
594 &mut self,
595 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
596 ) {
597 let count = alternatives.len();
598
599 if count == 0 || count > MAX_TERMS - self.predicates.len() {
600 self.over_limit = true;
601 } else {
602 self.predicates.extend(alternatives.enumerate().map(
603 |(i, (field, comparison, operand))| Predicate {
604 field,
605 comparison,
606 operand,
607 or_next: i + 1 < count,
608 },
609 ));
610 }
611 }
612
613 #[inline(never)]
614 fn filter_not_in(
615 &mut self,
616 field: &'a str,
617 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
618 ) {
619 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
620 self.over_limit = true;
621
622 return;
623 }
624 for value in values {
625 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
626 }
627 }
628
629 #[inline(never)]
630 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
631 if values.len() > 4 {
632 self.over_limit = true;
633 } else {
634 self.index = Some((name, values.to_vec()));
635 }
636 }
637
638 #[inline(never)]
639 fn order_by(&mut self, fields: &[&'a str]) {
640 self.order_descending = 0;
641
642 if fields.len() > 4 {
643 self.over_limit = true;
644 } else {
645 self.order = Some(fields.to_vec());
646 }
647 }
648
649 #[inline(never)]
650 fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
651 if fields.len() > 4 {
652 self.over_limit = true;
653
654 return;
655 }
656 self.order = Some(Vec::with_capacity(fields.len()));
657 self.order_descending = 0;
658 for &(field, direction) in fields {
659 self.append_order(field, direction);
660 }
661 }
662
663 fn append_order(&mut self, field: &'a str, direction: SortDirection) {
664 let fields = self.order.get_or_insert_with(Vec::new);
665 if fields.len() == 4 {
666 self.over_limit = true;
667
668 return;
669 }
670 if direction == SortDirection::Descending {
671 self.order_descending |= 1 << fields.len();
672 }
673 fields.push(field);
674 }
675
676 fn primary_descending(&self, entity: &EntitySchema) -> bool {
677 self.order_descending != 0
678 && self.order.as_ref().is_some_and(|fields| {
679 fields.last() == Some(&entity.primary_key)
680 && self.order_descending & (1 << (fields.len() - 1)) != 0
681 })
682 }
683}
684
685pub(super) fn source_page<M: Memory>(
687 map: &Map<M>,
688 entity: &EntitySchema,
689 binding: [u8; 32],
690 incarnation: [u8; 16],
691 cursor: Option<&QueryCursor>,
692 rows: usize,
693 bytes: usize,
694) -> Result<QueryPage<Vec<u8>>, Error> {
695 let request = Request {
696 rows,
697 work: rows,
698 bytes,
699 cursor,
700 ..Request::default()
701 };
702 let plan = Plan::admit(
703 entity,
704 &request,
705 binding,
706 incarnation,
707 None,
708 PlanOutput::Rows,
709 )?;
710
711 execute(map, entity, &request, &plan, None)
712}
713
714enum QuerySource<'a, M: Memory> {
715 Direct(&'a Database<M>),
716 Session(Rc<RefCell<Database<M>>>),
717}
718
719enum QueryRead<'a, M: Memory> {
720 Direct(&'a Database<M>),
721 Session(Ref<'a, Database<M>>),
722}
723
724impl<M: Memory> Deref for QueryRead<'_, M> {
725 type Target = Database<M>;
726
727 fn deref(&self) -> &Self::Target {
728 match self {
729 Self::Direct(db) => db,
730 Self::Session(db) => db,
731 }
732 }
733}
734
735impl<M: Memory> QuerySource<'_, M> {
736 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
737 match self {
738 Self::Direct(db) => Ok(QueryRead::Direct(db)),
739 Self::Session(db) => db
740 .try_borrow()
741 .map(QueryRead::Session)
742 .map_err(|_| Error::BorrowConflict),
743 }
744 }
745}
746
747pub struct Query<'a, E, M: Memory> {
751 db: QuerySource<'a, M>,
752 request: Request<'a>,
753 entity: PhantomData<E>,
754}
755impl<M: Memory> Database<M> {
756 #[must_use]
758 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
759 Query {
760 db: QuerySource::Direct(self),
761 entity: PhantomData,
762 request: Request::default(),
763 }
764 }
765}
766impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
767 pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
768 Self {
769 db: QuerySource::Session(db),
770 request: Request::default(),
771 entity: PhantomData,
772 }
773 }
774
775 #[must_use]
789 pub fn distinct(mut self) -> Self {
790 self.request.distinct = true;
791
792 self
793 }
794
795 #[must_use]
808 pub fn filter(
809 mut self,
810 field: &'a str,
811 comparison: Comparison,
812 value: impl Into<IndexValue<'a>>,
813 ) -> Self {
814 self.request
815 .filter(field, comparison, QueryOperand::Literal(value.into()));
816
817 self
818 }
819
820 #[must_use]
822 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
823 self.filter(field, Comparison::Eq, value)
824 }
825
826 #[must_use]
828 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
829 self.filter(field, Comparison::Ne, value)
830 }
831
832 #[must_use]
834 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
835 self.filter(field, Comparison::Lt, value)
836 }
837
838 #[must_use]
840 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
841 self.filter(field, Comparison::Le, value)
842 }
843
844 #[must_use]
846 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
847 self.filter(field, Comparison::Gt, value)
848 }
849
850 #[must_use]
852 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
853 self.filter(field, Comparison::Ge, value)
854 }
855
856 #[must_use]
864 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
865 self.request
866 .filter(left, comparison, QueryOperand::Field(right));
867
868 self
869 }
870
871 #[must_use]
876 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
877 self.request
878 .filter(field, comparison, QueryOperand::Length(length));
879
880 self
881 }
882
883 #[must_use]
886 pub fn filter_present(self, field: &'a str) -> Self {
887 self.filter(field, Comparison::Ne, IndexValue::Absent)
888 }
889
890 #[must_use]
893 pub fn filter_absent(self, field: &'a str) -> Self {
894 self.filter(field, Comparison::Eq, IndexValue::Absent)
895 }
896
897 #[must_use]
904 pub fn filter_between(
905 self,
906 field: &'a str,
907 lower: impl Into<IndexValue<'a>>,
908 upper: impl Into<IndexValue<'a>>,
909 ) -> Self {
910 self.filter(field, Comparison::Ge, lower)
911 .filter(field, Comparison::Le, upper)
912 }
913
914 #[must_use]
922 pub fn filter_not_between(
923 self,
924 field: &'a str,
925 lower: impl Into<IndexValue<'a>>,
926 upper: impl Into<IndexValue<'a>>,
927 ) -> Self {
928 self.filter_any(&[
929 (field, Comparison::Lt, lower.into()),
930 (field, Comparison::Gt, upper.into()),
931 ])
932 }
933
934 #[must_use]
939 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
940 self.filter_fields(field, Comparison::Ge, lower)
941 .filter_fields(field, Comparison::Le, upper)
942 }
943
944 #[must_use]
949 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
950 self.filter_any_operands(&[
951 (field, Comparison::Lt, QueryOperand::Field(lower)),
952 (field, Comparison::Gt, QueryOperand::Field(upper)),
953 ])
954 }
955
956 #[must_use]
964 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
965 self.request.or_clause(
966 alternatives
967 .iter()
968 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
969 );
970
971 self
972 }
973
974 #[must_use]
979 pub fn filter_any_operands(
980 mut self,
981 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
982 ) -> Self {
983 self.request.or_clause(alternatives.iter().copied());
984
985 self
986 }
987
988 #[must_use]
998 pub fn filter_in(
999 mut self,
1000 field: &'a str,
1001 values: &[impl Copy + Into<IndexValue<'a>>],
1002 ) -> Self {
1003 self.request.or_clause(
1004 values
1005 .iter()
1006 .copied()
1007 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
1008 );
1009
1010 self
1011 }
1012
1013 #[must_use]
1021 pub fn filter_not_in(
1022 mut self,
1023 field: &'a str,
1024 values: &[impl Copy + Into<IndexValue<'a>>],
1025 ) -> Self {
1026 self.request
1027 .filter_not_in(field, values.iter().copied().map(Into::into));
1028
1029 self
1030 }
1031
1032 #[must_use]
1037 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
1038 self.request.using_index(name, values);
1039
1040 self
1041 }
1042
1043 #[must_use]
1046 pub fn order_asc(mut self, field: &'a str) -> Self {
1047 self.request.append_order(field, SortDirection::Ascending);
1048
1049 self
1050 }
1051
1052 #[must_use]
1055 pub fn order_desc(mut self, field: &'a str) -> Self {
1056 self.request.append_order(field, SortDirection::Descending);
1057
1058 self
1059 }
1060
1061 #[must_use]
1072 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
1073 self.request.order_by(fields);
1074
1075 self
1076 }
1077
1078 #[must_use]
1083 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
1084 self.request.order_by_each(fields);
1085
1086 self
1087 }
1088
1089 #[must_use]
1091 pub fn descending(mut self) -> Self {
1092 self.request.descending = true;
1093
1094 self
1095 }
1096
1097 #[must_use]
1104 pub fn limit(mut self, rows: usize) -> Self {
1105 self.request.rows = rows;
1106
1107 self
1108 }
1109
1110 #[must_use]
1112 pub fn work_limit(mut self, candidates: usize) -> Self {
1113 self.request.work = candidates;
1114
1115 self
1116 }
1117
1118 #[cfg(feature = "test-support")]
1120 #[doc(hidden)]
1121 #[must_use]
1122 pub fn test_output_limit(mut self, bytes: usize) -> Self {
1123 self.request.bytes = bytes;
1124
1125 self
1126 }
1127
1128 #[must_use]
1130 pub fn after(mut self, cursor: &'a QueryCursor) -> Self {
1131 self.request.cursor = Some(cursor);
1132
1133 self
1134 }
1135
1136 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
1143 observe!(query, { self.entity_page() })
1144 }
1145
1146 fn entity_page(self) -> Result<QueryPage<E>, Error> {
1147 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
1148 }
1149
1150 pub fn first(self) -> Result<Option<E>, Error> {
1156 self.first_with(Self::entity_page)
1157 }
1158
1159 pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
1163 self.first_with(Self::projected_page::<R>)
1164 }
1165
1166 fn first_with<R>(
1167 self,
1168 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1169 ) -> Result<Option<R>, Error> {
1170 observe!(query, {
1171 let page = fetch(self.probe_matches(1)?)?;
1172 if page.rows.is_empty() && page.next.is_some() {
1173 return Err(Error::Limit);
1174 }
1175 Ok(page)
1176 })
1177 .map(|mut page| page.rows.pop())
1178 }
1179
1180 pub fn try_one(self) -> Result<Option<E>, Error> {
1187 self.try_one_with(Self::entity_page)
1188 }
1189
1190 pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
1196 self.try_one_with(Self::projected_page::<R>)
1197 }
1198
1199 fn try_one_with<R>(
1200 self,
1201 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1202 ) -> Result<Option<R>, Error> {
1203 observe!(query, {
1204 if self.request.cursor.is_some() {
1205 return Err(Error::InvalidQuery);
1206 }
1207 let page = fetch(self.probe_matches(2)?)?;
1208 if page.rows.len() == 2 {
1209 return Err(Error::MultipleMatches);
1210 }
1211 if page.next.is_some() {
1212 return Err(Error::Limit);
1213 }
1214
1215 Ok(page)
1216 })
1217 .map(|mut page| page.rows.pop())
1218 }
1219
1220 fn probe_matches(mut self, rows: usize) -> Result<Self, Error> {
1221 if !(1..=32).contains(&self.request.rows) {
1222 return Err(Error::Limit);
1223 }
1224
1225 self.request.single_result_probe = true;
1226
1227 Ok(self.limit(rows))
1228 }
1229
1230 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1240 observe!(query, { self.projected_page() })
1241 }
1242
1243 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1244 let raw = fetch_rows(
1245 &*self.db.read()?,
1246 E::SCHEMA,
1247 self.request,
1248 Some(R::definition()),
1249 )?;
1250
1251 raw.decode_projection()
1252 }
1253}
1254
1255fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u32, Error> {
1259 let TypeBody::Record(fields) = &output.body else {
1260 return Err(Error::InvalidQuery);
1261 };
1262 if fields.is_empty()
1263 || fields.len() > crate::schema::MAX_FIELDS
1264 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1265 {
1266 return Err(Error::InvalidQuery);
1267 }
1268 let mut source = TypeGraph::default();
1269 let mut target = TypeGraph::default();
1270 let mut mask = 0;
1271 for field in *fields {
1272 let position = entity
1273 .field_position(field.name)
1274 .ok_or(Error::InvalidQuery)?;
1275 let stored = &entity.fields[position];
1276 if stored.value != field.value || stored.optional != field.optional {
1277 return Err(Error::InvalidQuery);
1278 }
1279 source
1280 .include(stored.value)
1281 .map_err(|_| Error::InvalidQuery)?;
1282 target
1283 .include(field.value)
1284 .map_err(|_| Error::InvalidQuery)?;
1285 mask |= 1 << position;
1286 }
1287 if !source.contains(&target) {
1288 return Err(Error::InvalidQuery);
1289 }
1290
1291 Ok(mask)
1292}
1293
1294struct Term {
1295 tests_presence: bool,
1296 position: usize,
1297 comparison: Comparison,
1298 operand: TermOperand,
1299 or_next: bool,
1300}
1301
1302enum TermOperand {
1303 Literal {
1304 bytes: Vec<u8>,
1305 absent: bool,
1306 },
1307 Member {
1308 item: FieldType,
1309 needle: MemberNeedle,
1310 },
1311 Nested {
1312 member: crate::member::RecordMember,
1313 literal: Vec<u8>,
1314 absent: bool,
1315 },
1316 Field {
1317 right: usize,
1318 left_member: Option<crate::member::RecordMember>,
1319 right_member: Option<crate::member::RecordMember>,
1320 },
1321 Length {
1322 member: Option<crate::member::RecordMember>,
1323 threshold: u32,
1324 },
1325}
1326
1327enum MemberNeedle {
1328 Literal(Vec<u8>),
1329 Field(usize, Option<crate::member::RecordMember>),
1330}
1331
1332fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1335 match value {
1336 IndexValue::Text(text) => Some(text.as_bytes()),
1337 IndexValue::Blob(bytes) => Some(bytes),
1338 _ => None,
1339 }
1340}
1341
1342fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1343 match (left, right) {
1345 (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1346 a == b
1347 }
1348 _ => left == right,
1349 }
1350}
1351
1352fn length_limit(field: FieldType) -> Option<u32> {
1353 match key::operand_type(field) {
1354 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1355 FieldType::List { max_items, .. } => Some(max_items),
1356 FieldType::Named(link) => match (link.definition)().body {
1357 TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1358 _ => None,
1359 },
1360 _ => None,
1361 }
1362}
1363
1364fn member_type(field: FieldType) -> Option<FieldType> {
1365 match key::operand_type(field) {
1366 FieldType::List { item, .. } => Some(*item),
1367 FieldType::Named(link) => match (link.definition)().body {
1368 TypeBody::Set { item, .. } => Some(item),
1369 _ => None,
1370 },
1371 _ => None,
1372 }
1373}
1374
1375fn contains_member(
1377 span: &[u8],
1378 optional: bool,
1379 item: FieldType,
1380 needle: IndexValue<'_>,
1381) -> Result<bool, Error> {
1382 let mut reader = Decoder::new(span)?;
1383 if optional && !reader.boolean()? {
1384 return Ok(false);
1385 }
1386 for _ in 0..reader.nat32()? {
1387 let value = IndexValue::read(&mut reader, item)?;
1388 if equal_values(value, needle) {
1389 return Ok(true);
1390 }
1391 }
1392
1393 Ok(false)
1394}
1395
1396fn projection_positions(mut mask: u32) -> impl Iterator<Item = usize> {
1399 std::iter::from_fn(move || {
1400 if mask == 0 {
1401 return None;
1402 }
1403 let position = mask.trailing_zeros() as usize;
1404 mask &= mask - 1;
1405 Some(position)
1406 })
1407}
1408
1409fn admit_ordered_fields(entity: &EntitySchema, mask: u32) -> Result<(), Error> {
1410 for i in projection_positions(mask) {
1411 if !key::supports(entity.fields[i].value) {
1412 return Err(Error::InvalidQuery);
1413 }
1414 }
1415
1416 Ok(())
1417}
1418
1419fn comparison_key(
1421 entity: &EntitySchema,
1422 mask: u32,
1423 values: &[IndexValue<'_>],
1424 scratch: &mut Vec<u8>,
1425) -> Result<(), Error> {
1426 build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1427}
1428
1429fn build_comparison_key<'a>(
1430 entity: &EntitySchema,
1431 mask: u32,
1432 key: &mut Vec<u8>,
1433 mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1434) -> Result<(), Error> {
1435 key.clear();
1436 for i in projection_positions(mask) {
1437 let field = &entity.fields[i];
1438 value(i, field)?.append_component(field.optional, key);
1439 if key.len() > MAX_COMPARISON_KEY {
1440 return Err(Error::Limit);
1441 }
1442 }
1443
1444 Ok(())
1445}
1446
1447fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1448 if size > limit {
1449 return Err(Error::RowTooLarge);
1450 }
1451 if size > limit - *used {
1452 return Err(Error::Limit);
1453 }
1454 *used += size;
1455
1456 Ok(())
1457}
1458
1459fn projection_size(spans: &[(u16, u16)], mask: u32) -> usize {
1461 projection_positions(mask)
1462 .map(|i| {
1463 let (start, end) = spans[i];
1464 usize::from(end - start)
1465 })
1466 .sum()
1467}
1468
1469fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u32, size: usize) -> Vec<u8> {
1470 let mut output = Vec::with_capacity(size);
1471 for i in projection_positions(mask) {
1472 let (start, end) = spans[i];
1473 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1474 }
1475
1476 output
1477}
1478#[derive(Clone, Copy)]
1479enum PlanOutput {
1480 Rows,
1481 Aggregate { grouped: bool },
1482}
1483
1484struct Plan<'a> {
1485 primary: usize,
1486 index: Option<&'a IndexSchema>,
1487 prefix: Vec<u8>,
1488 fixed_components: usize,
1489 terms: Vec<Term>,
1490 selected: u32,
1491 span_fields: u32,
1493 binding: [u8; 32],
1494 projection: Option<u32>,
1495 distinct: distinct::Strategy,
1496 sort: Option<Vec<order::SortField>>,
1497 descending: bool,
1498}
1499impl<'a> Plan<'a> {
1500 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1501 self.terms.split_inclusive(|term| !term.or_next)
1502 }
1503
1504 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1505 self.index = Some(path.index);
1506 self.prefix = path.prefix;
1507 self.fixed_components = path.fixed;
1508 self.selected |= entity.key_fields();
1509 }
1510
1511 fn admit(
1512 entity: &'a EntitySchema,
1513 request: &Request<'_>,
1514 schema: [u8; 32],
1515 incarnation: [u8; 16],
1516 projection: Option<&TypeSchema>,
1517 output: PlanOutput,
1518 ) -> Result<Self, Error> {
1519 if request.over_limit
1520 || !(1..=32).contains(&request.rows)
1521 || !(1..=MAX_WORK).contains(&request.work)
1522 || !(1..=MAX_OUTPUT).contains(&request.bytes)
1523 {
1524 return Err(Error::Limit);
1525 }
1526 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1527 {
1528 return Err(Error::InvalidQuery);
1529 }
1530 for value in request
1532 .predicates
1533 .iter()
1534 .filter_map(|p| match &p.operand {
1535 QueryOperand::Literal(value) => Some(value),
1536 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1537 })
1538 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1539 {
1540 if match value {
1541 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1542 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1543 _ => false,
1544 } {
1545 return Err(Error::Limit);
1546 }
1547 }
1548 let primary = entity
1549 .field_position(entity.primary_key)
1550 .filter(|&i| !entity.fields[i].optional)
1551 .ok_or(Error::InvalidQuery)?;
1552 let mut plan = Self {
1553 primary,
1554 index: None,
1555 prefix: prefix(2, entity.id),
1556 fixed_components: 0,
1557 terms: Vec::new(),
1558 selected: 1 << primary,
1559 span_fields: 0,
1560 binding: [0; 32],
1561 projection: projection
1562 .map(|output| admit_projection(entity, output))
1563 .transpose()?,
1564 distinct: distinct::Strategy::Identity,
1565 sort: None,
1566 descending: request.descending ^ request.primary_descending(entity),
1567 };
1568 for predicate in &request.predicates {
1569 let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
1570 let field = &entity.fields[position];
1571 let member = if predicate.comparison == Comparison::Contains {
1572 member_type(field.value)
1573 } else {
1574 None
1575 };
1576 let operand = match (predicate.operand, record_member) {
1577 (QueryOperand::Literal(value), Some(member)) => {
1578 if !predicate.comparison.supports_record_member() {
1579 return Err(Error::InvalidQuery);
1580 }
1581 let leaf = member.field();
1582 predicate.comparison.admit(
1583 leaf.value,
1584 field.optional || leaf.optional,
1585 value,
1586 )?;
1587 let mut literal = Vec::new();
1588 value.append_component(false, &mut literal);
1589 plan.span_fields |= 1 << position;
1590 TermOperand::Nested {
1591 member,
1592 literal,
1593 absent: value == IndexValue::Absent,
1594 }
1595 }
1596 (QueryOperand::Length(length), member) => {
1597 let selected = member.map_or(field.value, |m| m.field().value);
1598 if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1599 return Err(Error::InvalidQuery);
1600 }
1601 plan.span_fields |= 1 << position;
1602
1603 TermOperand::Length {
1604 member,
1605 threshold: length,
1606 }
1607 }
1608 (QueryOperand::Field(name), left_member) => {
1609 let (right, right_member) = crate::member::resolve_field(entity, name)?;
1610 if (left_member.is_some() || right_member.is_some())
1611 && member.is_none()
1612 && !predicate.comparison.supports_record_member()
1613 {
1614 return Err(Error::InvalidQuery);
1615 }
1616 let right_type =
1617 right_member.map_or(entity.fields[right].value, |m| m.field().value);
1618 let left_type =
1619 left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1620 let compatible = left_type == right_type
1621 || matches!(
1622 (left_type, right_type),
1623 (FieldType::Text { .. }, FieldType::Text { .. })
1624 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1625 );
1626 if !compatible
1627 || !key::supports(left_type)
1628 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1629 {
1630 return Err(Error::InvalidQuery);
1631 }
1632 if right_member.is_some() {
1633 plan.span_fields |= 1 << right;
1634 } else {
1635 plan.selected |= 1 << right;
1636 }
1637
1638 if let Some(item) = member {
1639 plan.span_fields |= 1 << position;
1640
1641 TermOperand::Member {
1642 item,
1643 needle: MemberNeedle::Field(right, right_member),
1644 }
1645 } else {
1646 if left_member.is_some() {
1647 plan.span_fields |= 1 << position;
1648 } else {
1649 plan.selected |= 1 << position;
1650 }
1651 TermOperand::Field {
1652 right,
1653 left_member,
1654 right_member,
1655 }
1656 }
1657 }
1658 (QueryOperand::Literal(value), None) => {
1659 if let Some(item) = member {
1660 if !key::supports(item) {
1661 return Err(Error::InvalidQuery);
1662 }
1663 value.admit(item, false)?;
1664 let mut bytes = Vec::new();
1665 value.append_component(false, &mut bytes);
1666 plan.span_fields |= 1 << position;
1667
1668 TermOperand::Member {
1669 item,
1670 needle: MemberNeedle::Literal(bytes),
1671 }
1672 } else {
1673 let absent = value == IndexValue::Absent;
1674 if key::supports(field.value) {
1675 plan.selected |= 1 << position;
1676 } else if absent
1677 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1678 {
1679 plan.span_fields |= 1 << position;
1680 } else {
1681 return Err(Error::InvalidQuery);
1682 }
1683 predicate
1684 .comparison
1685 .admit(field.value, field.optional, value)?;
1686 let mut bytes = Vec::new();
1687 value.append_component(field.optional, &mut bytes);
1688
1689 TermOperand::Literal { bytes, absent }
1690 }
1691 }
1692 };
1693 plan.terms.push(Term {
1694 tests_presence: predicate.tests_presence(entity, &operand),
1695 position,
1696 comparison: predicate.comparison,
1697 operand,
1698 or_next: predicate.or_next,
1699 });
1700 }
1701 match order::select(entity, request, output)? {
1704 order::Path::Primary => {}
1705 order::Path::Index(path, descending) => {
1706 plan.use_index(entity, path);
1707 plan.descending = request.descending ^ descending;
1708 }
1709 order::Path::Sort(fields) => {
1710 order::select_filtered_path(entity, request, &mut plan, None)?;
1711 for field in &fields {
1712 if field.member.is_some() {
1713 plan.span_fields |= 1 << field.position;
1714 } else {
1715 plan.selected |= 1 << field.position;
1716 }
1717 }
1718 plan.sort = Some(fields);
1719 }
1720 }
1721 if request.distinct {
1722 plan.distinct = distinct::admit(entity, request, &plan)?;
1723 if let distinct::Strategy::Complete { key_fields } = plan.distinct {
1724 plan.selected |= key_fields;
1725 }
1726 }
1727 let mut hash = Sha256::new();
1728 hash.update(b"ic-db:query:v1\0");
1729 hash.update(schema);
1730 hash.update(incarnation);
1731 hash.update([u8::from(request.descending)]);
1732 hash.update((plan.prefix.len() as u32).to_le_bytes());
1733 hash.update(&plan.prefix);
1734 for term in &plan.terms {
1735 hash.update([term.position as u8, term.comparison as u8]);
1736
1737 match &term.operand {
1738 TermOperand::Nested {
1739 member,
1740 literal,
1741 absent,
1742 } => {
1743 hash.update((u32::MAX - 2).to_le_bytes());
1744 hash.update([member.position() as u8, u8::from(*absent)]);
1745 hash.update((literal.len() as u32).to_le_bytes());
1746 hash.update(literal);
1747 }
1748 TermOperand::Literal { bytes, .. }
1749 | TermOperand::Member {
1750 needle: MemberNeedle::Literal(bytes),
1751 ..
1752 } => {
1753 hash.update((bytes.len() as u32).to_le_bytes());
1754 hash.update(bytes);
1755 }
1756 TermOperand::Length { member, threshold } => {
1757 if let Some(member) = member {
1758 hash.update((u32::MAX - 3).to_le_bytes());
1759 hash.update([member.position() as u8]);
1760 } else {
1761 hash.update((u32::MAX - 1).to_le_bytes());
1762 }
1763 hash.update(threshold.to_le_bytes());
1764 }
1765 TermOperand::Field {
1766 right,
1767 left_member: None,
1768 right_member: None,
1769 }
1770 | TermOperand::Member {
1771 needle: MemberNeedle::Field(right, None),
1772 ..
1773 } => {
1774 hash.update(u32::MAX.to_le_bytes());
1776 hash.update([*right as u8]);
1777 }
1778 TermOperand::Member {
1779 needle: MemberNeedle::Field(right, Some(member)),
1780 ..
1781 } => {
1782 hash.update((u32::MAX - 4).to_le_bytes());
1783 hash.update([u8::MAX, *right as u8, member.position() as u8]);
1784 }
1785 TermOperand::Field {
1786 right,
1787 left_member,
1788 right_member,
1789 } => {
1790 hash.update((u32::MAX - 4).to_le_bytes());
1791 let slot = |member: &Option<crate::member::RecordMember>| {
1792 member.map_or(u8::MAX, |m| m.position() as u8)
1793 };
1794 hash.update([slot(left_member), *right as u8, slot(right_member)]);
1795 }
1796 }
1797 }
1798 let clauses = plan
1801 .terms
1802 .iter()
1803 .enumerate()
1804 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1805 if clauses != 0 {
1806 hash.update(b"or-clauses\0");
1807 hash.update([clauses]);
1808 }
1809 if let Some(order) = &request.order {
1810 hash.update(b"order\0");
1811 hash.update([order.len() as u8]);
1812 for name in order {
1813 if let Some(position) = entity.field_position(name) {
1815 hash.update([position as u8]);
1816 } else {
1817 hash.update([u8::MAX, name.len() as u8]);
1819 hash.update(name.as_bytes());
1820 }
1821 }
1822 }
1823 if request.order_descending != 0 {
1824 hash.update(b"order-directions\0");
1825 hash.update([request.order_descending]);
1826 }
1827 if let Some(mask) = plan.projection {
1830 hash.update(b"projection\0");
1831 hash.update(mask.to_le_bytes());
1832 }
1833 if request.distinct {
1834 hash.update(b"distinct\0");
1835 }
1836 plan.binding = hash.finalize().into();
1837 if let Some(cursor) = request.cursor {
1838 if cursor.binding != plan.binding {
1839 return Err(Error::InvalidCursor);
1840 }
1841 plan.validate_position(entity, cursor)
1842 .map_err(|_| Error::InvalidCursor)?;
1843 }
1844
1845 Ok(plan)
1846 }
1847
1848 fn validate_position(&self, entity: &EntitySchema, cursor: &QueryCursor) -> Result<(), Error> {
1849 if cursor.resume == Resume::AfterUnemittedClass
1850 && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
1851 {
1852 return Err(Error::InvalidCursor);
1853 }
1854 let bytes = cursor.position.as_slice();
1855 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
1856 return Err(Error::InvalidCursor);
1857 }
1858 if let Some(index) = self.index {
1859 let mut remaining = bytes
1860 .get(INDEX_PREFIX_BYTES..)
1861 .ok_or(Error::InvalidCursor)?;
1862 for name in index.fields {
1863 consume_index_component(entity, index, name, &mut remaining)?;
1864 }
1865 if !index.unique {
1866 key::consume(&mut remaining, entity.key_type()?)?;
1867 }
1868 if !remaining.is_empty() {
1869 return Err(Error::InvalidCursor);
1870 }
1871 } else {
1872 RowKey::decode(
1873 bytes
1874 .get(ENTITY_PREFIX_BYTES..)
1875 .ok_or(Error::InvalidCursor)?,
1876 entity.key_type()?,
1877 )?;
1878 }
1879
1880 Ok(())
1881 }
1882
1883 fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
1884 QueryCursor {
1885 binding: self.binding,
1886 position: position.to_vec(),
1887 resume,
1888 }
1889 }
1890}
1891
1892fn consume_index_component(
1894 entity: &EntitySchema,
1895 index: &IndexSchema,
1896 name: &str,
1897 remaining: &mut &[u8],
1898) -> Result<(), Error> {
1899 let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
1900
1901 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
1902}
1903
1904#[inline(never)]
1907#[expect(
1908 clippy::needless_pass_by_value,
1909 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1910)]
1911fn fetch_rows<M: Memory>(
1912 db: &Database<M>,
1913 entity: &EntitySchema,
1914 request: Request<'_>,
1915 projection: Option<&TypeSchema>,
1916) -> Result<QueryPage<Vec<u8>>, Error> {
1917 db.schema.admits(entity)?;
1918 let plan = Plan::admit(
1919 entity,
1920 &request,
1921 db.schema.fingerprint(),
1922 db.incarnation,
1923 projection,
1924 PlanOutput::Rows,
1925 )?;
1926
1927 execute(&db.map, entity, &request, &plan, None)
1928}
1929
1930fn execute<M: Memory>(
1931 map: &Map<M>,
1932 entity: &EntitySchema,
1933 request: &Request<'_>,
1934 plan: &Plan<'_>,
1935 mut aggregate: Option<aggregate::Accumulator<'_>>,
1936) -> Result<QueryPage<Vec<u8>>, Error> {
1937 execute_inner(
1938 map,
1939 entity,
1940 request,
1941 plan,
1942 range::bounds(entity, request, plan)?,
1943 aggregate.as_mut(),
1944 None,
1945 )
1946}
1947
1948const STEP_INPUT_BYTES: usize = 64 * 1024;
1951const fn candidate_byte_limit(row_bytes: usize) -> usize {
1952 row_bytes + 2 * crate::MAX_INDEX_KEY_BYTES
1953}
1954
1955fn execute_inner<M: Memory>(
1956 map: &Map<M>,
1957 entity: &EntitySchema,
1958 request: &Request<'_>,
1959 plan: &Plan<'_>,
1960 bounds: Option<range::Bounds>,
1961 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1962 mut input_bytes: Option<&mut usize>,
1963) -> Result<QueryPage<Vec<u8>>, Error> {
1964 let mut page = QueryPage {
1965 rows: Vec::new(),
1966 next: None,
1967 examined: 0,
1968 fetched: 0,
1969 output_bytes: 0,
1970 };
1971 let Some(bounds) = bounds else {
1972 return Ok(page);
1973 };
1974 let terminal = range::terminal_key(&bounds, plan.descending);
1975 let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
1976 let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
1977 Some(distinct::Collection::new(
1978 plan.projection.ok_or(Error::InvalidQuery)?,
1979 key_fields,
1980 ))
1981 } else {
1982 None
1983 };
1984 let mut sorted = plan
1985 .sort
1986 .as_ref()
1987 .map(|_| sort::Collection::new(request, plan.distinct));
1988 let mut component = Vec::new();
1989 let mut right_component = Vec::new();
1990 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
1992 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1993 } else {
1994 None
1995 };
1996 let candidate_bytes = candidate_byte_limit(entity.max_row_bytes);
1997 let primary_type = entity.fields[plan.primary].value;
1998 let needs_spans = plan.index.is_some()
1999 || plan.span_fields != 0
2000 || match &aggregate {
2001 Some(accumulator) => accumulator.needs_spans(),
2002 None => plan.projection.is_some(),
2003 };
2004 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
2006 while let Some(entry) = if plan.descending {
2007 entries.next_back()
2008 } else {
2009 entries.next()
2010 } {
2011 if request.work == 0 {
2015 return Err(Error::Limit);
2016 }
2017 page.examined += 1;
2018 let stored_key = entry.key();
2019 let mut read_bytes = stored_key.len();
2020 let (owner, bytes) = if plan.index.is_some() {
2021 let owner_bytes = entry.value();
2022 read_bytes += owner_bytes.len();
2023 let owner = RowKey::decode(&owner_bytes, primary_type)?;
2024 let bytes = map.get(&row_key(entity.id, owner)).ok_or(Error::Corrupt)?;
2025
2026 (owner, bytes)
2027 } else {
2028 (
2029 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
2030 entry.value(),
2031 )
2032 };
2033 if let Some(used) = input_bytes.as_deref_mut() {
2034 read_bytes += bytes.len();
2035 if read_bytes > candidate_bytes {
2036 return Err(Error::Corrupt);
2037 }
2038 *used += read_bytes;
2039 }
2040 page.fetched += 1;
2041 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
2042 entity.inspect_fields(
2043 &bytes,
2044 plan.selected,
2045 &mut values,
2046 needs_spans.then_some(&mut spans),
2047 )?;
2048 if RowKey::from_index(values[plan.primary])? != owner {
2049 return Err(Error::Corrupt);
2050 }
2051 if plan.index.is_some() {
2052 validate_index_entry(
2053 entity,
2054 &entity.row_info(&values, &bytes, &spans)?,
2055 owner,
2056 stored_key,
2057 )?;
2058 }
2059 let read = |position: usize, member: Option<crate::member::RecordMember>| {
2060 if let Some(member) = member {
2061 let (start, end) = spans[position];
2062 member.read(
2063 &bytes[usize::from(start)..usize::from(end)],
2064 entity.fields[position].optional,
2065 )
2066 } else {
2067 Ok(values[position])
2068 }
2069 };
2070 let mut accepts = |term: &Term, supplied: &QueryOperand<'_>| -> Result<bool, Error> {
2071 let mut value = values[term.position];
2072 component.clear();
2073 let (operand, optional) = match &term.operand {
2074 TermOperand::Nested {
2075 member,
2076 literal,
2077 absent,
2078 } => {
2079 value = read(term.position, Some(*member))?;
2080 if *absent {
2081 return Ok(term.comparison.accepts_absent(value == IndexValue::Absent));
2082 }
2083 (Some(literal.as_slice()), false)
2084 }
2085 TermOperand::Literal { absent: true, .. } => {
2086 let absent = if plan.span_fields & (1 << term.position) != 0 {
2087 bytes[usize::from(spans[term.position].0)] == 0
2088 } else {
2089 value == IndexValue::Absent
2090 };
2091
2092 return Ok(term.comparison.accepts_absent(absent));
2093 }
2094 TermOperand::Member { item, needle } => {
2095 let needle = match (needle, supplied) {
2096 (MemberNeedle::Literal(_), QueryOperand::Literal(value)) => *value,
2097 (MemberNeedle::Field(right, member), QueryOperand::Field(_)) => {
2098 read(*right, *member)?
2099 }
2100 _ => return Err(Error::Corrupt),
2101 };
2102 if needle == IndexValue::Absent {
2103 return Ok(false);
2104 }
2105 let (start, end) = spans[term.position];
2106
2107 return contains_member(
2108 &bytes[usize::from(start)..usize::from(end)],
2109 entity.fields[term.position].optional,
2110 *item,
2111 needle,
2112 );
2113 }
2114 TermOperand::Length { member, threshold } => {
2115 let (start, end) = spans[term.position];
2116 let span = &bytes[usize::from(start)..usize::from(end)];
2117 let optional = entity.fields[term.position].optional;
2118 let actual = if let Some(member) = member {
2119 match member.read(span, optional)? {
2120 IndexValue::Absent => None,
2121 value => Some(scalar_bytes(value).ok_or(Error::Corrupt)?.len() as u32),
2122 }
2123 } else {
2124 crate::codec::validated_length(span, optional)
2125 };
2126
2127 return Ok(term.comparison.accepts_length(actual, *threshold));
2128 }
2129 TermOperand::Literal {
2130 bytes,
2131 absent: false,
2132 } => (
2133 Some(bytes.as_slice()),
2134 entity.fields[term.position].optional,
2135 ),
2136 TermOperand::Field {
2137 right,
2138 left_member,
2139 right_member,
2140 } => {
2141 value = read(term.position, *left_member)?;
2142 let rhs = read(*right, *right_member)?;
2143 if value == IndexValue::Absent || rhs == IndexValue::Absent {
2144 return Ok(term.comparison.accepts_absent(value == rhs));
2145 }
2146 if let Some(matches) = term.comparison.accepts_values(value, rhs) {
2147 return Ok(matches);
2148 }
2149 right_component.clear();
2150 rhs.append_component(false, &mut right_component);
2151
2152 (Some(right_component.as_slice()), false)
2153 }
2154 };
2155 if let QueryOperand::Literal(right) = supplied
2156 && let Some(matches) = term.comparison.accepts_values(value, *right)
2157 {
2158 return Ok(matches);
2159 }
2160 value.append_component(optional, &mut component);
2161
2162 Ok(term.comparison.accepts(
2163 (value != IndexValue::Absent).then_some(component.as_slice()),
2164 operand,
2165 optional,
2166 ))
2167 };
2168 let matches = 'matches: {
2169 let mut clause_matches = false;
2170 for (term, predicate) in plan.terms.iter().zip(&request.predicates) {
2171 clause_matches = clause_matches || accepts(term, &predicate.operand)?;
2172 if !term.or_next {
2173 if !clause_matches {
2174 break 'matches false;
2175 }
2176 clause_matches = false;
2177 }
2178 }
2179
2180 true
2181 };
2182 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
2183 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2184 if matches && let Some(accumulator) = aggregate.as_mut() {
2185 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2186 if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
2187 return Ok(page);
2189 }
2190 } else if matches && let Some(collection) = collected.as_mut() {
2191 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2192 if request.single_result_probe && collection.rows.len() == request.rows {
2195 break;
2196 }
2197 } else if matches && let Some(collection) = sorted.as_mut() {
2198 collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2199 } else if matches && !duplicate {
2200 let size = plan
2201 .projection
2202 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2203 if size > request.bytes {
2204 return Err(Error::RowTooLarge);
2205 }
2206 if size > request.bytes - page.output_bytes {
2207 page.next = Some(plan.cursor(stored_key, Resume::Retry));
2208
2209 return Ok(page);
2210 }
2211 page.output_bytes += size;
2212 if let Some(mask) = plan.projection {
2213 page.rows.push(copy_projection(&bytes, &spans, mask, size));
2214 } else {
2215 page.rows.push(bytes);
2216 }
2217 if plan.distinct == distinct::Strategy::FirstMatch {
2218 return Ok(page);
2219 }
2220 if let Some(boundary) = boundary {
2221 previous = Some(boundary.to_vec());
2222 }
2223 }
2224 if page.rows.len() == request.rows
2225 || page.examined == request.work
2226 || input_bytes
2227 .as_deref()
2228 .is_some_and(|used| *used > STEP_INPUT_BYTES - candidate_bytes)
2229 {
2230 if terminal == Some(stored_key) {
2231 break;
2232 }
2233 if (aggregate.is_some() && input_bytes.is_none())
2234 || collected.is_some()
2235 || sorted.is_some()
2236 {
2237 return Err(Error::Limit);
2240 }
2241 let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
2242 Resume::AfterUnemittedClass
2243 } else {
2244 Resume::After
2245 };
2246 page.next = Some(plan.cursor(stored_key, resume));
2247
2248 return Ok(page);
2249 }
2250 }
2251 if let Some(collection) = collected {
2252 page.output_bytes = collection.output_bytes;
2253 page.rows = collection.rows;
2254 }
2255 if let Some(collection) = sorted {
2256 collection.finish(request.bytes, &mut page)?;
2257 }
2258
2259 Ok(page)
2260}