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