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, primary::RowKey, types::TypeGraph,
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 let page = fetch(self.probe_matches(SingleResult::Only)?)?;
1333 if page.next.is_some() {
1334 return Err(Error::Limit);
1335 }
1336
1337 Ok(page)
1338 })
1339 .map(|mut page| page.rows.pop())
1340 }
1341
1342 fn probe_matches(mut self, probe: SingleResult) -> Result<Self, Error> {
1343 if !(1..=32).contains(&self.request.rows) {
1344 return Err(Error::Limit);
1345 }
1346
1347 self.request.single_result_probe = Some(probe);
1348
1349 Ok(self.limit(match probe {
1350 SingleResult::First => 1,
1351 SingleResult::Only => 2,
1352 }))
1353 }
1354
1355 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1365 observe!(query, { self.projected_page() })
1366 }
1367
1368 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1369 let raw = fetch_rows(
1370 &*self.db.read()?,
1371 E::SCHEMA,
1372 self.request,
1373 Some(Projection::Record(R::definition())),
1374 )?;
1375
1376 raw.decode_with(R::decode_from)
1377 }
1378}
1379
1380#[derive(Clone, Copy)]
1381enum Projection<'a> {
1382 Record(&'a TypeSchema),
1383 Columns(&'a [u8]),
1384}
1385
1386impl Projection<'_> {
1387 fn mask(self, entity: &EntitySchema) -> Result<u32, Error> {
1388 match self {
1389 Self::Record(record) => admit_projection(entity, record),
1390 Self::Columns(columns) => {
1391 let mut mask = 0;
1392 for &column in columns {
1393 if usize::from(column) >= entity.fields.len() || mask & (1 << column) != 0 {
1394 return Err(Error::InvalidQuery);
1395 }
1396 mask |= 1 << column;
1397 }
1398 Ok(mask)
1399 }
1400 }
1401 }
1402}
1403
1404fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u32, Error> {
1408 let TypeBody::Record(fields) = &output.body else {
1409 return Err(Error::InvalidQuery);
1410 };
1411 if fields.is_empty()
1412 || fields.len() > crate::schema::MAX_FIELDS
1413 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1414 {
1415 return Err(Error::InvalidQuery);
1416 }
1417 let mut source = TypeGraph::default();
1418 let mut target = TypeGraph::default();
1419 let mut mask = 0;
1420 for field in *fields {
1421 let position = entity
1422 .field_position(field.name)
1423 .ok_or(Error::InvalidQuery)?;
1424 let stored = &entity.fields[position];
1425 if stored.value != field.value || stored.optional != field.optional {
1426 return Err(Error::InvalidQuery);
1427 }
1428 source
1429 .include(stored.value)
1430 .map_err(|_| Error::InvalidQuery)?;
1431 target
1432 .include(field.value)
1433 .map_err(|_| Error::InvalidQuery)?;
1434 mask |= 1 << position;
1435 }
1436 if !source.contains(&target) {
1437 return Err(Error::InvalidQuery);
1438 }
1439
1440 Ok(mask)
1441}
1442
1443struct Term {
1444 tests_presence: bool,
1445 position: usize,
1446 comparison: Comparison,
1447 operand: TermOperand,
1448 or_next: bool,
1449}
1450
1451enum TermOperand {
1452 Literal {
1453 bytes: Vec<u8>,
1454 absent: bool,
1455 },
1456 Member {
1457 item: FieldType,
1458 needle: MemberNeedle,
1459 },
1460 Nested {
1461 member: crate::member::RecordMember,
1462 literal: Vec<u8>,
1463 absent: bool,
1464 },
1465 Field {
1466 right: usize,
1467 left_member: Option<crate::member::RecordMember>,
1468 right_member: Option<crate::member::RecordMember>,
1469 },
1470 Length {
1471 member: Option<crate::member::RecordMember>,
1472 threshold: u32,
1473 },
1474}
1475
1476enum MemberNeedle {
1477 Literal(Vec<u8>),
1478 Field(usize, Option<crate::member::RecordMember>),
1479}
1480
1481fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1484 match value {
1485 IndexValue::Text(text) => Some(text.as_bytes()),
1486 IndexValue::Blob(bytes) => Some(bytes),
1487 _ => None,
1488 }
1489}
1490
1491fn consecutive_values(low: IndexValue<'_>, high: IndexValue<'_>) -> bool {
1492 low.discrete_successor()
1493 .is_some_and(|next| equal_values(next, high))
1494}
1495
1496fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1497 match (left, right) {
1499 (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1500 a == b
1501 }
1502 _ => left == right,
1503 }
1504}
1505
1506fn length_limit(field: FieldType) -> Option<u32> {
1507 match key::operand_type(field) {
1508 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1509 FieldType::List { max_items, .. } => Some(max_items),
1510 FieldType::Named(link) => match (link.definition)().body {
1511 TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1512 _ => None,
1513 },
1514 _ => None,
1515 }
1516}
1517
1518fn member_type(field: FieldType) -> Option<FieldType> {
1519 match key::operand_type(field) {
1520 FieldType::List { item, .. } => Some(*item),
1521 FieldType::Named(link) => match (link.definition)().body {
1522 TypeBody::Set { item, .. } => Some(item),
1523 _ => None,
1524 },
1525 _ => None,
1526 }
1527}
1528
1529fn contains_member(
1531 span: &[u8],
1532 optional: bool,
1533 item: FieldType,
1534 needle: IndexValue<'_>,
1535) -> Result<bool, Error> {
1536 let mut reader = Decoder::new(span)?;
1537 if optional && !reader.boolean()? {
1538 return Ok(false);
1539 }
1540 for _ in 0..reader.nat32()? {
1541 let value = IndexValue::read(&mut reader, item)?;
1542 if equal_values(value, needle) {
1543 return Ok(true);
1544 }
1545 }
1546
1547 Ok(false)
1548}
1549
1550fn projection_positions(mut mask: u32) -> impl Iterator<Item = usize> {
1553 std::iter::from_fn(move || {
1554 if mask == 0 {
1555 return None;
1556 }
1557 let position = mask.trailing_zeros() as usize;
1558 mask &= mask - 1;
1559 Some(position)
1560 })
1561}
1562
1563fn admit_ordered_fields(entity: &EntitySchema, mask: u32) -> Result<(), Error> {
1564 for i in projection_positions(mask) {
1565 if !key::supports(entity.fields[i].value) {
1566 return Err(Error::InvalidQuery);
1567 }
1568 }
1569
1570 Ok(())
1571}
1572
1573fn comparison_key(
1575 entity: &EntitySchema,
1576 mask: u32,
1577 values: &[IndexValue<'_>],
1578 scratch: &mut Vec<u8>,
1579) -> Result<(), Error> {
1580 build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1581}
1582
1583fn build_comparison_key<'a>(
1584 entity: &EntitySchema,
1585 mask: u32,
1586 key: &mut Vec<u8>,
1587 mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1588) -> Result<(), Error> {
1589 key.clear();
1590 for i in projection_positions(mask) {
1591 let field = &entity.fields[i];
1592 value(i, field)?.append_component(field.optional, key);
1593 if key.len() > MAX_COMPARISON_KEY {
1594 return Err(Error::Limit);
1595 }
1596 }
1597
1598 Ok(())
1599}
1600
1601fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1602 if size > limit {
1603 return Err(Error::RowTooLarge);
1604 }
1605 if size > limit - *used {
1606 return Err(Error::Limit);
1607 }
1608 *used += size;
1609
1610 Ok(())
1611}
1612
1613fn projection_size(spans: &[(u16, u16)], mask: u32) -> usize {
1615 projection_positions(mask)
1616 .map(|i| {
1617 let (start, end) = spans[i];
1618 usize::from(end - start)
1619 })
1620 .sum()
1621}
1622
1623fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u32, size: usize) -> Vec<u8> {
1624 let mut output = Vec::with_capacity(size);
1625 for i in projection_positions(mask) {
1626 let (start, end) = spans[i];
1627 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1628 }
1629
1630 output
1631}
1632#[derive(Clone, Copy)]
1633enum PlanOutput {
1634 Rows,
1635 Aggregate { grouped: bool },
1636}
1637
1638struct Plan<'a> {
1639 primary: usize,
1640 index: Option<&'a IndexSchema>,
1641 prefix: Vec<u8>,
1642 fixed_components: usize,
1643 terms: Vec<Term>,
1644 selected: u32,
1645 span_fields: u32,
1647 binding: [u8; 32],
1648 projection: Option<u32>,
1649 distinct: distinct::Strategy,
1650 sort: Option<Vec<order::SortField>>,
1651 descending: bool,
1652}
1653impl<'a> Plan<'a> {
1654 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1655 self.terms.split_inclusive(|term| !term.or_next)
1656 }
1657
1658 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1659 self.index = Some(path.index);
1660 self.prefix = path.prefix;
1661 self.fixed_components = path.fixed;
1662 self.selected |= entity.key_fields();
1663 }
1664
1665 fn admit(
1666 entity: &'a EntitySchema,
1667 request: &Request<'_>,
1668 schema: [u8; 32],
1669 incarnation: [u8; 16],
1670 projection: Option<Projection<'_>>,
1671 output: PlanOutput,
1672 ) -> Result<Self, Error> {
1673 if request.over_limit
1674 || !(1..=32).contains(&request.rows)
1675 || !(1..=MAX_WORK).contains(&request.work)
1676 || !(1..=MAX_OUTPUT).contains(&request.bytes)
1677 {
1678 return Err(Error::Limit);
1679 }
1680 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1681 {
1682 return Err(Error::InvalidQuery);
1683 }
1684 for value in request
1686 .predicates
1687 .iter()
1688 .filter_map(|p| match &p.operand {
1689 QueryOperand::Literal(value) => Some(value),
1690 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1691 })
1692 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1693 {
1694 if match value {
1695 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1696 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1697 _ => false,
1698 } {
1699 return Err(Error::Limit);
1700 }
1701 }
1702 let primary = entity
1703 .field_position(entity.primary_key)
1704 .filter(|&i| !entity.fields[i].optional)
1705 .ok_or(Error::InvalidQuery)?;
1706 let mut plan = Self {
1707 primary,
1708 index: None,
1709 prefix: prefix(2, entity.id),
1710 fixed_components: 0,
1711 terms: Vec::new(),
1712 selected: 1 << primary,
1713 span_fields: 0,
1714 binding: [0; 32],
1715 projection: projection.map(|output| output.mask(entity)).transpose()?,
1716 distinct: distinct::Strategy::Identity,
1717 sort: None,
1718 descending: request.descending ^ request.primary_descending(entity),
1719 };
1720 for predicate in &request.predicates {
1721 let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
1722 let field = &entity.fields[position];
1723 let member = if predicate.comparison == Comparison::Contains {
1724 member_type(field.value)
1725 } else {
1726 None
1727 };
1728 let operand = match (predicate.operand, record_member) {
1729 (QueryOperand::Literal(value), Some(member)) => {
1730 if !predicate.comparison.supports_record_member() {
1731 return Err(Error::InvalidQuery);
1732 }
1733 let leaf = member.field();
1734 predicate.comparison.admit(
1735 leaf.value,
1736 field.optional || leaf.optional,
1737 value,
1738 )?;
1739 let mut literal = Vec::new();
1740 value.append_component(field.optional || leaf.optional, &mut literal);
1741 plan.span_fields |= 1 << position;
1742 TermOperand::Nested {
1743 member,
1744 literal,
1745 absent: value == IndexValue::Absent,
1746 }
1747 }
1748 (QueryOperand::Length(length), member) => {
1749 let selected = member.map_or(field.value, |m| m.field().value);
1750 if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1751 return Err(Error::InvalidQuery);
1752 }
1753 plan.span_fields |= 1 << position;
1754
1755 TermOperand::Length {
1756 member,
1757 threshold: length,
1758 }
1759 }
1760 (QueryOperand::Field(name), left_member) => {
1761 let (right, right_member) = crate::member::resolve_field(entity, name)?;
1762 if (left_member.is_some() || right_member.is_some())
1763 && member.is_none()
1764 && !predicate.comparison.supports_record_member()
1765 {
1766 return Err(Error::InvalidQuery);
1767 }
1768 let right_type =
1769 right_member.map_or(entity.fields[right].value, |m| m.field().value);
1770 let left_type =
1771 left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1772 let compatible = left_type == right_type
1773 || matches!(
1774 (left_type, right_type),
1775 (FieldType::Text { .. }, FieldType::Text { .. })
1776 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1777 );
1778 if !compatible
1779 || !key::supports(left_type)
1780 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1781 {
1782 return Err(Error::InvalidQuery);
1783 }
1784 if right_member.is_some() {
1785 plan.span_fields |= 1 << right;
1786 } else {
1787 plan.selected |= 1 << right;
1788 }
1789
1790 if let Some(item) = member {
1791 plan.span_fields |= 1 << position;
1792
1793 TermOperand::Member {
1794 item,
1795 needle: MemberNeedle::Field(right, right_member),
1796 }
1797 } else {
1798 if left_member.is_some() {
1799 plan.span_fields |= 1 << position;
1800 } else {
1801 plan.selected |= 1 << position;
1802 }
1803 TermOperand::Field {
1804 right,
1805 left_member,
1806 right_member,
1807 }
1808 }
1809 }
1810 (QueryOperand::Literal(value), None) => {
1811 if let Some(item) = member {
1812 if !key::supports(item) {
1813 return Err(Error::InvalidQuery);
1814 }
1815 value.admit(item, false)?;
1816 let mut bytes = Vec::new();
1817 value.append_component(false, &mut bytes);
1818 plan.span_fields |= 1 << position;
1819
1820 TermOperand::Member {
1821 item,
1822 needle: MemberNeedle::Literal(bytes),
1823 }
1824 } else {
1825 let absent = value == IndexValue::Absent;
1826 if key::supports(field.value) {
1827 plan.selected |= 1 << position;
1828 } else if absent
1829 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1830 {
1831 plan.span_fields |= 1 << position;
1832 } else {
1833 return Err(Error::InvalidQuery);
1834 }
1835 predicate
1836 .comparison
1837 .admit(field.value, field.optional, value)?;
1838 let mut bytes = Vec::new();
1839 value.append_component(field.optional, &mut bytes);
1840
1841 TermOperand::Literal { bytes, absent }
1842 }
1843 }
1844 };
1845 plan.terms.push(Term {
1846 tests_presence: predicate.tests_presence(entity, &operand),
1847 position,
1848 comparison: predicate.comparison,
1849 operand,
1850 or_next: predicate.or_next,
1851 });
1852 }
1853 match order::select(entity, request, output)? {
1856 order::Path::Primary => {}
1857 order::Path::Index(path, descending) => {
1858 plan.use_index(entity, path);
1859 plan.descending = request.descending ^ descending;
1860 }
1861 order::Path::Filtered { sort } => {
1862 order::select_filtered_path(entity, request, &mut plan, None)?;
1863 for field in sort.iter().flatten() {
1864 if field.member.is_some() {
1865 plan.span_fields |= 1 << field.position;
1866 } else {
1867 plan.selected |= 1 << field.position;
1868 }
1869 }
1870 plan.sort = sort;
1871 }
1872 }
1873 if request.distinct {
1874 plan.distinct = distinct::admit(entity, request, &plan)?;
1875 match plan.distinct {
1876 distinct::Strategy::FirstMatch => plan.sort = None,
1877 distinct::Strategy::Complete { key_fields } => plan.selected |= key_fields,
1878 _ => {}
1879 }
1880 }
1881 let mut hash = Sha256::new();
1882 hash.update(b"ic-db:query:v1\0");
1883 hash.update(schema);
1884 hash.update(incarnation);
1885 hash.update([u8::from(request.descending)]);
1886 hash.update((plan.prefix.len() as u32).to_le_bytes());
1887 hash.update(&plan.prefix);
1888 for term in &plan.terms {
1889 hash.update([term.position as u8, term.comparison as u8]);
1890
1891 match &term.operand {
1892 TermOperand::Nested {
1893 member,
1894 literal,
1895 absent,
1896 } => {
1897 hash.update((u32::MAX - 2).to_le_bytes());
1898 hash.update([member.position() as u8, u8::from(*absent)]);
1899 let literal = &literal[usize::from(
1901 entity.fields[term.position].optional || member.field().optional,
1902 )..];
1903 hash.update((literal.len() as u32).to_le_bytes());
1904 hash.update(literal);
1905 }
1906 TermOperand::Literal { bytes, .. }
1907 | TermOperand::Member {
1908 needle: MemberNeedle::Literal(bytes),
1909 ..
1910 } => {
1911 hash.update((bytes.len() as u32).to_le_bytes());
1912 hash.update(bytes);
1913 }
1914 TermOperand::Length { member, threshold } => {
1915 if let Some(member) = member {
1916 hash.update((u32::MAX - 3).to_le_bytes());
1917 hash.update([member.position() as u8]);
1918 } else {
1919 hash.update((u32::MAX - 1).to_le_bytes());
1920 }
1921 hash.update(threshold.to_le_bytes());
1922 }
1923 TermOperand::Field {
1924 right,
1925 left_member: None,
1926 right_member: None,
1927 }
1928 | TermOperand::Member {
1929 needle: MemberNeedle::Field(right, None),
1930 ..
1931 } => {
1932 hash.update(u32::MAX.to_le_bytes());
1934 hash.update([*right as u8]);
1935 }
1936 TermOperand::Member {
1937 needle: MemberNeedle::Field(right, Some(member)),
1938 ..
1939 } => {
1940 hash.update((u32::MAX - 4).to_le_bytes());
1941 hash.update([u8::MAX, *right as u8, member.position() as u8]);
1942 }
1943 TermOperand::Field {
1944 right,
1945 left_member,
1946 right_member,
1947 } => {
1948 hash.update((u32::MAX - 4).to_le_bytes());
1949 let slot = |member: &Option<crate::member::RecordMember>| {
1950 member.map_or(u8::MAX, |m| m.position() as u8)
1951 };
1952 hash.update([slot(left_member), *right as u8, slot(right_member)]);
1953 }
1954 }
1955 }
1956 let clauses = plan
1959 .terms
1960 .iter()
1961 .enumerate()
1962 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1963 if clauses != 0 {
1964 hash.update(b"or-clauses\0");
1965 hash.update([clauses]);
1966 }
1967 if let Some(order) = &request.order {
1968 hash.update(b"order\0");
1969 hash.update([order.len() as u8]);
1970 for name in order {
1971 if let Some(position) = entity.field_position(name) {
1973 hash.update([position as u8]);
1974 } else {
1975 hash.update([u8::MAX, name.len() as u8]);
1977 hash.update(name.as_bytes());
1978 }
1979 }
1980 }
1981 if request.order_descending != 0 {
1982 hash.update(b"order-directions\0");
1983 hash.update([request.order_descending]);
1984 }
1985 if let Some(mask) = plan.projection {
1988 hash.update(b"projection\0");
1989 hash.update(mask.to_le_bytes());
1990 if let Some(Projection::Columns(columns)) = projection {
1991 hash.update(b"columns\0");
1992 hash.update(columns);
1993 }
1994 }
1995 if request.distinct {
1996 hash.update(b"distinct\0");
1997 }
1998 plan.binding = hash.finalize().into();
1999 if let Some(cursor) = request.cursor {
2000 if cursor.binding != plan.binding {
2001 return Err(Error::InvalidCursor);
2002 }
2003 plan.validate_position(entity, cursor)
2004 .map_err(|_| Error::InvalidCursor)?;
2005 }
2006
2007 Ok(plan)
2008 }
2009
2010 fn validate_position(&self, entity: &EntitySchema, cursor: &QueryCursor) -> Result<(), Error> {
2011 if cursor.resume == Resume::AfterUnemittedClass
2012 && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
2013 {
2014 return Err(Error::InvalidCursor);
2015 }
2016 let bytes = cursor.position.as_slice();
2017 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
2018 return Err(Error::InvalidCursor);
2019 }
2020 if let Some(index) = self.index {
2021 let mut remaining = bytes
2022 .get(INDEX_PREFIX_BYTES..)
2023 .ok_or(Error::InvalidCursor)?;
2024 for name in index.fields {
2025 consume_index_component(entity, index, name, &mut remaining)?;
2026 }
2027 if !index.unique {
2028 key::consume(&mut remaining, entity.key_type()?)?;
2029 }
2030 if !remaining.is_empty() {
2031 return Err(Error::InvalidCursor);
2032 }
2033 } else {
2034 RowKey::decode(
2035 bytes
2036 .get(ENTITY_PREFIX_BYTES..)
2037 .ok_or(Error::InvalidCursor)?,
2038 entity.key_type()?,
2039 )?;
2040 }
2041
2042 Ok(())
2043 }
2044
2045 fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
2046 QueryCursor {
2047 binding: self.binding,
2048 position: position.to_vec(),
2049 resume,
2050 }
2051 }
2052}
2053
2054fn consume_index_component(
2056 entity: &EntitySchema,
2057 index: &IndexSchema,
2058 name: &str,
2059 remaining: &mut &[u8],
2060) -> Result<(), Error> {
2061 let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
2062
2063 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
2064}
2065
2066#[inline(never)]
2069#[expect(
2070 clippy::needless_pass_by_value,
2071 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
2072)]
2073fn fetch_rows<M: Memory>(
2074 db: &Database<M>,
2075 entity: &EntitySchema,
2076 request: Request<'_>,
2077 projection: Option<Projection<'_>>,
2078) -> Result<QueryPage<Vec<u8>>, Error> {
2079 db.schema.admits(entity)?;
2080 let plan = Plan::admit(
2081 entity,
2082 &request,
2083 db.schema.fingerprint(),
2084 db.incarnation,
2085 projection,
2086 PlanOutput::Rows,
2087 )?;
2088
2089 execute(&db.map, entity, &request, &plan, None)
2090}
2091
2092fn execute<M: Memory>(
2093 map: &Map<M>,
2094 entity: &EntitySchema,
2095 request: &Request<'_>,
2096 plan: &Plan<'_>,
2097 mut aggregate: Option<aggregate::Accumulator<'_>>,
2098) -> Result<QueryPage<Vec<u8>>, Error> {
2099 execute_inner(
2100 map,
2101 entity,
2102 request,
2103 plan,
2104 range::bounds(entity, request, plan)?,
2105 aggregate.as_mut(),
2106 None,
2107 )
2108}
2109
2110const STEP_INPUT_BYTES: usize = 64 * 1024;
2113const fn candidate_byte_limit(row_bytes: usize) -> usize {
2114 row_bytes + 2 * crate::MAX_INDEX_KEY_BYTES
2115}
2116
2117fn execute_inner<M: Memory>(
2118 map: &Map<M>,
2119 entity: &EntitySchema,
2120 request: &Request<'_>,
2121 plan: &Plan<'_>,
2122 bounds: Option<range::Bounds>,
2123 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
2124 mut input_bytes: Option<&mut usize>,
2125) -> Result<QueryPage<Vec<u8>>, Error> {
2126 let mut page = QueryPage {
2127 rows: Vec::new(),
2128 next: None,
2129 examined: 0,
2130 fetched: 0,
2131 output_bytes: 0,
2132 };
2133 let Some(bounds) = bounds else {
2134 return Ok(page);
2135 };
2136 let terminal = range::terminal_key(&bounds, plan.descending);
2137 let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
2138 let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
2139 Some(distinct::Collection::new(
2140 plan.projection.ok_or(Error::InvalidQuery)?,
2141 key_fields,
2142 ))
2143 } else {
2144 None
2145 };
2146 let mut sorted = plan
2147 .sort
2148 .as_ref()
2149 .map(|_| sort::Collection::new(request, plan.distinct));
2150 let mut component = Vec::new();
2151 let mut right_component = Vec::new();
2152 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
2154 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
2155 } else {
2156 None
2157 };
2158 let candidate_bytes = candidate_byte_limit(entity.max_row_bytes);
2159 let primary_type = entity.fields[plan.primary].value;
2160 let needs_spans = plan.index.is_some()
2161 || plan.span_fields != 0
2162 || match &aggregate {
2163 Some(accumulator) => accumulator.needs_spans(),
2164 None => plan.projection.is_some(),
2165 };
2166 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
2168 while let Some(entry) = if plan.descending {
2169 entries.next_back()
2170 } else {
2171 entries.next()
2172 } {
2173 if request.work == 0 {
2177 return Err(Error::Limit);
2178 }
2179 page.examined += 1;
2180 let stored_key = entry.key();
2181 let mut read_bytes = stored_key.len();
2182 let (owner, bytes) = if plan.index.is_some() {
2183 let owner_bytes = entry.value();
2184 read_bytes += owner_bytes.len();
2185 read_index_owner(map, entity.id, primary_type, &owner_bytes)?
2186 } else {
2187 (
2188 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
2189 entry.value(),
2190 )
2191 };
2192 if let Some(used) = input_bytes.as_deref_mut() {
2193 read_bytes += bytes.len();
2194 if read_bytes > candidate_bytes {
2195 return Err(Error::Corrupt);
2196 }
2197 *used += read_bytes;
2198 }
2199 page.fetched += 1;
2200 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
2201 entity.inspect_fields(
2202 &bytes,
2203 plan.selected,
2204 &mut values,
2205 needs_spans.then_some(&mut spans),
2206 )?;
2207 if RowKey::from_index(values[plan.primary])? != owner {
2208 return Err(Error::Corrupt);
2209 }
2210 if plan.index.is_some() {
2211 validate_index_entry(
2212 entity,
2213 &entity.row_info(&values, &bytes, &spans)?,
2214 owner,
2215 stored_key,
2216 )?;
2217 }
2218 let read = |position: usize, member: Option<crate::member::RecordMember>| {
2219 if let Some(member) = member {
2220 let (start, end) = spans[position];
2221 member.read(
2222 &bytes[usize::from(start)..usize::from(end)],
2223 entity.fields[position].optional,
2224 )
2225 } else {
2226 Ok(values[position])
2227 }
2228 };
2229 let mut accepts = |term: &Term, supplied: &QueryOperand<'_>| -> Result<bool, Error> {
2230 let mut value = values[term.position];
2231 component.clear();
2232 let (operand, optional) = match &term.operand {
2233 TermOperand::Nested {
2234 member,
2235 literal,
2236 absent,
2237 } => {
2238 value = read(term.position, Some(*member))?;
2239 if *absent {
2240 return Ok(term.comparison.accepts_absent(value == IndexValue::Absent));
2241 }
2242 (
2243 Some(literal.as_slice()),
2244 entity.fields[term.position].optional || member.field().optional,
2245 )
2246 }
2247 TermOperand::Literal { absent: true, .. } => {
2248 let absent = if plan.span_fields & (1 << term.position) != 0 {
2249 bytes[usize::from(spans[term.position].0)] == 0
2250 } else {
2251 value == IndexValue::Absent
2252 };
2253
2254 return Ok(term.comparison.accepts_absent(absent));
2255 }
2256 TermOperand::Member { item, needle } => {
2257 let needle = match (needle, supplied) {
2258 (MemberNeedle::Literal(_), QueryOperand::Literal(value)) => *value,
2259 (MemberNeedle::Field(right, member), QueryOperand::Field(_)) => {
2260 read(*right, *member)?
2261 }
2262 _ => return Err(Error::Corrupt),
2263 };
2264 if needle == IndexValue::Absent {
2265 return Ok(false);
2266 }
2267 let (start, end) = spans[term.position];
2268
2269 return contains_member(
2270 &bytes[usize::from(start)..usize::from(end)],
2271 entity.fields[term.position].optional,
2272 *item,
2273 needle,
2274 );
2275 }
2276 TermOperand::Length { member, threshold } => {
2277 let (start, end) = spans[term.position];
2278 let span = &bytes[usize::from(start)..usize::from(end)];
2279 let optional = entity.fields[term.position].optional;
2280 let actual = if let Some(member) = member {
2281 match member.read(span, optional)? {
2282 IndexValue::Absent => None,
2283 value => Some(scalar_bytes(value).ok_or(Error::Corrupt)?.len() as u32),
2284 }
2285 } else {
2286 crate::codec::validated_length(span, optional)
2287 };
2288
2289 return Ok(term.comparison.accepts_length(actual, *threshold));
2290 }
2291 TermOperand::Literal {
2292 bytes,
2293 absent: false,
2294 } => (
2295 Some(bytes.as_slice()),
2296 entity.fields[term.position].optional,
2297 ),
2298 TermOperand::Field {
2299 right,
2300 left_member,
2301 right_member,
2302 } => {
2303 value = read(term.position, *left_member)?;
2304 let rhs = read(*right, *right_member)?;
2305 if value == IndexValue::Absent || rhs == IndexValue::Absent {
2306 return Ok(term.comparison.accepts_absent(value == rhs));
2307 }
2308 if let Some(matches) = term.comparison.accepts_values(value, rhs) {
2309 return Ok(matches);
2310 }
2311 right_component.clear();
2312 rhs.append_component(false, &mut right_component);
2313
2314 (Some(right_component.as_slice()), false)
2315 }
2316 };
2317 if let QueryOperand::Literal(right) = supplied
2318 && let Some(matches) = term.comparison.accepts_values(value, *right)
2319 {
2320 return Ok(matches);
2321 }
2322 value.append_component(optional, &mut component);
2323
2324 Ok(term.comparison.accepts(
2325 (value != IndexValue::Absent).then_some(component.as_slice()),
2326 operand,
2327 optional,
2328 ))
2329 };
2330 let matches = 'matches: {
2331 let mut clause_matches = false;
2332 for (term, predicate) in plan.terms.iter().zip(&request.predicates) {
2333 clause_matches = clause_matches || accepts(term, &predicate.operand)?;
2334 if !term.or_next {
2335 if !clause_matches {
2336 break 'matches false;
2337 }
2338 clause_matches = false;
2339 }
2340 }
2341
2342 true
2343 };
2344 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
2345 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2346 if matches && let Some(accumulator) = aggregate.as_mut() {
2347 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2348 if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
2349 return Ok(page);
2351 }
2352 } else if matches && let Some(collection) = collected.as_mut() {
2353 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2354 if request.single_result_probe == Some(SingleResult::First) {
2356 break;
2357 }
2358 } else if matches && let Some(collection) = sorted.as_mut() {
2359 collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2360 request.check_result_count(collection.result_count())?;
2362 } else if matches && !duplicate {
2363 request.check_result_count(page.rows.len() + 1)?;
2364 let size = plan
2365 .projection
2366 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2367 if size > request.bytes {
2368 return Err(Error::RowTooLarge);
2369 }
2370 if size > request.bytes - page.output_bytes {
2371 page.next = Some(plan.cursor(stored_key, Resume::Retry));
2372
2373 return Ok(page);
2374 }
2375 page.output_bytes += size;
2376 if let Some(mask) = plan.projection {
2377 page.rows.push(copy_projection(&bytes, &spans, mask, size));
2378 } else {
2379 page.rows.push(bytes);
2380 }
2381 if request.single_result_probe == Some(SingleResult::First)
2382 || plan.distinct.finishes_on_match(plan.fixed_components)
2383 {
2384 return Ok(page);
2385 }
2386 if let Some(boundary) = boundary {
2387 previous = Some(boundary.to_vec());
2388 }
2389 }
2390 if page.rows.len() == request.rows
2391 || page.examined == request.work
2392 || input_bytes
2393 .as_deref()
2394 .is_some_and(|used| *used > STEP_INPUT_BYTES - candidate_bytes)
2395 {
2396 if terminal == Some(stored_key) {
2397 break;
2398 }
2399 if request.single_result_probe == Some(SingleResult::First)
2400 || (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}