1mod aggregate;
4mod distinct;
5mod order;
6mod probe;
7mod range;
8mod select;
9mod sort;
10pub use select::{Column, SelectColumns, SelectedQuery, Selection};
11
12pub use aggregate::{
13 Aggregate, GroupCount, GroupOrder, GroupSummaries, GroupSummary, GroupSummaryPage, GroupValue,
14 SummaryMeasure,
15 jobs::{AggregateJobs, GroupCursor, GroupPage, JobHandle, JobOutcome, JobStep},
16};
17
18use super::{
19 Database, ENTITY_PREFIX_BYTES, INDEX_PREFIX_BYTES, Map, prefix, read_index_owner,
20 validate_index_entry,
21};
22use crate::{
23 Entity, EntitySchema, Error, FieldType, IndexSchema, IndexValue, TypeBody, TypeSchema, Value,
24 codec::Decoder, key, named_schema::TypeGraph, primary::RowKey,
25};
26use ic_storage::Memory;
27use sha2::{Digest, Sha256};
28use std::{
29 cell::{Ref, RefCell},
30 marker::PhantomData,
31 ops::Deref,
32 rc::Rc,
33};
34
35const MAX_TERMS: usize = 8;
36const MAX_WORK: usize = 512;
37const MAX_OUTPUT: usize = 128 * 1024;
38const MAX_COMPARISON_KEY: usize = 4096;
39const MAX_DISTINCT_VALUES: usize = 32;
40const MAX_STATE_BYTES: usize = 128 * 1024;
41
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub enum SortDirection {
45 Ascending,
47 Descending,
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53#[repr(u8)]
54pub enum Comparison {
55 Eq = 0,
57 Ne = 1,
59 Lt = 2,
61 Le = 3,
63 Gt = 4,
65 Ge = 5,
67 StartsWith = 6,
71 EndsWith = 7,
74 Contains = 8,
78}
79
80impl Comparison {
81 fn supports_record_member(self) -> bool {
82 self.is_relational() || matches!(self, Self::StartsWith | Self::EndsWith)
83 }
84
85 fn is_relational(self) -> bool {
86 matches!(
87 self,
88 Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge
89 )
90 }
91
92 fn supports_scalar(self, field: FieldType) -> bool {
93 self.is_relational()
94 || matches!(
95 key::operand_type(field),
96 FieldType::Text { .. } | FieldType::Blob { .. }
97 )
98 }
99
100 fn admit(self, field: FieldType, optional: bool, value: IndexValue<'_>) -> Result<(), Error> {
101 value.admit(field, optional)?;
102 if !self.supports_scalar(field) {
103 return Err(Error::InvalidQuery);
104 }
105 if value == IndexValue::Absent && !matches!(self, Self::Eq | Self::Ne) {
106 return Err(Error::InvalidOperand);
107 }
108
109 Ok(())
110 }
111
112 fn accepts(self, actual: Option<&[u8]>, operand: Option<&[u8]>, optional: bool) -> bool {
113 if actual.is_none() {
114 return self.accepts_absent(operand.is_none());
115 }
116
117 match self {
118 Self::Eq => actual == operand,
119 Self::Ne => actual != operand,
120 Self::StartsWith | Self::EndsWith | Self::Contains => {
121 fn content(key: &[u8], optional: bool) -> Option<&[u8]> {
124 crate::key::bytes_prefix(key.get(usize::from(optional)..)?)
125 }
126
127 actual
128 .and_then(|key| content(key, optional))
129 .zip(operand.and_then(|key| content(key, optional)))
130 .is_some_and(|(actual, operand)| match self {
131 Self::StartsWith => actual.starts_with(operand),
134 Self::EndsWith => actual
138 .strip_suffix(operand)
139 .is_some_and(|prefix| prefix.last() != Some(&0)),
140 _ => contains_component(actual, operand),
141 })
142 }
143 _ if actual.is_none() || operand.is_none() => false,
144 Self::Lt => actual < operand,
145 Self::Le => actual <= operand,
146 Self::Gt => actual > operand,
147 Self::Ge => actual >= operand,
148 }
149 }
150
151 fn accepts_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
153 match self {
154 Self::Eq => Some(equal_values(left, right)),
155 Self::Ne => Some(!equal_values(left, right)),
156 _ => Some(self.accepts_bytes(scalar_bytes(left)?, scalar_bytes(right)?)),
157 }
158 }
159
160 fn accepts_fixed_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
162 if left == IndexValue::Absent || right == IndexValue::Absent {
163 return Some(self.accepts_absent(left == right));
164 }
165 if let Some(result) = self.accepts_values(left, right) {
166 return Some(result);
167 }
168 match self {
169 Comparison::Lt | Comparison::Le | Comparison::Gt | Comparison::Ge => {
170 let mut encoded = Vec::new();
172 left.append_component(false, &mut encoded);
173 let split = encoded.len();
174 right.append_component(false, &mut encoded);
175 let (left, right) = encoded.split_at(split);
176
177 Some(self.accepts(Some(left), Some(right), false))
178 }
179 _ => None,
180 }
181 }
182
183 fn accepts_bytes(self, actual: &[u8], operand: &[u8]) -> bool {
185 match self {
186 Self::StartsWith => actual.starts_with(operand),
187 Self::EndsWith => actual.ends_with(operand),
188 Self::Contains => memchr::memmem::find(actual, operand).is_some(),
189 _ => self.accepts(Some(actual), Some(operand), false),
190 }
191 }
192
193 fn accepts_length(self, actual: Option<u32>, threshold: u32) -> bool {
194 let encoded = actual.map(u32::to_be_bytes);
195
196 self.accepts(
197 encoded.as_ref().map(|v| v.as_slice()),
198 Some(&threshold.to_be_bytes()),
199 false,
200 )
201 }
202
203 fn empty_length_value(self, threshold: u32, field: FieldType) -> Option<IndexValue<'static>> {
205 if !matches!((self, threshold), (Self::Eq | Self::Le, 0) | (Self::Lt, 1)) {
206 return None;
207 }
208 match key::operand_type(field) {
209 FieldType::Text { .. } => Some(IndexValue::Text("")),
210 FieldType::Blob { .. } => Some(IndexValue::Blob(&[])),
211 _ => None,
212 }
213 }
214
215 fn uniform_length_result(self, min: u32, max: u32, n: u32) -> Option<bool> {
217 match self {
218 Self::Eq | Self::Ne if min == max || n < min || n > max => {
219 Some(self.accepts_length(Some(min), n))
220 }
221 Self::Lt | Self::Ge if max < n || min >= n => Some(self.accepts_length(Some(min), n)),
222 Self::Le | Self::Gt if max <= n || min > n => Some(self.accepts_length(Some(min), n)),
223 _ => None,
224 }
225 }
226
227 fn accepts_absent(self, other_absent: bool) -> bool {
230 match self {
231 Self::Eq => other_absent,
232 Self::Ne => !other_absent,
233 _ => false,
234 }
235 }
236}
237
238fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
240 let Some(start) = memchr::memmem::find(actual, needle) else {
241 return false;
242 };
243 if start == 0 || actual[start - 1] != 0 {
244 return true;
245 }
246 fn raw(content: &[u8]) -> Vec<u8> {
250 let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
251 let mut encoded = content.iter();
252 while let Some(&byte) = encoded.next() {
253 bytes.push(byte);
254 if byte == 0 {
255 encoded.next();
256 }
257 }
258
259 bytes
260 }
261
262 memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
263}
264
265#[derive(Clone, Debug, PartialEq, Eq)]
269pub struct QueryCursor {
270 binding: [u8; 32],
271 position: Vec<u8>,
272 resume: Resume,
273}
274
275#[derive(Clone, Copy, Debug, PartialEq, Eq)]
276enum Resume {
277 After = 0,
278 Retry = 1,
279 AfterUnemittedClass = 2,
280}
281impl QueryCursor {
282 pub(super) const MAX_ENCODED_BYTES: usize = 34 + crate::MAX_INDEX_KEY_BYTES;
283
284 #[must_use]
286 pub fn to_bytes(&self) -> Vec<u8> {
287 let mut bytes = vec![1, self.resume as u8];
288 bytes.extend(self.binding);
289 bytes.extend(&self.position);
290
291 bytes
292 }
293
294 pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
298 if !(35..=Self::MAX_ENCODED_BYTES).contains(&bytes.len()) || bytes[0] != 1 {
299 return Err(Error::InvalidCursor);
300 }
301
302 Ok(Self {
303 binding: bytes[2..34].try_into().map_err(|_| Error::InvalidCursor)?,
304 position: bytes[34..].to_vec(),
305 resume: match bytes[1] {
306 0 => Resume::After,
307 1 => Resume::Retry,
308 2 => Resume::AfterUnemittedClass,
309 _ => return Err(Error::InvalidCursor),
310 },
311 })
312 }
313}
314
315impl serde::Serialize for QueryCursor {
316 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
317 self.to_bytes().serialize(serializer)
318 }
319}
320
321impl<'de> serde::Deserialize<'de> for QueryCursor {
322 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
323 struct Frame;
324
325 impl<'de> serde::de::Visitor<'de> for Frame {
326 type Value = QueryCursor;
327
328 fn expecting(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
329 fmt.write_str("a bounded IC DB query cursor frame")
330 }
331
332 fn visit_seq<A: serde::de::SeqAccess<'de>>(
333 self,
334 mut seq: A,
335 ) -> Result<QueryCursor, A::Error> {
336 let size = seq.size_hint().unwrap_or(0);
337 if size > QueryCursor::MAX_ENCODED_BYTES {
338 return Err(serde::de::Error::custom(Error::InvalidCursor));
339 }
340 let mut frame = Vec::with_capacity(size);
341 while let Some(byte) = seq.next_element()? {
342 if frame.len() == QueryCursor::MAX_ENCODED_BYTES {
343 return Err(serde::de::Error::custom(Error::InvalidCursor));
344 }
345 frame.push(byte);
346 }
347 QueryCursor::from_bytes(&frame).map_err(serde::de::Error::custom)
348 }
349 }
350
351 deserializer.deserialize_seq(Frame)
352 }
353}
354
355#[derive(Debug)]
358pub struct QueryPage<T> {
359 pub rows: Vec<T>,
361 pub next: Option<QueryCursor>,
363 pub examined: usize,
365 pub fetched: usize,
367 pub output_bytes: usize,
369}
370
371impl QueryPage<Vec<u8>> {
372 #[inline(never)]
373 pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
374 Ok(QueryPage {
375 rows: self
376 .rows
377 .iter()
378 .map(|bytes| E::decode(bytes))
379 .collect::<Result<_, _>>()?,
380 next: self.next,
381 examined: self.examined,
382 fetched: self.fetched,
383 output_bytes: self.output_bytes,
384 })
385 }
386
387 #[inline(never)]
388 fn decode_with<R>(
389 self,
390 decode: impl Fn(&mut Decoder<'_>) -> Result<R, Error>,
391 ) -> Result<QueryPage<R>, Error> {
392 Ok(QueryPage {
393 rows: self
394 .rows
395 .iter()
396 .map(|bytes| {
397 let mut reader = Decoder::new(bytes)?;
398 let row = decode(&mut reader)?;
400 reader.finish()?;
401
402 Ok(row)
403 })
404 .collect::<Result<_, Error>>()?,
405 next: self.next,
406 examined: self.examined,
407 fetched: self.fetched,
408 output_bytes: self.output_bytes,
409 })
410 }
411}
412
413#[derive(Clone, Copy, Debug, PartialEq, Eq)]
415pub enum QueryOperand<'a> {
416 Literal(IndexValue<'a>),
418 Length(u32),
420 Field(&'a str),
422}
423
424struct Predicate<'a> {
425 field: &'a str,
426 comparison: Comparison,
427 operand: QueryOperand<'a>,
428 or_next: bool,
430}
431
432impl<'a> Predicate<'a> {
433 fn compared_field(&self, name: &str) -> Option<&'a str> {
435 let QueryOperand::Field(right) = self.operand else {
436 return None;
437 };
438 if self.field == name {
439 Some(right)
440 } else if right == name {
441 Some(self.field)
442 } else {
443 None
444 }
445 }
446
447 fn at_extreme(&self, entity: &EntitySchema, value: IndexValue<'_>, upper: bool) -> bool {
449 match value {
450 IndexValue::Bool(b) => b == upper,
451 IndexValue::UnitEnum { ordinal, .. } => entity
452 .index_field(self.field)
453 .is_some_and(|field| key::is_fixed_extreme(field.value, &[ordinal], upper)),
454 IndexValue::Text("") | IndexValue::Blob([]) => !upper,
455 _ => value.is_integer_extreme(upper),
456 }
457 }
458
459 fn fixed_equality(&self, entity: &EntitySchema) -> Option<(&'a str, IndexValue<'a>)> {
461 if let QueryOperand::Length(n) = self.operand {
462 let empty = self
463 .comparison
464 .empty_length_value(n, entity.index_field(self.field)?.value)?;
465 return Some((self.field, empty));
466 }
467 let QueryOperand::Literal(value) = self.operand else {
468 return None;
469 };
470 let fixed = match (self.comparison, value) {
472 (Comparison::Eq, _) => value,
473 (Comparison::Ne, IndexValue::Bool(excluded))
474 if entity.field_is_required(self.field) =>
475 {
476 IndexValue::Bool(!excluded)
477 }
478 (cmp @ (Comparison::Ge | Comparison::Le), _)
479 if self.at_extreme(entity, value, cmp == Comparison::Ge) =>
480 {
481 value
482 }
483 (Comparison::Gt, IndexValue::Bool(false)) => IndexValue::Bool(true),
484 (Comparison::Lt, IndexValue::Bool(true)) => IndexValue::Bool(false),
485 _ => return None,
486 };
487 Some((self.field, fixed))
488 }
489
490 fn tests_presence(&self, entity: &EntitySchema, operand: &TermOperand) -> bool {
492 match (self.comparison, self.operand) {
493 (Comparison::Ne, QueryOperand::Literal(IndexValue::Absent)) => true,
494 (cmp @ (Comparison::Le | Comparison::Ge), QueryOperand::Literal(value)) => {
495 self.at_extreme(entity, value, cmp == Comparison::Le)
496 }
497 (_, QueryOperand::Length(_)) => {
498 self.present_length_result(entity) == Some(true)
499 && self.comparison != Comparison::Ne
500 }
501 (
502 Comparison::Le
503 | Comparison::Ge
504 | Comparison::StartsWith
505 | Comparison::EndsWith
506 | Comparison::Contains,
507 QueryOperand::Field(right),
508 ) => right == self.field,
509 (
510 Comparison::StartsWith | Comparison::EndsWith | Comparison::Contains,
511 QueryOperand::Literal(needle),
512 ) => {
513 !matches!(operand, TermOperand::Member { .. })
515 && scalar_bytes(needle).is_some_and(<[u8]>::is_empty)
516 }
517 _ => false,
518 }
519 }
520
521 fn present_length_result(&self, entity: &EntitySchema) -> Option<bool> {
523 let QueryOperand::Length(n) = self.operand else {
524 return None;
525 };
526 let max = length_limit(entity.index_field(self.field)?.value)?;
527 self.comparison.uniform_length_result(0, max, n)
528 }
529
530 fn constant_comparison(&self, entity: &EntitySchema) -> Option<bool> {
531 if let QueryOperand::Literal(value) = self.operand {
532 return match (self.comparison, value) {
534 (cmp @ (Comparison::Lt | Comparison::Gt), value)
535 if self.at_extreme(entity, value, cmp == Comparison::Gt) =>
536 {
537 Some(false)
538 }
539 _ => None,
540 };
541 }
542 if matches!(self.operand, QueryOperand::Length(_)) {
543 let result = self.present_length_result(entity)?;
544 return (result == self.comparison.accepts_absent(false)
545 || entity.field_is_required(self.field))
546 .then_some(result);
547 }
548 if !matches!(self.operand, QueryOperand::Field(right) if right == self.field) {
549 return None;
550 }
551 match self.comparison {
552 Comparison::Eq => Some(true),
553 Comparison::Ne | Comparison::Lt | Comparison::Gt => Some(false),
554 _ => None,
555 }
556 }
557}
558
559#[derive(Clone, Copy, PartialEq, Eq)]
560enum SingleResult {
561 First,
562 Only,
563}
564
565struct Request<'a> {
566 groups: aggregate::GroupRequest<'a>,
567 predicates: Vec<Predicate<'a>>,
568 index: Option<(&'a str, Vec<IndexValue<'a>>)>,
569 order: Option<Vec<&'a str>>,
570 order_descending: u8,
571 descending: bool,
572 distinct: bool,
573 single_result_probe: Option<SingleResult>,
574 rows: usize,
575 work: usize,
576 bytes: usize,
577 cursor: Option<&'a QueryCursor>,
578 over_limit: bool,
579}
580
581impl Default for Request<'_> {
582 fn default() -> Self {
583 Self {
584 groups: aggregate::GroupRequest::default(),
585 predicates: Vec::new(),
586 index: None,
587 order: None,
588 order_descending: 0,
589 descending: false,
590 distinct: false,
591 single_result_probe: None,
592 rows: 32,
593 work: 128,
594 bytes: MAX_OUTPUT,
595 cursor: None,
596 over_limit: false,
597 }
598 }
599}
600
601impl<'a> Request<'a> {
604 fn check_result_count(&self, count: usize) -> Result<(), Error> {
607 if self.single_result_probe == Some(SingleResult::Only) && count > 1 {
608 return Err(Error::MultipleMatches);
609 }
610 Ok(())
611 }
612
613 fn fixed_equalities<'r>(
615 &'r self,
616 entity: &'r EntitySchema,
617 ) -> impl Iterator<Item = (&'a str, IndexValue<'a>)> + 'r {
618 self.clauses().filter_map(move |clause| {
619 let (predicate, rest) = clause.split_first()?;
620 if !rest.is_empty() {
621 let mut candidate = predicate.fixed_equality(entity)?;
622 for alternative in rest {
623 let other = alternative.fixed_equality(entity)?;
624 if candidate.0 != other.0 {
625 return None;
626 }
627 if equal_values(candidate.1, other.1) {
628 continue;
629 }
630 if self.predicates.len() == clause.len() {
631 return None;
632 }
633 if self.excludes_literal(other.0, other.1) {
634 continue;
635 }
636 if !self.excludes_literal(candidate.0, candidate.1) {
637 return None;
638 }
639 candidate = other;
640 }
641 return Some(candidate);
644 }
645 if let Some(equality) = predicate.fixed_equality(entity) {
646 return Some(equality);
647 }
648 let QueryOperand::Literal(value) = predicate.operand else {
652 return None;
653 };
654 let lower = match predicate.comparison {
655 Comparison::Ge => value,
656 Comparison::Gt if self.predicates.len() > 1 => value.discrete_successor()?,
657 _ => return None,
658 };
659 self.clauses()
660 .any(|clause| {
661 let [upper] = clause else { return false };
662 if upper.field != predicate.field {
663 return false;
664 }
665 match (upper.comparison, upper.operand) {
666 (Comparison::Le, QueryOperand::Literal(value)) => {
667 equal_values(lower, value)
668 }
669 (Comparison::Lt, QueryOperand::Literal(value)) => {
670 consecutive_values(lower, value)
671 }
672 _ => false,
673 }
674 })
675 .then_some((predicate.field, lower))
676 })
677 }
678
679 fn excludes_literal(&self, field: &str, value: IndexValue<'_>) -> bool {
680 self.clauses().any(|clause| {
683 clause.iter().all(|predicate| {
684 if predicate.field != field {
685 return false;
686 }
687 let QueryOperand::Literal(literal) = predicate.operand else {
688 return false;
689 };
690 match predicate.comparison {
691 Comparison::Eq
692 | Comparison::Ne
693 | Comparison::Lt
694 | Comparison::Le
695 | Comparison::Gt
696 | Comparison::Ge => {
697 predicate.comparison.accepts_fixed_values(value, literal) == Some(false)
698 }
699 _ => false,
700 }
701 })
702 })
703 }
704
705 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
706 self.predicates.split_inclusive(|p| !p.or_next)
707 }
708
709 #[inline(never)]
710 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
711 if self.predicates.len() == MAX_TERMS {
712 self.over_limit = true;
713 } else {
714 self.predicates.push(Predicate {
715 field,
716 comparison,
717 operand,
718 or_next: false,
719 });
720 }
721 }
722
723 #[inline(never)]
724 fn or_clause(
725 &mut self,
726 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
727 ) {
728 let count = alternatives.len();
729
730 if count == 0 || count > MAX_TERMS - self.predicates.len() {
731 self.over_limit = true;
732 } else {
733 self.predicates.extend(alternatives.enumerate().map(
734 |(i, (field, comparison, operand))| Predicate {
735 field,
736 comparison,
737 operand,
738 or_next: i + 1 < count,
739 },
740 ));
741 }
742 }
743
744 #[inline(never)]
745 fn filter_not_in(
746 &mut self,
747 field: &'a str,
748 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
749 ) {
750 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
751 self.over_limit = true;
752
753 return;
754 }
755 for value in values {
756 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
757 }
758 }
759
760 #[inline(never)]
761 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
762 if values.len() > 4 {
763 self.over_limit = true;
764 } else {
765 self.index = Some((name, values.to_vec()));
766 }
767 }
768
769 #[inline(never)]
770 fn order_by(&mut self, fields: &[&'a str]) {
771 self.order_descending = 0;
772
773 if fields.len() > 4 {
774 self.over_limit = true;
775 } else {
776 self.order = Some(fields.to_vec());
777 }
778 }
779
780 #[inline(never)]
781 fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
782 if fields.len() > 4 {
783 self.over_limit = true;
784
785 return;
786 }
787 self.order = Some(Vec::with_capacity(fields.len()));
788 self.order_descending = 0;
789 for &(field, direction) in fields {
790 self.append_order(field, direction);
791 }
792 }
793
794 fn append_order(&mut self, field: &'a str, direction: SortDirection) {
795 let fields = self.order.get_or_insert_with(Vec::new);
796 if fields.len() == 4 {
797 self.over_limit = true;
798
799 return;
800 }
801 if direction == SortDirection::Descending {
802 self.order_descending |= 1 << fields.len();
803 }
804 fields.push(field);
805 }
806
807 fn primary_descending(&self, entity: &EntitySchema) -> bool {
808 self.order_descending != 0
809 && self.order.as_ref().is_some_and(|fields| {
810 fields.last() == Some(&entity.primary_key)
811 && self.order_descending & (1 << (fields.len() - 1)) != 0
812 })
813 }
814}
815
816pub(super) fn source_page<M: Memory>(
818 map: &Map<M>,
819 entity: &EntitySchema,
820 binding: [u8; 32],
821 incarnation: [u8; 16],
822 cursor: Option<&QueryCursor>,
823 rows: usize,
824 bytes: usize,
825) -> Result<QueryPage<Vec<u8>>, Error> {
826 let request = Request {
827 rows,
828 work: rows,
829 bytes,
830 cursor,
831 ..Request::default()
832 };
833 let plan = Plan::admit(
834 entity,
835 &request,
836 binding,
837 incarnation,
838 None,
839 PlanOutput::Rows,
840 )?;
841
842 execute(map, entity, &request, &plan, None)
843}
844
845enum QuerySource<'a, M: Memory> {
846 Direct(&'a Database<M>),
847 Session(Rc<RefCell<Database<M>>>),
848}
849
850enum QueryRead<'a, M: Memory> {
851 Direct(&'a Database<M>),
852 Session(Ref<'a, Database<M>>),
853}
854
855impl<M: Memory> Deref for QueryRead<'_, M> {
856 type Target = Database<M>;
857
858 fn deref(&self) -> &Self::Target {
859 match self {
860 Self::Direct(db) => db,
861 Self::Session(db) => db,
862 }
863 }
864}
865
866impl<M: Memory> QuerySource<'_, M> {
867 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
868 match self {
869 Self::Direct(db) => Ok(QueryRead::Direct(db)),
870 Self::Session(db) => db
871 .try_borrow()
872 .map(QueryRead::Session)
873 .map_err(|_| Error::BorrowConflict),
874 }
875 }
876}
877
878pub struct Query<'a, E, M: Memory> {
882 db: QuerySource<'a, M>,
883 request: Request<'a>,
884 entity: PhantomData<E>,
885}
886impl<M: Memory> Database<M> {
887 #[must_use]
889 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
890 Query {
891 db: QuerySource::Direct(self),
892 entity: PhantomData,
893 request: Request::default(),
894 }
895 }
896}
897impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
898 pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
899 Self {
900 db: QuerySource::Session(db),
901 request: Request::default(),
902 entity: PhantomData,
903 }
904 }
905
906 #[must_use]
920 pub fn distinct(mut self) -> Self {
921 self.request.distinct = true;
922
923 self
924 }
925
926 #[must_use]
939 pub fn filter(
940 mut self,
941 field: &'a str,
942 comparison: Comparison,
943 value: impl Into<IndexValue<'a>>,
944 ) -> Self {
945 self.request
946 .filter(field, comparison, QueryOperand::Literal(value.into()));
947
948 self
949 }
950
951 #[must_use]
953 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
954 self.filter(field, Comparison::Eq, value)
955 }
956
957 #[must_use]
959 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
960 self.filter(field, Comparison::Ne, value)
961 }
962
963 #[must_use]
965 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
966 self.filter(field, Comparison::Lt, value)
967 }
968
969 #[must_use]
971 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
972 self.filter(field, Comparison::Le, value)
973 }
974
975 #[must_use]
977 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
978 self.filter(field, Comparison::Gt, value)
979 }
980
981 #[must_use]
983 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
984 self.filter(field, Comparison::Ge, value)
985 }
986
987 #[must_use]
995 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
996 self.request
997 .filter(left, comparison, QueryOperand::Field(right));
998
999 self
1000 }
1001
1002 #[must_use]
1007 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
1008 self.request
1009 .filter(field, comparison, QueryOperand::Length(length));
1010
1011 self
1012 }
1013
1014 #[must_use]
1017 pub fn filter_present(self, field: &'a str) -> Self {
1018 self.filter(field, Comparison::Ne, IndexValue::Absent)
1019 }
1020
1021 #[must_use]
1024 pub fn filter_absent(self, field: &'a str) -> Self {
1025 self.filter(field, Comparison::Eq, IndexValue::Absent)
1026 }
1027
1028 #[must_use]
1035 pub fn filter_between(
1036 self,
1037 field: &'a str,
1038 lower: impl Into<IndexValue<'a>>,
1039 upper: impl Into<IndexValue<'a>>,
1040 ) -> Self {
1041 self.filter(field, Comparison::Ge, lower)
1042 .filter(field, Comparison::Le, upper)
1043 }
1044
1045 #[must_use]
1053 pub fn filter_not_between(
1054 self,
1055 field: &'a str,
1056 lower: impl Into<IndexValue<'a>>,
1057 upper: impl Into<IndexValue<'a>>,
1058 ) -> Self {
1059 self.filter_any(&[
1060 (field, Comparison::Lt, lower.into()),
1061 (field, Comparison::Gt, upper.into()),
1062 ])
1063 }
1064
1065 #[must_use]
1070 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1071 self.filter_fields(field, Comparison::Ge, lower)
1072 .filter_fields(field, Comparison::Le, upper)
1073 }
1074
1075 #[must_use]
1080 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1081 self.filter_any_operands(&[
1082 (field, Comparison::Lt, QueryOperand::Field(lower)),
1083 (field, Comparison::Gt, QueryOperand::Field(upper)),
1084 ])
1085 }
1086
1087 #[must_use]
1095 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
1096 self.request.or_clause(
1097 alternatives
1098 .iter()
1099 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
1100 );
1101
1102 self
1103 }
1104
1105 #[must_use]
1110 pub fn filter_any_operands(
1111 mut self,
1112 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
1113 ) -> Self {
1114 self.request.or_clause(alternatives.iter().copied());
1115
1116 self
1117 }
1118
1119 #[must_use]
1129 pub fn filter_in(
1130 mut self,
1131 field: &'a str,
1132 values: &[impl Copy + Into<IndexValue<'a>>],
1133 ) -> Self {
1134 self.request.or_clause(
1135 values
1136 .iter()
1137 .copied()
1138 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
1139 );
1140
1141 self
1142 }
1143
1144 #[must_use]
1152 pub fn filter_not_in(
1153 mut self,
1154 field: &'a str,
1155 values: &[impl Copy + Into<IndexValue<'a>>],
1156 ) -> Self {
1157 self.request
1158 .filter_not_in(field, values.iter().copied().map(Into::into));
1159
1160 self
1161 }
1162
1163 #[must_use]
1168 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
1169 self.request.using_index(name, values);
1170
1171 self
1172 }
1173
1174 #[must_use]
1177 pub fn order_asc(mut self, field: &'a str) -> Self {
1178 self.request.append_order(field, SortDirection::Ascending);
1179
1180 self
1181 }
1182
1183 #[must_use]
1186 pub fn order_desc(mut self, field: &'a str) -> Self {
1187 self.request.append_order(field, SortDirection::Descending);
1188
1189 self
1190 }
1191
1192 #[must_use]
1203 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
1204 self.request.order_by(fields);
1205
1206 self
1207 }
1208
1209 #[must_use]
1214 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
1215 self.request.order_by_each(fields);
1216
1217 self
1218 }
1219
1220 #[must_use]
1222 pub fn descending(mut self) -> Self {
1223 self.request.descending = true;
1224
1225 self
1226 }
1227
1228 #[must_use]
1235 pub fn limit(mut self, rows: usize) -> Self {
1236 self.request.rows = rows;
1237
1238 self
1239 }
1240
1241 #[must_use]
1243 pub fn work_limit(mut self, candidates: usize) -> Self {
1244 self.request.work = candidates;
1245
1246 self
1247 }
1248
1249 #[cfg(feature = "test-support")]
1251 #[doc(hidden)]
1252 #[must_use]
1253 pub fn test_output_limit(mut self, bytes: usize) -> Self {
1254 self.request.bytes = bytes;
1255
1256 self
1257 }
1258
1259 #[must_use]
1261 pub fn after(mut self, cursor: &'a QueryCursor) -> Self {
1262 self.request.cursor = Some(cursor);
1263
1264 self
1265 }
1266
1267 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
1274 observe!(query, { self.entity_page() })
1275 }
1276
1277 fn entity_page(self) -> Result<QueryPage<E>, Error> {
1278 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
1279 }
1280
1281 pub fn first(self) -> Result<Option<E>, Error> {
1287 self.first_with(Self::entity_page)
1288 }
1289
1290 pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
1294 self.first_with(Self::projected_page::<R>)
1295 }
1296
1297 fn first_with<R>(
1298 self,
1299 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1300 ) -> Result<Option<R>, Error> {
1301 observe!(query, { fetch(self.probe_matches(SingleResult::First)?) })
1302 .map(|mut page| page.rows.pop())
1303 }
1304
1305 pub fn try_one(self) -> Result<Option<E>, Error> {
1312 self.try_one_with(Self::entity_page)
1313 }
1314
1315 pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
1321 self.try_one_with(Self::projected_page::<R>)
1322 }
1323
1324 fn try_one_with<R>(
1325 self,
1326 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1327 ) -> Result<Option<R>, Error> {
1328 observe!(query, {
1329 if self.request.cursor.is_some() {
1330 return Err(Error::InvalidQuery);
1331 }
1332 fetch(self.probe_matches(SingleResult::Only)?)
1333 })
1334 .map(|mut page| page.rows.pop())
1335 }
1336
1337 fn probe_matches(mut self, probe: SingleResult) -> Result<Self, Error> {
1338 if !(1..=32).contains(&self.request.rows) {
1339 return Err(Error::Limit);
1340 }
1341
1342 self.request.single_result_probe = Some(probe);
1343
1344 Ok(self.limit(match probe {
1345 SingleResult::First => 1,
1346 SingleResult::Only => 2,
1347 }))
1348 }
1349
1350 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1360 observe!(query, { self.projected_page() })
1361 }
1362
1363 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1364 let raw = fetch_rows(
1365 &*self.db.read()?,
1366 E::SCHEMA,
1367 self.request,
1368 Some(Projection::Record(R::definition())),
1369 )?;
1370
1371 raw.decode_with(R::decode_from)
1372 }
1373}
1374
1375#[derive(Clone, Copy)]
1376enum Projection<'a> {
1377 Record(&'a TypeSchema),
1378 Columns(&'a [u8]),
1379}
1380
1381impl Projection<'_> {
1382 fn mask(self, entity: &EntitySchema) -> Result<u32, Error> {
1383 match self {
1384 Self::Record(record) => admit_projection(entity, record),
1385 Self::Columns(columns) => {
1386 let mut mask = 0;
1387 for &column in columns {
1388 if usize::from(column) >= entity.fields.len() || mask & (1 << column) != 0 {
1389 return Err(Error::InvalidQuery);
1390 }
1391 mask |= 1 << column;
1392 }
1393 Ok(mask)
1394 }
1395 }
1396 }
1397}
1398
1399fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u32, Error> {
1403 let TypeBody::Record(fields) = &output.body else {
1404 return Err(Error::InvalidQuery);
1405 };
1406 if fields.is_empty()
1407 || fields.len() > crate::schema::MAX_FIELDS
1408 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1409 {
1410 return Err(Error::InvalidQuery);
1411 }
1412 let mut source = TypeGraph::default();
1413 let mut target = TypeGraph::default();
1414 let mut mask = 0;
1415 for field in *fields {
1416 let position = entity
1417 .field_position(field.name)
1418 .ok_or(Error::InvalidQuery)?;
1419 let stored = &entity.fields[position];
1420 if stored.value != field.value || stored.optional != field.optional {
1421 return Err(Error::InvalidQuery);
1422 }
1423 source
1424 .include(stored.value)
1425 .map_err(|_| Error::InvalidQuery)?;
1426 target
1427 .include(field.value)
1428 .map_err(|_| Error::InvalidQuery)?;
1429 mask |= 1 << position;
1430 }
1431 if !source.contains(&target) {
1432 return Err(Error::InvalidQuery);
1433 }
1434
1435 Ok(mask)
1436}
1437
1438struct Term {
1439 tests_presence: bool,
1440 position: usize,
1441 comparison: Comparison,
1442 operand: TermOperand,
1443 or_next: bool,
1444}
1445
1446enum TermOperand {
1447 Literal {
1448 bytes: Vec<u8>,
1449 absent: bool,
1450 },
1451 Member {
1452 item: FieldType,
1453 needle: MemberNeedle,
1454 },
1455 Nested {
1456 member: crate::member::RecordMember,
1457 literal: Vec<u8>,
1458 absent: bool,
1459 },
1460 Field {
1461 right: usize,
1462 left_member: Option<crate::member::RecordMember>,
1463 right_member: Option<crate::member::RecordMember>,
1464 },
1465 Length {
1466 member: Option<crate::member::RecordMember>,
1467 threshold: u32,
1468 },
1469}
1470
1471enum MemberNeedle {
1472 Literal(Vec<u8>),
1473 Field(usize, Option<crate::member::RecordMember>),
1474}
1475
1476fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1479 match value {
1480 IndexValue::Text(text) => Some(text.as_bytes()),
1481 IndexValue::Blob(bytes) => Some(bytes),
1482 _ => None,
1483 }
1484}
1485
1486fn consecutive_values(low: IndexValue<'_>, high: IndexValue<'_>) -> bool {
1487 low.discrete_successor()
1488 .is_some_and(|next| equal_values(next, high))
1489}
1490
1491fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1492 match (left, right) {
1494 (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1495 a == b
1496 }
1497 _ => left == right,
1498 }
1499}
1500
1501fn length_limit(field: FieldType) -> Option<u32> {
1502 match key::operand_type(field) {
1503 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1504 FieldType::List { max_items, .. } => Some(max_items),
1505 FieldType::Named(link) => match (link.definition)().body {
1506 TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1507 _ => None,
1508 },
1509 _ => None,
1510 }
1511}
1512
1513fn member_type(field: FieldType) -> Option<FieldType> {
1514 match key::operand_type(field) {
1515 FieldType::List { item, .. } => Some(*item),
1516 FieldType::Named(link) => match (link.definition)().body {
1517 TypeBody::Set { item, .. } => Some(item),
1518 _ => None,
1519 },
1520 _ => None,
1521 }
1522}
1523
1524fn contains_member(
1526 span: &[u8],
1527 optional: bool,
1528 item: FieldType,
1529 needle: IndexValue<'_>,
1530) -> Result<bool, Error> {
1531 let mut reader = Decoder::new(span)?;
1532 if optional && !reader.boolean()? {
1533 return Ok(false);
1534 }
1535 for _ in 0..reader.nat32()? {
1536 let value = IndexValue::read(&mut reader, item)?;
1537 if equal_values(value, needle) {
1538 return Ok(true);
1539 }
1540 }
1541
1542 Ok(false)
1543}
1544
1545fn projection_positions(mut mask: u32) -> impl Iterator<Item = usize> {
1548 std::iter::from_fn(move || {
1549 if mask == 0 {
1550 return None;
1551 }
1552 let position = mask.trailing_zeros() as usize;
1553 mask &= mask - 1;
1554 Some(position)
1555 })
1556}
1557
1558fn admit_ordered_fields(entity: &EntitySchema, mask: u32) -> Result<(), Error> {
1559 for i in projection_positions(mask) {
1560 if !key::supports(entity.fields[i].value) {
1561 return Err(Error::InvalidQuery);
1562 }
1563 }
1564
1565 Ok(())
1566}
1567
1568fn comparison_key(
1570 entity: &EntitySchema,
1571 mask: u32,
1572 values: &[IndexValue<'_>],
1573 scratch: &mut Vec<u8>,
1574) -> Result<(), Error> {
1575 build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1576}
1577
1578fn build_comparison_key<'a>(
1579 entity: &EntitySchema,
1580 mask: u32,
1581 key: &mut Vec<u8>,
1582 mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1583) -> Result<(), Error> {
1584 key.clear();
1585 for i in projection_positions(mask) {
1586 let field = &entity.fields[i];
1587 value(i, field)?.append_component(field.optional, key);
1588 if key.len() > MAX_COMPARISON_KEY {
1589 return Err(Error::Limit);
1590 }
1591 }
1592
1593 Ok(())
1594}
1595
1596fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1597 if size > limit {
1598 return Err(Error::RowTooLarge);
1599 }
1600 if size > limit - *used {
1601 return Err(Error::Limit);
1602 }
1603 *used += size;
1604
1605 Ok(())
1606}
1607
1608fn projection_size(spans: &[(u16, u16)], mask: u32) -> usize {
1610 projection_positions(mask)
1611 .map(|i| {
1612 let (start, end) = spans[i];
1613 usize::from(end - start)
1614 })
1615 .sum()
1616}
1617
1618fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u32, size: usize) -> Vec<u8> {
1619 let mut output = Vec::with_capacity(size);
1620 for i in projection_positions(mask) {
1621 let (start, end) = spans[i];
1622 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1623 }
1624
1625 output
1626}
1627#[derive(Clone, Copy)]
1628enum PlanOutput {
1629 Rows,
1630 Aggregate { grouped: bool },
1631}
1632
1633struct Plan<'a> {
1634 primary: usize,
1635 index: Option<&'a IndexSchema>,
1636 prefix: Vec<u8>,
1637 fixed_components: usize,
1638 terms: Vec<Term>,
1639 selected: u32,
1640 span_fields: u32,
1642 binding: [u8; 32],
1643 projection: Option<u32>,
1644 distinct: distinct::Strategy,
1645 sort: Option<Vec<order::SortField>>,
1646 descending: bool,
1647}
1648impl<'a> Plan<'a> {
1649 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1650 self.terms.split_inclusive(|term| !term.or_next)
1651 }
1652
1653 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1654 self.index = Some(path.index);
1655 self.prefix = path.prefix;
1656 self.fixed_components = path.fixed;
1657 self.selected |= entity.key_fields();
1658 }
1659
1660 fn admit(
1661 entity: &'a EntitySchema,
1662 request: &Request<'_>,
1663 schema: [u8; 32],
1664 incarnation: [u8; 16],
1665 projection: Option<Projection<'_>>,
1666 output: PlanOutput,
1667 ) -> Result<Self, Error> {
1668 if request.over_limit
1669 || !(1..=32).contains(&request.rows)
1670 || !(1..=MAX_WORK).contains(&request.work)
1671 || !(1..=MAX_OUTPUT).contains(&request.bytes)
1672 {
1673 return Err(Error::Limit);
1674 }
1675 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1676 {
1677 return Err(Error::InvalidQuery);
1678 }
1679 for value in request
1681 .predicates
1682 .iter()
1683 .filter_map(|p| match &p.operand {
1684 QueryOperand::Literal(value) => Some(value),
1685 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1686 })
1687 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1688 {
1689 if match value {
1690 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1691 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1692 _ => false,
1693 } {
1694 return Err(Error::Limit);
1695 }
1696 }
1697 let primary = entity
1698 .field_position(entity.primary_key)
1699 .filter(|&i| !entity.fields[i].optional)
1700 .ok_or(Error::InvalidQuery)?;
1701 let mut plan = Self {
1702 primary,
1703 index: None,
1704 prefix: prefix(2, entity.id),
1705 fixed_components: 0,
1706 terms: Vec::new(),
1707 selected: 1 << primary,
1708 span_fields: 0,
1709 binding: [0; 32],
1710 projection: projection.map(|output| output.mask(entity)).transpose()?,
1711 distinct: distinct::Strategy::Identity,
1712 sort: None,
1713 descending: request.descending ^ request.primary_descending(entity),
1714 };
1715 for predicate in &request.predicates {
1716 let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
1717 let field = &entity.fields[position];
1718 let member = if predicate.comparison == Comparison::Contains {
1719 member_type(field.value)
1720 } else {
1721 None
1722 };
1723 let operand = match (predicate.operand, record_member) {
1724 (QueryOperand::Literal(value), Some(member)) => {
1725 if !predicate.comparison.supports_record_member() {
1726 return Err(Error::InvalidQuery);
1727 }
1728 let leaf = member.field();
1729 predicate.comparison.admit(
1730 leaf.value,
1731 field.optional || leaf.optional,
1732 value,
1733 )?;
1734 let mut literal = Vec::new();
1735 value.append_component(field.optional || leaf.optional, &mut literal);
1736 plan.span_fields |= 1 << position;
1737 TermOperand::Nested {
1738 member,
1739 literal,
1740 absent: value == IndexValue::Absent,
1741 }
1742 }
1743 (QueryOperand::Length(length), member) => {
1744 let selected = member.map_or(field.value, |m| m.field().value);
1745 if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1746 return Err(Error::InvalidQuery);
1747 }
1748 plan.span_fields |= 1 << position;
1749
1750 TermOperand::Length {
1751 member,
1752 threshold: length,
1753 }
1754 }
1755 (QueryOperand::Field(name), left_member) => {
1756 let (right, right_member) = crate::member::resolve_field(entity, name)?;
1757 if (left_member.is_some() || right_member.is_some())
1758 && member.is_none()
1759 && !predicate.comparison.supports_record_member()
1760 {
1761 return Err(Error::InvalidQuery);
1762 }
1763 let right_type =
1764 right_member.map_or(entity.fields[right].value, |m| m.field().value);
1765 let left_type =
1766 left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1767 let compatible = left_type == right_type
1768 || matches!(
1769 (left_type, right_type),
1770 (FieldType::Text { .. }, FieldType::Text { .. })
1771 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1772 );
1773 if !compatible
1774 || !key::supports(left_type)
1775 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1776 {
1777 return Err(Error::InvalidQuery);
1778 }
1779 if right_member.is_some() {
1780 plan.span_fields |= 1 << right;
1781 } else {
1782 plan.selected |= 1 << right;
1783 }
1784
1785 if let Some(item) = member {
1786 plan.span_fields |= 1 << position;
1787
1788 TermOperand::Member {
1789 item,
1790 needle: MemberNeedle::Field(right, right_member),
1791 }
1792 } else {
1793 if left_member.is_some() {
1794 plan.span_fields |= 1 << position;
1795 } else {
1796 plan.selected |= 1 << position;
1797 }
1798 TermOperand::Field {
1799 right,
1800 left_member,
1801 right_member,
1802 }
1803 }
1804 }
1805 (QueryOperand::Literal(value), None) => {
1806 if let Some(item) = member {
1807 if !key::supports(item) {
1808 return Err(Error::InvalidQuery);
1809 }
1810 value.admit(item, false)?;
1811 let mut bytes = Vec::new();
1812 value.append_component(false, &mut bytes);
1813 plan.span_fields |= 1 << position;
1814
1815 TermOperand::Member {
1816 item,
1817 needle: MemberNeedle::Literal(bytes),
1818 }
1819 } else {
1820 let absent = value == IndexValue::Absent;
1821 if key::supports(field.value) {
1822 plan.selected |= 1 << position;
1823 } else if absent
1824 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1825 {
1826 plan.span_fields |= 1 << position;
1827 } else {
1828 return Err(Error::InvalidQuery);
1829 }
1830 predicate
1831 .comparison
1832 .admit(field.value, field.optional, value)?;
1833 let mut bytes = Vec::new();
1834 value.append_component(field.optional, &mut bytes);
1835
1836 TermOperand::Literal { bytes, absent }
1837 }
1838 }
1839 };
1840 plan.terms.push(Term {
1841 tests_presence: predicate.tests_presence(entity, &operand),
1842 position,
1843 comparison: predicate.comparison,
1844 operand,
1845 or_next: predicate.or_next,
1846 });
1847 }
1848 match order::select(entity, request, output)? {
1851 order::Path::Primary => {}
1852 order::Path::Index(path, descending) => {
1853 plan.use_index(entity, path);
1854 plan.descending = request.descending ^ descending;
1855 }
1856 order::Path::Filtered { sort } => {
1857 order::select_filtered_path(entity, request, &mut plan, None)?;
1858 for field in sort.iter().flatten() {
1859 if field.member.is_some() {
1860 plan.span_fields |= 1 << field.position;
1861 } else {
1862 plan.selected |= 1 << field.position;
1863 }
1864 }
1865 plan.sort = sort;
1866 }
1867 }
1868 if request.distinct {
1869 plan.distinct = distinct::admit(entity, request, &plan)?;
1870 match plan.distinct {
1871 distinct::Strategy::FirstMatch => plan.sort = None,
1872 distinct::Strategy::Complete { key_fields } => plan.selected |= key_fields,
1873 _ => {}
1874 }
1875 }
1876 let mut hash = Sha256::new();
1877 hash.update(b"ic-db:query:v1\0");
1878 hash.update(schema);
1879 hash.update(incarnation);
1880 hash.update([u8::from(request.descending)]);
1881 hash.update((plan.prefix.len() as u32).to_le_bytes());
1882 hash.update(&plan.prefix);
1883 for term in &plan.terms {
1884 hash.update([term.position as u8, term.comparison as u8]);
1885
1886 match &term.operand {
1887 TermOperand::Nested {
1888 member,
1889 literal,
1890 absent,
1891 } => {
1892 hash.update((u32::MAX - 2).to_le_bytes());
1893 hash.update([member.position() as u8, u8::from(*absent)]);
1894 let literal = &literal[usize::from(
1896 entity.fields[term.position].optional || member.field().optional,
1897 )..];
1898 hash.update((literal.len() as u32).to_le_bytes());
1899 hash.update(literal);
1900 }
1901 TermOperand::Literal { bytes, .. }
1902 | TermOperand::Member {
1903 needle: MemberNeedle::Literal(bytes),
1904 ..
1905 } => {
1906 hash.update((bytes.len() as u32).to_le_bytes());
1907 hash.update(bytes);
1908 }
1909 TermOperand::Length { member, threshold } => {
1910 if let Some(member) = member {
1911 hash.update((u32::MAX - 3).to_le_bytes());
1912 hash.update([member.position() as u8]);
1913 } else {
1914 hash.update((u32::MAX - 1).to_le_bytes());
1915 }
1916 hash.update(threshold.to_le_bytes());
1917 }
1918 TermOperand::Field {
1919 right,
1920 left_member: None,
1921 right_member: None,
1922 }
1923 | TermOperand::Member {
1924 needle: MemberNeedle::Field(right, None),
1925 ..
1926 } => {
1927 hash.update(u32::MAX.to_le_bytes());
1929 hash.update([*right as u8]);
1930 }
1931 TermOperand::Member {
1932 needle: MemberNeedle::Field(right, Some(member)),
1933 ..
1934 } => {
1935 hash.update((u32::MAX - 4).to_le_bytes());
1936 hash.update([u8::MAX, *right as u8, member.position() as u8]);
1937 }
1938 TermOperand::Field {
1939 right,
1940 left_member,
1941 right_member,
1942 } => {
1943 hash.update((u32::MAX - 4).to_le_bytes());
1944 let slot = |member: &Option<crate::member::RecordMember>| {
1945 member.map_or(u8::MAX, |m| m.position() as u8)
1946 };
1947 hash.update([slot(left_member), *right as u8, slot(right_member)]);
1948 }
1949 }
1950 }
1951 let clauses = plan
1954 .terms
1955 .iter()
1956 .enumerate()
1957 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1958 if clauses != 0 {
1959 hash.update(b"or-clauses\0");
1960 hash.update([clauses]);
1961 }
1962 if let Some(order) = &request.order {
1963 hash.update(b"order\0");
1964 hash.update([order.len() as u8]);
1965 for name in order {
1966 if let Some(position) = entity.field_position(name) {
1968 hash.update([position as u8]);
1969 } else {
1970 hash.update([u8::MAX, name.len() as u8]);
1972 hash.update(name.as_bytes());
1973 }
1974 }
1975 }
1976 if request.order_descending != 0 {
1977 hash.update(b"order-directions\0");
1978 hash.update([request.order_descending]);
1979 }
1980 if let Some(mask) = plan.projection {
1983 hash.update(b"projection\0");
1984 hash.update(mask.to_le_bytes());
1985 if let Some(Projection::Columns(columns)) = projection {
1986 hash.update(b"columns\0");
1987 hash.update(columns);
1988 }
1989 }
1990 if request.distinct {
1991 hash.update(b"distinct\0");
1992 }
1993 plan.binding = hash.finalize().into();
1994 if let Some(cursor) = request.cursor {
1995 if cursor.binding != plan.binding {
1996 return Err(Error::InvalidCursor);
1997 }
1998 plan.validate_position(entity, cursor)
1999 .map_err(|_| Error::InvalidCursor)?;
2000 }
2001
2002 Ok(plan)
2003 }
2004
2005 fn validate_position(&self, entity: &EntitySchema, cursor: &QueryCursor) -> Result<(), Error> {
2006 if cursor.resume == Resume::AfterUnemittedClass
2007 && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
2008 {
2009 return Err(Error::InvalidCursor);
2010 }
2011 let bytes = cursor.position.as_slice();
2012 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
2013 return Err(Error::InvalidCursor);
2014 }
2015 if let Some(index) = self.index {
2016 let mut remaining = bytes
2017 .get(INDEX_PREFIX_BYTES..)
2018 .ok_or(Error::InvalidCursor)?;
2019 for name in index.fields {
2020 consume_index_component(entity, index, name, &mut remaining)?;
2021 }
2022 if !index.unique {
2023 key::consume(&mut remaining, entity.key_type()?)?;
2024 }
2025 if !remaining.is_empty() {
2026 return Err(Error::InvalidCursor);
2027 }
2028 } else {
2029 RowKey::decode(
2030 bytes
2031 .get(ENTITY_PREFIX_BYTES..)
2032 .ok_or(Error::InvalidCursor)?,
2033 entity.key_type()?,
2034 )?;
2035 }
2036
2037 Ok(())
2038 }
2039
2040 fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
2041 QueryCursor {
2042 binding: self.binding,
2043 position: position.to_vec(),
2044 resume,
2045 }
2046 }
2047}
2048
2049fn consume_index_component(
2051 entity: &EntitySchema,
2052 index: &IndexSchema,
2053 name: &str,
2054 remaining: &mut &[u8],
2055) -> Result<(), Error> {
2056 let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
2057
2058 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
2059}
2060
2061#[inline(never)]
2064#[expect(
2065 clippy::needless_pass_by_value,
2066 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
2067)]
2068fn fetch_rows<M: Memory>(
2069 db: &Database<M>,
2070 entity: &EntitySchema,
2071 request: Request<'_>,
2072 projection: Option<Projection<'_>>,
2073) -> Result<QueryPage<Vec<u8>>, Error> {
2074 db.schema.admits(entity)?;
2075 let plan = Plan::admit(
2076 entity,
2077 &request,
2078 db.schema.fingerprint(),
2079 db.incarnation,
2080 projection,
2081 PlanOutput::Rows,
2082 )?;
2083
2084 execute(&db.map, entity, &request, &plan, None)
2085}
2086
2087fn execute<M: Memory>(
2088 map: &Map<M>,
2089 entity: &EntitySchema,
2090 request: &Request<'_>,
2091 plan: &Plan<'_>,
2092 mut aggregate: Option<aggregate::Accumulator<'_>>,
2093) -> Result<QueryPage<Vec<u8>>, Error> {
2094 execute_inner(
2095 map,
2096 entity,
2097 request,
2098 plan,
2099 range::bounds(entity, request, plan)?,
2100 aggregate.as_mut(),
2101 None,
2102 )
2103}
2104
2105const STEP_INPUT_BYTES: usize = 64 * 1024;
2108const fn candidate_byte_limit(row_bytes: usize) -> usize {
2109 row_bytes + 2 * crate::MAX_INDEX_KEY_BYTES
2110}
2111
2112fn execute_inner<M: Memory>(
2113 map: &Map<M>,
2114 entity: &EntitySchema,
2115 request: &Request<'_>,
2116 plan: &Plan<'_>,
2117 bounds: Option<range::Bounds>,
2118 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
2119 mut input_bytes: Option<&mut usize>,
2120) -> Result<QueryPage<Vec<u8>>, Error> {
2121 let mut page = QueryPage {
2122 rows: Vec::new(),
2123 next: None,
2124 examined: 0,
2125 fetched: 0,
2126 output_bytes: 0,
2127 };
2128 let Some(bounds) = bounds else {
2129 return Ok(page);
2130 };
2131 let terminal = range::terminal_key(&bounds, plan.descending);
2132 let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
2133 let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
2134 Some(distinct::Collection::new(
2135 plan.projection.ok_or(Error::InvalidQuery)?,
2136 key_fields,
2137 ))
2138 } else {
2139 None
2140 };
2141 let mut sorted = plan
2142 .sort
2143 .as_ref()
2144 .map(|_| sort::Collection::new(request, plan.distinct));
2145 let mut component = Vec::new();
2146 let mut right_component = Vec::new();
2147 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
2149 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
2150 } else {
2151 None
2152 };
2153 let candidate_bytes = candidate_byte_limit(entity.max_row_bytes);
2154 let primary_type = entity.fields[plan.primary].value;
2155 let needs_spans = plan.index.is_some()
2156 || plan.span_fields != 0
2157 || match &aggregate {
2158 Some(accumulator) => accumulator.needs_spans(),
2159 None => plan.projection.is_some(),
2160 };
2161 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
2163 while let Some(entry) = if plan.descending {
2164 entries.next_back()
2165 } else {
2166 entries.next()
2167 } {
2168 if page.examined == request.work {
2171 return Err(Error::Limit);
2172 }
2173 page.examined += 1;
2174 let stored_key = entry.key();
2175 let mut read_bytes = stored_key.len();
2176 let (owner, bytes) = if plan.index.is_some() {
2177 let owner_bytes = entry.value();
2178 read_bytes += owner_bytes.len();
2179 read_index_owner(map, entity.id, primary_type, &owner_bytes)?
2180 } else {
2181 (
2182 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
2183 entry.value(),
2184 )
2185 };
2186 if let Some(used) = input_bytes.as_deref_mut() {
2187 read_bytes += bytes.len();
2188 if read_bytes > candidate_bytes {
2189 return Err(Error::Corrupt);
2190 }
2191 *used += read_bytes;
2192 }
2193 page.fetched += 1;
2194 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
2195 entity.inspect_fields(
2196 &bytes,
2197 plan.selected,
2198 &mut values,
2199 needs_spans.then_some(&mut spans),
2200 )?;
2201 if RowKey::from_index(values[plan.primary])? != owner {
2202 return Err(Error::Corrupt);
2203 }
2204 if plan.index.is_some() {
2205 validate_index_entry(
2206 entity,
2207 &entity.row_info(&values, &bytes, &spans)?,
2208 owner,
2209 stored_key,
2210 )?;
2211 }
2212 let read = |position: usize, member: Option<crate::member::RecordMember>| {
2213 if let Some(member) = member {
2214 let (start, end) = spans[position];
2215 member.read(
2216 &bytes[usize::from(start)..usize::from(end)],
2217 entity.fields[position].optional,
2218 )
2219 } else {
2220 Ok(values[position])
2221 }
2222 };
2223 let mut accepts = |term: &Term, supplied: &QueryOperand<'_>| -> Result<bool, Error> {
2224 let mut value = values[term.position];
2225 component.clear();
2226 let (operand, optional) = match &term.operand {
2227 TermOperand::Nested {
2228 member,
2229 literal,
2230 absent,
2231 } => {
2232 value = read(term.position, Some(*member))?;
2233 if *absent {
2234 return Ok(term.comparison.accepts_absent(value == IndexValue::Absent));
2235 }
2236 (
2237 Some(literal.as_slice()),
2238 entity.fields[term.position].optional || member.field().optional,
2239 )
2240 }
2241 TermOperand::Literal { absent: true, .. } => {
2242 let absent = if plan.span_fields & (1 << term.position) != 0 {
2243 bytes[usize::from(spans[term.position].0)] == 0
2244 } else {
2245 value == IndexValue::Absent
2246 };
2247
2248 return Ok(term.comparison.accepts_absent(absent));
2249 }
2250 TermOperand::Member { item, needle } => {
2251 let needle = match (needle, supplied) {
2252 (MemberNeedle::Literal(_), QueryOperand::Literal(value)) => *value,
2253 (MemberNeedle::Field(right, member), QueryOperand::Field(_)) => {
2254 read(*right, *member)?
2255 }
2256 _ => return Err(Error::Corrupt),
2257 };
2258 if needle == IndexValue::Absent {
2259 return Ok(false);
2260 }
2261 let (start, end) = spans[term.position];
2262
2263 return contains_member(
2264 &bytes[usize::from(start)..usize::from(end)],
2265 entity.fields[term.position].optional,
2266 *item,
2267 needle,
2268 );
2269 }
2270 TermOperand::Length { member, threshold } => {
2271 let (start, end) = spans[term.position];
2272 let span = &bytes[usize::from(start)..usize::from(end)];
2273 let optional = entity.fields[term.position].optional;
2274 let actual = if let Some(member) = member {
2275 match member.read(span, optional)? {
2276 IndexValue::Absent => None,
2277 value => Some(scalar_bytes(value).ok_or(Error::Corrupt)?.len() as u32),
2278 }
2279 } else {
2280 crate::codec::validated_length(span, optional)
2281 };
2282
2283 return Ok(term.comparison.accepts_length(actual, *threshold));
2284 }
2285 TermOperand::Literal {
2286 bytes,
2287 absent: false,
2288 } => (
2289 Some(bytes.as_slice()),
2290 entity.fields[term.position].optional,
2291 ),
2292 TermOperand::Field {
2293 right,
2294 left_member,
2295 right_member,
2296 } => {
2297 value = read(term.position, *left_member)?;
2298 let rhs = read(*right, *right_member)?;
2299 if value == IndexValue::Absent || rhs == IndexValue::Absent {
2300 return Ok(term.comparison.accepts_absent(value == rhs));
2301 }
2302 if let Some(matches) = term.comparison.accepts_values(value, rhs) {
2303 return Ok(matches);
2304 }
2305 right_component.clear();
2306 rhs.append_component(false, &mut right_component);
2307
2308 (Some(right_component.as_slice()), false)
2309 }
2310 };
2311 if let QueryOperand::Literal(right) = supplied
2312 && let Some(matches) = term.comparison.accepts_values(value, *right)
2313 {
2314 return Ok(matches);
2315 }
2316 value.append_component(optional, &mut component);
2317
2318 Ok(term.comparison.accepts(
2319 (value != IndexValue::Absent).then_some(component.as_slice()),
2320 operand,
2321 optional,
2322 ))
2323 };
2324 let matches = 'matches: {
2325 let mut clause_matches = false;
2326 for (term, predicate) in plan.terms.iter().zip(&request.predicates) {
2327 clause_matches = clause_matches || accepts(term, &predicate.operand)?;
2328 if !term.or_next {
2329 if !clause_matches {
2330 break 'matches false;
2331 }
2332 clause_matches = false;
2333 }
2334 }
2335
2336 true
2337 };
2338 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
2339 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2340 if matches && let Some(accumulator) = aggregate.as_mut() {
2341 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2342 if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
2343 return Ok(page);
2345 }
2346 } else if matches && let Some(collection) = collected.as_mut() {
2347 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2348 if request.single_result_probe == Some(SingleResult::First) {
2350 break;
2351 }
2352 } else if matches && let Some(collection) = sorted.as_mut() {
2353 collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2354 request.check_result_count(collection.result_count())?;
2356 } else if matches && !duplicate {
2357 request.check_result_count(page.rows.len() + 1)?;
2358 let size = plan
2359 .projection
2360 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2361 if size > request.bytes {
2362 return Err(Error::RowTooLarge);
2363 }
2364 if size > request.bytes - page.output_bytes {
2365 page.next = Some(plan.cursor(stored_key, Resume::Retry));
2366
2367 return Ok(page);
2368 }
2369 page.output_bytes += size;
2370 if let Some(mask) = plan.projection {
2371 page.rows.push(copy_projection(&bytes, &spans, mask, size));
2372 } else {
2373 page.rows.push(bytes);
2374 }
2375 if request.single_result_probe == Some(SingleResult::First)
2376 || plan.distinct.finishes_on_match(plan.fixed_components)
2377 {
2378 return Ok(page);
2379 }
2380 if let Some(boundary) = boundary {
2381 previous = Some(boundary.to_vec());
2382 }
2383 }
2384 if page.rows.len() == request.rows
2385 || page.examined == request.work
2386 || input_bytes
2387 .as_deref()
2388 .is_some_and(|used| *used > STEP_INPUT_BYTES - candidate_bytes)
2389 {
2390 if terminal == Some(stored_key) {
2391 break;
2392 }
2393 if request.single_result_probe.is_some()
2394 || matches!(aggregate, Some(aggregate::Accumulator::Exists(_)))
2395 {
2396 continue;
2399 }
2400 if (aggregate.is_some() && input_bytes.is_none())
2401 || collected.is_some()
2402 || sorted.is_some()
2403 {
2404 return Err(Error::Limit);
2407 }
2408 let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
2409 Resume::AfterUnemittedClass
2410 } else {
2411 Resume::After
2412 };
2413 page.next = Some(plan.cursor(stored_key, resume));
2414
2415 return Ok(page);
2416 }
2417 }
2418 if let Some(collection) = collected {
2419 page.output_bytes = collection.output_bytes;
2420 page.rows = collection.rows;
2421 }
2422 if let Some(collection) = sorted {
2423 collection.finish(request.bytes, &mut page)?;
2424 }
2425
2426 Ok(page)
2427}