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(crate) 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 serializer.serialize_bytes(&self.to_bytes())
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_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<QueryCursor, E> {
333 QueryCursor::from_bytes(bytes).map_err(E::custom)
334 }
335
336 fn visit_seq<A: serde::de::SeqAccess<'de>>(
337 self,
338 mut seq: A,
339 ) -> Result<QueryCursor, A::Error> {
340 let size = seq.size_hint().unwrap_or(0);
341 if size > QueryCursor::MAX_ENCODED_BYTES {
342 return Err(serde::de::Error::custom(Error::InvalidCursor));
343 }
344 let mut frame = Vec::with_capacity(size);
345 while let Some(byte) = seq.next_element()? {
346 if frame.len() == QueryCursor::MAX_ENCODED_BYTES {
347 return Err(serde::de::Error::custom(Error::InvalidCursor));
348 }
349 frame.push(byte);
350 }
351 QueryCursor::from_bytes(&frame).map_err(serde::de::Error::custom)
352 }
353 }
354
355 deserializer.deserialize_bytes(Frame)
356 }
357}
358
359#[derive(Debug)]
362pub struct QueryPage<T> {
363 pub rows: Vec<T>,
365 pub next: Option<QueryCursor>,
367 pub examined: usize,
369 pub fetched: usize,
371 pub output_bytes: usize,
373}
374
375impl QueryPage<Vec<u8>> {
376 #[inline(never)]
377 pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
378 Ok(QueryPage {
379 rows: self
380 .rows
381 .iter()
382 .map(|bytes| E::decode(bytes))
383 .collect::<Result<_, _>>()?,
384 next: self.next,
385 examined: self.examined,
386 fetched: self.fetched,
387 output_bytes: self.output_bytes,
388 })
389 }
390
391 #[inline(never)]
392 fn decode_with<R>(
393 self,
394 decode: impl Fn(&mut Decoder<'_>) -> Result<R, Error>,
395 ) -> Result<QueryPage<R>, Error> {
396 Ok(QueryPage {
397 rows: self
398 .rows
399 .iter()
400 .map(|bytes| {
401 let mut reader = Decoder::new(bytes)?;
402 let row = decode(&mut reader)?;
404 reader.finish()?;
405
406 Ok(row)
407 })
408 .collect::<Result<_, Error>>()?,
409 next: self.next,
410 examined: self.examined,
411 fetched: self.fetched,
412 output_bytes: self.output_bytes,
413 })
414 }
415}
416
417#[derive(Clone, Copy, Debug, PartialEq, Eq)]
419pub enum QueryOperand<'a> {
420 Literal(IndexValue<'a>),
422 Length(u32),
424 Field(&'a str),
426}
427
428struct Predicate<'a> {
429 field: &'a str,
430 comparison: Comparison,
431 operand: QueryOperand<'a>,
432 or_next: bool,
434}
435
436impl<'a> Predicate<'a> {
437 fn compared_field(&self, name: &str) -> Option<&'a str> {
439 let QueryOperand::Field(right) = self.operand else {
440 return None;
441 };
442 if self.field == name {
443 Some(right)
444 } else if right == name {
445 Some(self.field)
446 } else {
447 None
448 }
449 }
450
451 fn at_extreme(&self, entity: &EntitySchema, value: IndexValue<'_>, upper: bool) -> bool {
453 match value {
454 IndexValue::Bool(b) => b == upper,
455 IndexValue::UnitEnum { ordinal, .. } => entity
456 .index_field(self.field)
457 .is_some_and(|field| key::is_fixed_extreme(field.value, &[ordinal], upper)),
458 IndexValue::Text("") | IndexValue::Blob([]) => !upper,
459 _ => value.is_integer_extreme(upper),
460 }
461 }
462
463 fn fixed_equality(&self, entity: &EntitySchema) -> Option<(&'a str, IndexValue<'a>)> {
465 if let QueryOperand::Length(n) = self.operand {
466 let empty = self
467 .comparison
468 .empty_length_value(n, entity.index_field(self.field)?.value)?;
469 return Some((self.field, empty));
470 }
471 let QueryOperand::Literal(value) = self.operand else {
472 return None;
473 };
474 let fixed = match (self.comparison, value) {
476 (Comparison::Eq, _) => value,
477 (Comparison::Ne, IndexValue::Bool(excluded))
478 if entity.field_is_required(self.field) =>
479 {
480 IndexValue::Bool(!excluded)
481 }
482 (cmp @ (Comparison::Ge | Comparison::Le), _)
483 if self.at_extreme(entity, value, cmp == Comparison::Ge) =>
484 {
485 value
486 }
487 (Comparison::Gt, IndexValue::Bool(false)) => IndexValue::Bool(true),
488 (Comparison::Lt, IndexValue::Bool(true)) => IndexValue::Bool(false),
489 _ => return None,
490 };
491 Some((self.field, fixed))
492 }
493
494 fn tests_presence(&self, entity: &EntitySchema, operand: &TermOperand) -> bool {
496 match (self.comparison, self.operand) {
497 (Comparison::Ne, QueryOperand::Literal(IndexValue::Absent)) => true,
498 (cmp @ (Comparison::Le | Comparison::Ge), QueryOperand::Literal(value)) => {
499 self.at_extreme(entity, value, cmp == Comparison::Le)
500 }
501 (_, QueryOperand::Length(_)) => {
502 self.present_length_result(entity) == Some(true)
503 && self.comparison != Comparison::Ne
504 }
505 (
506 Comparison::Le
507 | Comparison::Ge
508 | Comparison::StartsWith
509 | Comparison::EndsWith
510 | Comparison::Contains,
511 QueryOperand::Field(right),
512 ) => right == self.field,
513 (
514 Comparison::StartsWith | Comparison::EndsWith | Comparison::Contains,
515 QueryOperand::Literal(needle),
516 ) => {
517 !matches!(operand, TermOperand::Member { .. })
519 && scalar_bytes(needle).is_some_and(<[u8]>::is_empty)
520 }
521 _ => false,
522 }
523 }
524
525 fn present_length_result(&self, entity: &EntitySchema) -> Option<bool> {
527 let QueryOperand::Length(n) = self.operand else {
528 return None;
529 };
530 let max = length_limit(entity.index_field(self.field)?.value)?;
531 self.comparison.uniform_length_result(0, max, n)
532 }
533
534 fn constant_comparison(&self, entity: &EntitySchema) -> Option<bool> {
535 if let QueryOperand::Literal(value) = self.operand {
536 return match (self.comparison, value) {
538 (cmp @ (Comparison::Lt | Comparison::Gt), value)
539 if self.at_extreme(entity, value, cmp == Comparison::Gt) =>
540 {
541 Some(false)
542 }
543 _ => None,
544 };
545 }
546 if matches!(self.operand, QueryOperand::Length(_)) {
547 let result = self.present_length_result(entity)?;
548 return (result == self.comparison.accepts_absent(false)
549 || entity.field_is_required(self.field))
550 .then_some(result);
551 }
552 if !matches!(self.operand, QueryOperand::Field(right) if right == self.field) {
553 return None;
554 }
555 match self.comparison {
556 Comparison::Eq => Some(true),
557 Comparison::Ne | Comparison::Lt | Comparison::Gt => Some(false),
558 _ => None,
559 }
560 }
561}
562
563#[derive(Clone, Copy, PartialEq, Eq)]
564enum SingleResult {
565 First,
566 Only,
567}
568
569struct Request<'a> {
570 groups: aggregate::GroupRequest<'a>,
571 predicates: Vec<Predicate<'a>>,
572 index: Option<(&'a str, Vec<IndexValue<'a>>)>,
573 order: Option<Vec<&'a str>>,
574 order_descending: u8,
575 descending: bool,
576 distinct: bool,
577 single_result_probe: Option<SingleResult>,
578 rows: usize,
579 work: usize,
580 bytes: usize,
581 cursor: Option<&'a QueryCursor>,
582 over_limit: bool,
583}
584
585impl Default for Request<'_> {
586 fn default() -> Self {
587 Self {
588 groups: aggregate::GroupRequest::default(),
589 predicates: Vec::new(),
590 index: None,
591 order: None,
592 order_descending: 0,
593 descending: false,
594 distinct: false,
595 single_result_probe: None,
596 rows: 32,
597 work: 128,
598 bytes: MAX_OUTPUT,
599 cursor: None,
600 over_limit: false,
601 }
602 }
603}
604
605impl<'a> Request<'a> {
608 fn check_result_count(&self, count: usize) -> Result<(), Error> {
611 if self.single_result_probe == Some(SingleResult::Only) && count > 1 {
612 return Err(Error::MultipleMatches);
613 }
614 Ok(())
615 }
616
617 fn fixed_equalities<'r>(
619 &'r self,
620 entity: &'r EntitySchema,
621 ) -> impl Iterator<Item = (&'a str, IndexValue<'a>)> + 'r {
622 self.clauses().filter_map(move |clause| {
623 let (predicate, rest) = clause.split_first()?;
624 if !rest.is_empty() {
625 let mut candidate = predicate.fixed_equality(entity)?;
626 for alternative in rest {
627 let other = alternative.fixed_equality(entity)?;
628 if candidate.0 != other.0 {
629 return None;
630 }
631 if equal_values(candidate.1, other.1) {
632 continue;
633 }
634 if self.predicates.len() == clause.len() {
635 return None;
636 }
637 if self.excludes_literal(other.0, other.1) {
638 continue;
639 }
640 if !self.excludes_literal(candidate.0, candidate.1) {
641 return None;
642 }
643 candidate = other;
644 }
645 return Some(candidate);
648 }
649 if let Some(equality) = predicate.fixed_equality(entity) {
650 return Some(equality);
651 }
652 let QueryOperand::Literal(value) = predicate.operand else {
656 return None;
657 };
658 let lower = match predicate.comparison {
659 Comparison::Ge => value,
660 Comparison::Gt if self.predicates.len() > 1 => value.discrete_successor()?,
661 _ => return None,
662 };
663 self.clauses()
664 .any(|clause| {
665 let [upper] = clause else { return false };
666 if upper.field != predicate.field {
667 return false;
668 }
669 match (upper.comparison, upper.operand) {
670 (Comparison::Le, QueryOperand::Literal(value)) => {
671 equal_values(lower, value)
672 }
673 (Comparison::Lt, QueryOperand::Literal(value)) => {
674 consecutive_values(lower, value)
675 }
676 _ => false,
677 }
678 })
679 .then_some((predicate.field, lower))
680 })
681 }
682
683 fn excludes_literal(&self, field: &str, value: IndexValue<'_>) -> bool {
684 self.clauses().any(|clause| {
687 clause.iter().all(|predicate| {
688 if predicate.field != field {
689 return false;
690 }
691 let QueryOperand::Literal(literal) = predicate.operand else {
692 return false;
693 };
694 match predicate.comparison {
695 Comparison::Eq
696 | Comparison::Ne
697 | Comparison::Lt
698 | Comparison::Le
699 | Comparison::Gt
700 | Comparison::Ge => {
701 predicate.comparison.accepts_fixed_values(value, literal) == Some(false)
702 }
703 _ => false,
704 }
705 })
706 })
707 }
708
709 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
710 self.predicates.split_inclusive(|p| !p.or_next)
711 }
712
713 #[inline(never)]
714 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
715 if self.predicates.len() == MAX_TERMS {
716 self.over_limit = true;
717 } else {
718 self.predicates.push(Predicate {
719 field,
720 comparison,
721 operand,
722 or_next: false,
723 });
724 }
725 }
726
727 #[inline(never)]
728 fn or_clause(
729 &mut self,
730 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
731 ) {
732 let count = alternatives.len();
733
734 if count == 0 || count > MAX_TERMS - self.predicates.len() {
735 self.over_limit = true;
736 } else {
737 self.predicates.extend(alternatives.enumerate().map(
738 |(i, (field, comparison, operand))| Predicate {
739 field,
740 comparison,
741 operand,
742 or_next: i + 1 < count,
743 },
744 ));
745 }
746 }
747
748 #[inline(never)]
749 fn filter_not_in(
750 &mut self,
751 field: &'a str,
752 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
753 ) {
754 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
755 self.over_limit = true;
756
757 return;
758 }
759 for value in values {
760 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
761 }
762 }
763
764 #[inline(never)]
765 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
766 if values.len() > 4 {
767 self.over_limit = true;
768 } else {
769 self.index = Some((name, values.to_vec()));
770 }
771 }
772
773 #[inline(never)]
774 fn order_by(&mut self, fields: &[&'a str]) {
775 self.order_descending = 0;
776
777 if fields.len() > 4 {
778 self.over_limit = true;
779 } else {
780 self.order = Some(fields.to_vec());
781 }
782 }
783
784 #[inline(never)]
785 fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
786 if fields.len() > 4 {
787 self.over_limit = true;
788
789 return;
790 }
791 self.order = Some(Vec::with_capacity(fields.len()));
792 self.order_descending = 0;
793 for &(field, direction) in fields {
794 self.append_order(field, direction);
795 }
796 }
797
798 fn append_order(&mut self, field: &'a str, direction: SortDirection) {
799 let fields = self.order.get_or_insert_with(Vec::new);
800 if fields.len() == 4 {
801 self.over_limit = true;
802
803 return;
804 }
805 if direction == SortDirection::Descending {
806 self.order_descending |= 1 << fields.len();
807 }
808 fields.push(field);
809 }
810
811 fn primary_descending(&self, entity: &EntitySchema) -> bool {
812 self.order_descending != 0
813 && self.order.as_ref().is_some_and(|fields| {
814 fields.last() == Some(&entity.primary_key)
815 && self.order_descending & (1 << (fields.len() - 1)) != 0
816 })
817 }
818}
819
820pub(super) fn source_page<M: Memory>(
822 map: &Map<M>,
823 entity: &EntitySchema,
824 binding: [u8; 32],
825 incarnation: [u8; 16],
826 cursor: Option<&QueryCursor>,
827 rows: usize,
828 bytes: usize,
829) -> Result<QueryPage<Vec<u8>>, Error> {
830 let request = Request {
831 rows,
832 work: rows,
833 bytes,
834 cursor,
835 ..Request::default()
836 };
837 let plan = Plan::admit(
838 entity,
839 &request,
840 binding,
841 incarnation,
842 None,
843 PlanOutput::Rows,
844 )?;
845
846 execute(map, entity, &request, &plan, None)
847}
848
849enum QuerySource<'a, M: Memory> {
850 Direct(&'a Database<M>),
851 Session(Rc<RefCell<Database<M>>>),
852}
853
854enum QueryRead<'a, M: Memory> {
855 Direct(&'a Database<M>),
856 Session(Ref<'a, Database<M>>),
857}
858
859impl<M: Memory> Deref for QueryRead<'_, M> {
860 type Target = Database<M>;
861
862 fn deref(&self) -> &Self::Target {
863 match self {
864 Self::Direct(db) => db,
865 Self::Session(db) => db,
866 }
867 }
868}
869
870impl<M: Memory> QuerySource<'_, M> {
871 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
872 match self {
873 Self::Direct(db) => Ok(QueryRead::Direct(db)),
874 Self::Session(db) => db
875 .try_borrow()
876 .map(QueryRead::Session)
877 .map_err(|_| Error::BorrowConflict),
878 }
879 }
880}
881
882pub struct Query<'a, E, M: Memory> {
886 db: QuerySource<'a, M>,
887 request: Request<'a>,
888 entity: PhantomData<E>,
889}
890impl<M: Memory> Database<M> {
891 #[must_use]
893 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
894 Query {
895 db: QuerySource::Direct(self),
896 entity: PhantomData,
897 request: Request::default(),
898 }
899 }
900}
901impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
902 pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
903 Self {
904 db: QuerySource::Session(db),
905 request: Request::default(),
906 entity: PhantomData,
907 }
908 }
909
910 #[must_use]
924 pub fn distinct(mut self) -> Self {
925 self.request.distinct = true;
926
927 self
928 }
929
930 #[must_use]
943 pub fn filter(
944 mut self,
945 field: &'a str,
946 comparison: Comparison,
947 value: impl Into<IndexValue<'a>>,
948 ) -> Self {
949 self.request
950 .filter(field, comparison, QueryOperand::Literal(value.into()));
951
952 self
953 }
954
955 #[must_use]
957 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
958 self.filter(field, Comparison::Eq, value)
959 }
960
961 #[must_use]
963 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
964 self.filter(field, Comparison::Ne, value)
965 }
966
967 #[must_use]
969 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
970 self.filter(field, Comparison::Lt, value)
971 }
972
973 #[must_use]
975 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
976 self.filter(field, Comparison::Le, value)
977 }
978
979 #[must_use]
981 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
982 self.filter(field, Comparison::Gt, value)
983 }
984
985 #[must_use]
987 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
988 self.filter(field, Comparison::Ge, value)
989 }
990
991 #[must_use]
999 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
1000 self.request
1001 .filter(left, comparison, QueryOperand::Field(right));
1002
1003 self
1004 }
1005
1006 #[must_use]
1011 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
1012 self.request
1013 .filter(field, comparison, QueryOperand::Length(length));
1014
1015 self
1016 }
1017
1018 #[must_use]
1021 pub fn filter_present(self, field: &'a str) -> Self {
1022 self.filter(field, Comparison::Ne, IndexValue::Absent)
1023 }
1024
1025 #[must_use]
1028 pub fn filter_absent(self, field: &'a str) -> Self {
1029 self.filter(field, Comparison::Eq, IndexValue::Absent)
1030 }
1031
1032 #[must_use]
1039 pub fn filter_between(
1040 self,
1041 field: &'a str,
1042 lower: impl Into<IndexValue<'a>>,
1043 upper: impl Into<IndexValue<'a>>,
1044 ) -> Self {
1045 self.filter(field, Comparison::Ge, lower)
1046 .filter(field, Comparison::Le, upper)
1047 }
1048
1049 #[must_use]
1057 pub fn filter_not_between(
1058 self,
1059 field: &'a str,
1060 lower: impl Into<IndexValue<'a>>,
1061 upper: impl Into<IndexValue<'a>>,
1062 ) -> Self {
1063 self.filter_any(&[
1064 (field, Comparison::Lt, lower.into()),
1065 (field, Comparison::Gt, upper.into()),
1066 ])
1067 }
1068
1069 #[must_use]
1074 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1075 self.filter_fields(field, Comparison::Ge, lower)
1076 .filter_fields(field, Comparison::Le, upper)
1077 }
1078
1079 #[must_use]
1084 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1085 self.filter_any_operands(&[
1086 (field, Comparison::Lt, QueryOperand::Field(lower)),
1087 (field, Comparison::Gt, QueryOperand::Field(upper)),
1088 ])
1089 }
1090
1091 #[must_use]
1099 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
1100 self.request.or_clause(
1101 alternatives
1102 .iter()
1103 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
1104 );
1105
1106 self
1107 }
1108
1109 #[must_use]
1114 pub fn filter_any_operands(
1115 mut self,
1116 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
1117 ) -> Self {
1118 self.request.or_clause(alternatives.iter().copied());
1119
1120 self
1121 }
1122
1123 #[must_use]
1133 pub fn filter_in(
1134 mut self,
1135 field: &'a str,
1136 values: &[impl Copy + Into<IndexValue<'a>>],
1137 ) -> Self {
1138 self.request.or_clause(
1139 values
1140 .iter()
1141 .copied()
1142 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
1143 );
1144
1145 self
1146 }
1147
1148 #[must_use]
1156 pub fn filter_not_in(
1157 mut self,
1158 field: &'a str,
1159 values: &[impl Copy + Into<IndexValue<'a>>],
1160 ) -> Self {
1161 self.request
1162 .filter_not_in(field, values.iter().copied().map(Into::into));
1163
1164 self
1165 }
1166
1167 #[must_use]
1172 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
1173 self.request.using_index(name, values);
1174
1175 self
1176 }
1177
1178 #[must_use]
1181 pub fn order_asc(mut self, field: &'a str) -> Self {
1182 self.request.append_order(field, SortDirection::Ascending);
1183
1184 self
1185 }
1186
1187 #[must_use]
1190 pub fn order_desc(mut self, field: &'a str) -> Self {
1191 self.request.append_order(field, SortDirection::Descending);
1192
1193 self
1194 }
1195
1196 #[must_use]
1207 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
1208 self.request.order_by(fields);
1209
1210 self
1211 }
1212
1213 #[must_use]
1218 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
1219 self.request.order_by_each(fields);
1220
1221 self
1222 }
1223
1224 #[must_use]
1226 pub fn descending(mut self) -> Self {
1227 self.request.descending = true;
1228
1229 self
1230 }
1231
1232 #[must_use]
1239 pub fn limit(mut self, rows: usize) -> Self {
1240 self.request.rows = rows;
1241
1242 self
1243 }
1244
1245 #[must_use]
1247 pub fn work_limit(mut self, candidates: usize) -> Self {
1248 self.request.work = candidates;
1249
1250 self
1251 }
1252
1253 #[cfg(feature = "test-support")]
1255 #[doc(hidden)]
1256 #[must_use]
1257 pub fn test_output_limit(mut self, bytes: usize) -> Self {
1258 self.request.bytes = bytes;
1259
1260 self
1261 }
1262
1263 #[must_use]
1265 pub fn after(self, cursor: &'a QueryCursor) -> Self {
1266 self.after_optional(Some(cursor))
1267 }
1268
1269 #[must_use]
1271 pub fn after_optional(mut self, cursor: Option<&'a QueryCursor>) -> Self {
1272 self.request.cursor = cursor;
1273
1274 self
1275 }
1276
1277 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
1284 observe!(query, { self.entity_page() })
1285 }
1286
1287 fn entity_page(self) -> Result<QueryPage<E>, Error> {
1288 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
1289 }
1290
1291 pub fn first(self) -> Result<Option<E>, Error> {
1297 self.first_with(Self::entity_page)
1298 }
1299
1300 pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
1304 self.first_with(Self::projected_page::<R>)
1305 }
1306
1307 fn first_with<R>(
1308 self,
1309 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1310 ) -> Result<Option<R>, Error> {
1311 observe!(query, { fetch(self.probe_matches(SingleResult::First)?) })
1312 .map(|mut page| page.rows.pop())
1313 }
1314
1315 pub fn try_one(self) -> Result<Option<E>, Error> {
1322 self.try_one_with(Self::entity_page)
1323 }
1324
1325 pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
1331 self.try_one_with(Self::projected_page::<R>)
1332 }
1333
1334 fn try_one_with<R>(
1335 self,
1336 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1337 ) -> Result<Option<R>, Error> {
1338 observe!(query, {
1339 if self.request.cursor.is_some() {
1340 return Err(Error::InvalidQuery);
1341 }
1342 fetch(self.probe_matches(SingleResult::Only)?)
1343 })
1344 .map(|mut page| page.rows.pop())
1345 }
1346
1347 fn probe_matches(mut self, probe: SingleResult) -> Result<Self, Error> {
1348 if !(1..=32).contains(&self.request.rows) {
1349 return Err(Error::Limit);
1350 }
1351
1352 self.request.single_result_probe = Some(probe);
1353
1354 Ok(self.limit(match probe {
1355 SingleResult::First => 1,
1356 SingleResult::Only => 2,
1357 }))
1358 }
1359
1360 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1370 observe!(query, { self.projected_page() })
1371 }
1372
1373 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1374 let raw = fetch_rows(
1375 &*self.db.read()?,
1376 E::SCHEMA,
1377 self.request,
1378 Some(Projection::Record(R::definition())),
1379 )?;
1380
1381 raw.decode_with(R::decode_from)
1382 }
1383}
1384
1385#[derive(Clone, Copy)]
1386enum Projection<'a> {
1387 Record(&'a TypeSchema),
1388 Columns(&'a [u8]),
1389}
1390
1391impl Projection<'_> {
1392 fn mask(self, entity: &EntitySchema) -> Result<u32, Error> {
1393 match self {
1394 Self::Record(record) => admit_projection(entity, record),
1395 Self::Columns(columns) => {
1396 let mut mask = 0;
1397 for &column in columns {
1398 if usize::from(column) >= entity.fields.len() || mask & (1 << column) != 0 {
1399 return Err(Error::InvalidQuery);
1400 }
1401 mask |= 1 << column;
1402 }
1403 Ok(mask)
1404 }
1405 }
1406 }
1407}
1408
1409fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u32, Error> {
1413 let TypeBody::Record(fields) = &output.body else {
1414 return Err(Error::InvalidQuery);
1415 };
1416 if fields.is_empty()
1417 || fields.len() > crate::schema::MAX_FIELDS
1418 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1419 {
1420 return Err(Error::InvalidQuery);
1421 }
1422 let mut source = TypeGraph::default();
1423 let mut target = TypeGraph::default();
1424 let mut mask = 0;
1425 for field in *fields {
1426 let position = entity
1427 .field_position(field.name)
1428 .ok_or(Error::InvalidQuery)?;
1429 let stored = &entity.fields[position];
1430 if stored.value != field.value || stored.optional != field.optional {
1431 return Err(Error::InvalidQuery);
1432 }
1433 source
1434 .include(stored.value)
1435 .map_err(|_| Error::InvalidQuery)?;
1436 target
1437 .include(field.value)
1438 .map_err(|_| Error::InvalidQuery)?;
1439 mask |= 1 << position;
1440 }
1441 if !source.contains(&target) {
1442 return Err(Error::InvalidQuery);
1443 }
1444
1445 Ok(mask)
1446}
1447
1448struct Term {
1449 tests_presence: bool,
1450 position: usize,
1451 comparison: Comparison,
1452 operand: TermOperand,
1453 or_next: bool,
1454}
1455
1456enum TermOperand {
1457 Literal {
1458 bytes: Vec<u8>,
1459 absent: bool,
1460 },
1461 Member {
1462 item: FieldType,
1463 needle: MemberNeedle,
1464 },
1465 Nested {
1466 member: crate::member::RecordMember,
1467 literal: Vec<u8>,
1468 absent: bool,
1469 },
1470 Field {
1471 right: usize,
1472 left_member: Option<crate::member::RecordMember>,
1473 right_member: Option<crate::member::RecordMember>,
1474 },
1475 Length {
1476 member: Option<crate::member::RecordMember>,
1477 threshold: u32,
1478 },
1479}
1480
1481enum MemberNeedle {
1482 Literal(Vec<u8>),
1483 Field(usize, Option<crate::member::RecordMember>),
1484}
1485
1486fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1489 match value {
1490 IndexValue::Text(text) => Some(text.as_bytes()),
1491 IndexValue::Blob(bytes) => Some(bytes),
1492 _ => None,
1493 }
1494}
1495
1496fn consecutive_values(low: IndexValue<'_>, high: IndexValue<'_>) -> bool {
1497 low.discrete_successor()
1498 .is_some_and(|next| equal_values(next, high))
1499}
1500
1501fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1502 match (left, right) {
1504 (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1505 a == b
1506 }
1507 _ => left == right,
1508 }
1509}
1510
1511fn length_limit(field: FieldType) -> Option<u32> {
1512 match key::operand_type(field) {
1513 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1514 FieldType::List { max_items, .. } => Some(max_items),
1515 FieldType::Named(link) => match (link.definition)().body {
1516 TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1517 _ => None,
1518 },
1519 _ => None,
1520 }
1521}
1522
1523fn member_type(field: FieldType) -> Option<FieldType> {
1524 match key::operand_type(field) {
1525 FieldType::List { item, .. } => Some(*item),
1526 FieldType::Named(link) => match (link.definition)().body {
1527 TypeBody::Set { item, .. } => Some(item),
1528 _ => None,
1529 },
1530 _ => None,
1531 }
1532}
1533
1534fn contains_member(
1536 span: &[u8],
1537 optional: bool,
1538 item: FieldType,
1539 needle: IndexValue<'_>,
1540) -> Result<bool, Error> {
1541 let mut reader = Decoder::new(span)?;
1542 if optional && !reader.boolean()? {
1543 return Ok(false);
1544 }
1545 for _ in 0..reader.nat32()? {
1546 let value = IndexValue::read(&mut reader, item)?;
1547 if equal_values(value, needle) {
1548 return Ok(true);
1549 }
1550 }
1551
1552 Ok(false)
1553}
1554
1555fn projection_positions(mut mask: u32) -> impl Iterator<Item = usize> {
1558 std::iter::from_fn(move || {
1559 if mask == 0 {
1560 return None;
1561 }
1562 let position = mask.trailing_zeros() as usize;
1563 mask &= mask - 1;
1564 Some(position)
1565 })
1566}
1567
1568fn admit_ordered_fields(entity: &EntitySchema, mask: u32) -> Result<(), Error> {
1569 for i in projection_positions(mask) {
1570 if !key::supports(entity.fields[i].value) {
1571 return Err(Error::InvalidQuery);
1572 }
1573 }
1574
1575 Ok(())
1576}
1577
1578fn comparison_key(
1580 entity: &EntitySchema,
1581 mask: u32,
1582 values: &[IndexValue<'_>],
1583 scratch: &mut Vec<u8>,
1584) -> Result<(), Error> {
1585 build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1586}
1587
1588fn build_comparison_key<'a>(
1589 entity: &EntitySchema,
1590 mask: u32,
1591 key: &mut Vec<u8>,
1592 mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1593) -> Result<(), Error> {
1594 key.clear();
1595 for i in projection_positions(mask) {
1596 let field = &entity.fields[i];
1597 value(i, field)?.append_component(field.optional, key);
1598 if key.len() > MAX_COMPARISON_KEY {
1599 return Err(Error::Limit);
1600 }
1601 }
1602
1603 Ok(())
1604}
1605
1606fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1607 if size > limit {
1608 return Err(Error::RowTooLarge);
1609 }
1610 if size > limit - *used {
1611 return Err(Error::Limit);
1612 }
1613 *used += size;
1614
1615 Ok(())
1616}
1617
1618fn projection_size(spans: &[(u16, u16)], mask: u32) -> usize {
1620 projection_positions(mask)
1621 .map(|i| {
1622 let (start, end) = spans[i];
1623 usize::from(end - start)
1624 })
1625 .sum()
1626}
1627
1628fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u32, size: usize) -> Vec<u8> {
1629 let mut output = Vec::with_capacity(size);
1630 for i in projection_positions(mask) {
1631 let (start, end) = spans[i];
1632 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1633 }
1634
1635 output
1636}
1637#[derive(Clone, Copy)]
1638enum PlanOutput {
1639 Rows,
1640 Aggregate { grouped: bool },
1641}
1642
1643struct Plan<'a> {
1644 primary: usize,
1645 index: Option<&'a IndexSchema>,
1646 prefix: Vec<u8>,
1647 fixed_components: usize,
1648 terms: Vec<Term>,
1649 selected: u32,
1650 span_fields: u32,
1652 binding: [u8; 32],
1653 projection: Option<u32>,
1654 distinct: distinct::Strategy,
1655 sort: Option<Vec<order::SortField>>,
1656 descending: bool,
1657}
1658impl<'a> Plan<'a> {
1659 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1660 self.terms.split_inclusive(|term| !term.or_next)
1661 }
1662
1663 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1664 self.index = Some(path.index);
1665 self.prefix = path.prefix;
1666 self.fixed_components = path.fixed;
1667 self.selected |= entity.key_fields();
1668 }
1669
1670 fn admit(
1671 entity: &'a EntitySchema,
1672 request: &Request<'_>,
1673 schema: [u8; 32],
1674 incarnation: [u8; 16],
1675 projection: Option<Projection<'_>>,
1676 output: PlanOutput,
1677 ) -> Result<Self, Error> {
1678 if request.over_limit
1679 || !(1..=32).contains(&request.rows)
1680 || !(1..=MAX_WORK).contains(&request.work)
1681 || !(1..=MAX_OUTPUT).contains(&request.bytes)
1682 {
1683 return Err(Error::Limit);
1684 }
1685 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1686 {
1687 return Err(Error::InvalidQuery);
1688 }
1689 for value in request
1691 .predicates
1692 .iter()
1693 .filter_map(|p| match &p.operand {
1694 QueryOperand::Literal(value) => Some(value),
1695 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1696 })
1697 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1698 {
1699 if match value {
1700 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1701 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1702 _ => false,
1703 } {
1704 return Err(Error::Limit);
1705 }
1706 }
1707 let primary = entity
1708 .field_position(entity.primary_key)
1709 .filter(|&i| !entity.fields[i].optional)
1710 .ok_or(Error::InvalidQuery)?;
1711 let mut plan = Self {
1712 primary,
1713 index: None,
1714 prefix: prefix(2, entity.id, &[]),
1715 fixed_components: 0,
1716 terms: Vec::new(),
1717 selected: 1 << primary,
1718 span_fields: 0,
1719 binding: [0; 32],
1720 projection: projection.map(|output| output.mask(entity)).transpose()?,
1721 distinct: distinct::Strategy::Identity,
1722 sort: None,
1723 descending: request.descending ^ request.primary_descending(entity),
1724 };
1725 for predicate in &request.predicates {
1726 let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
1727 let field = &entity.fields[position];
1728 let member = if predicate.comparison == Comparison::Contains {
1729 member_type(field.value)
1730 } else {
1731 None
1732 };
1733 let operand = match (predicate.operand, record_member) {
1734 (QueryOperand::Literal(value), Some(member)) => {
1735 if !predicate.comparison.supports_record_member() {
1736 return Err(Error::InvalidQuery);
1737 }
1738 let leaf = member.field();
1739 predicate.comparison.admit(
1740 leaf.value,
1741 field.optional || leaf.optional,
1742 value,
1743 )?;
1744 let mut literal = Vec::new();
1745 value.append_component(field.optional || leaf.optional, &mut literal);
1746 plan.span_fields |= 1 << position;
1747 TermOperand::Nested {
1748 member,
1749 literal,
1750 absent: value == IndexValue::Absent,
1751 }
1752 }
1753 (QueryOperand::Length(length), member) => {
1754 let selected = member.map_or(field.value, |m| m.field().value);
1755 if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1756 return Err(Error::InvalidQuery);
1757 }
1758 plan.span_fields |= 1 << position;
1759
1760 TermOperand::Length {
1761 member,
1762 threshold: length,
1763 }
1764 }
1765 (QueryOperand::Field(name), left_member) => {
1766 let (right, right_member) = crate::member::resolve_field(entity, name)?;
1767 if (left_member.is_some() || right_member.is_some())
1768 && member.is_none()
1769 && !predicate.comparison.supports_record_member()
1770 {
1771 return Err(Error::InvalidQuery);
1772 }
1773 let right_type =
1774 right_member.map_or(entity.fields[right].value, |m| m.field().value);
1775 let left_type =
1776 left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1777 let compatible = left_type == right_type
1778 || matches!(
1779 (left_type, right_type),
1780 (FieldType::Text { .. }, FieldType::Text { .. })
1781 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1782 );
1783 if !compatible
1784 || !key::supports(left_type)
1785 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1786 {
1787 return Err(Error::InvalidQuery);
1788 }
1789 if right_member.is_some() {
1790 plan.span_fields |= 1 << right;
1791 } else {
1792 plan.selected |= 1 << right;
1793 }
1794
1795 if let Some(item) = member {
1796 plan.span_fields |= 1 << position;
1797
1798 TermOperand::Member {
1799 item,
1800 needle: MemberNeedle::Field(right, right_member),
1801 }
1802 } else {
1803 if left_member.is_some() {
1804 plan.span_fields |= 1 << position;
1805 } else {
1806 plan.selected |= 1 << position;
1807 }
1808 TermOperand::Field {
1809 right,
1810 left_member,
1811 right_member,
1812 }
1813 }
1814 }
1815 (QueryOperand::Literal(value), None) => {
1816 if let Some(item) = member {
1817 if !key::supports(item) {
1818 return Err(Error::InvalidQuery);
1819 }
1820 value.admit(item, false)?;
1821 let mut bytes = Vec::new();
1822 value.append_component(false, &mut bytes);
1823 plan.span_fields |= 1 << position;
1824
1825 TermOperand::Member {
1826 item,
1827 needle: MemberNeedle::Literal(bytes),
1828 }
1829 } else {
1830 let absent = value == IndexValue::Absent;
1831 if key::supports(field.value) {
1832 plan.selected |= 1 << position;
1833 } else if absent
1834 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1835 {
1836 plan.span_fields |= 1 << position;
1837 } else {
1838 return Err(Error::InvalidQuery);
1839 }
1840 predicate
1841 .comparison
1842 .admit(field.value, field.optional, value)?;
1843 let mut bytes = Vec::new();
1844 value.append_component(field.optional, &mut bytes);
1845
1846 TermOperand::Literal { bytes, absent }
1847 }
1848 }
1849 };
1850 plan.terms.push(Term {
1851 tests_presence: predicate.tests_presence(entity, &operand),
1852 position,
1853 comparison: predicate.comparison,
1854 operand,
1855 or_next: predicate.or_next,
1856 });
1857 }
1858 match order::select(entity, request, output)? {
1861 order::Path::Primary => {}
1862 order::Path::Index(path, descending) => {
1863 plan.use_index(entity, path);
1864 plan.descending = request.descending ^ descending;
1865 }
1866 order::Path::Filtered { sort } => {
1867 order::select_filtered_path(entity, request, &mut plan, None)?;
1868 for field in sort.iter().flatten() {
1869 if field.member.is_some() {
1870 plan.span_fields |= 1 << field.position;
1871 } else {
1872 plan.selected |= 1 << field.position;
1873 }
1874 }
1875 plan.sort = sort;
1876 }
1877 }
1878 if request.distinct {
1879 plan.distinct = distinct::admit(entity, request, &plan)?;
1880 match plan.distinct {
1881 distinct::Strategy::FirstMatch => plan.sort = None,
1882 distinct::Strategy::Complete { key_fields } => plan.selected |= key_fields,
1883 _ => {}
1884 }
1885 }
1886 let mut hash = Sha256::new();
1887 hash.update(b"ic-db:query:v1\0");
1888 hash.update(schema);
1889 hash.update(incarnation);
1890 hash.update([u8::from(request.descending)]);
1891 hash.update((plan.prefix.len() as u32).to_le_bytes());
1892 hash.update(&plan.prefix);
1893 for term in &plan.terms {
1894 hash.update([term.position as u8, term.comparison as u8]);
1895
1896 match &term.operand {
1897 TermOperand::Nested {
1898 member,
1899 literal,
1900 absent,
1901 } => {
1902 hash.update((u32::MAX - 2).to_le_bytes());
1903 hash.update([member.position() as u8, u8::from(*absent)]);
1904 let literal = &literal[usize::from(
1906 entity.fields[term.position].optional || member.field().optional,
1907 )..];
1908 hash.update((literal.len() as u32).to_le_bytes());
1909 hash.update(literal);
1910 }
1911 TermOperand::Literal { bytes, .. }
1912 | TermOperand::Member {
1913 needle: MemberNeedle::Literal(bytes),
1914 ..
1915 } => {
1916 hash.update((bytes.len() as u32).to_le_bytes());
1917 hash.update(bytes);
1918 }
1919 TermOperand::Length { member, threshold } => {
1920 if let Some(member) = member {
1921 hash.update((u32::MAX - 3).to_le_bytes());
1922 hash.update([member.position() as u8]);
1923 } else {
1924 hash.update((u32::MAX - 1).to_le_bytes());
1925 }
1926 hash.update(threshold.to_le_bytes());
1927 }
1928 TermOperand::Field {
1929 right,
1930 left_member: None,
1931 right_member: None,
1932 }
1933 | TermOperand::Member {
1934 needle: MemberNeedle::Field(right, None),
1935 ..
1936 } => {
1937 hash.update(u32::MAX.to_le_bytes());
1939 hash.update([*right as u8]);
1940 }
1941 TermOperand::Member {
1942 needle: MemberNeedle::Field(right, Some(member)),
1943 ..
1944 } => {
1945 hash.update((u32::MAX - 4).to_le_bytes());
1946 hash.update([u8::MAX, *right as u8, member.position() as u8]);
1947 }
1948 TermOperand::Field {
1949 right,
1950 left_member,
1951 right_member,
1952 } => {
1953 hash.update((u32::MAX - 4).to_le_bytes());
1954 let slot = |member: &Option<crate::member::RecordMember>| {
1955 member.map_or(u8::MAX, |m| m.position() as u8)
1956 };
1957 hash.update([slot(left_member), *right as u8, slot(right_member)]);
1958 }
1959 }
1960 }
1961 let clauses = plan
1964 .terms
1965 .iter()
1966 .enumerate()
1967 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1968 if clauses != 0 {
1969 hash.update(b"or-clauses\0");
1970 hash.update([clauses]);
1971 }
1972 if let Some(order) = &request.order {
1973 hash.update(b"order\0");
1974 hash.update([order.len() as u8]);
1975 for name in order {
1976 if let Some(position) = entity.field_position(name) {
1978 hash.update([position as u8]);
1979 } else {
1980 hash.update([u8::MAX, name.len() as u8]);
1982 hash.update(name.as_bytes());
1983 }
1984 }
1985 }
1986 if request.order_descending != 0 {
1987 hash.update(b"order-directions\0");
1988 hash.update([request.order_descending]);
1989 }
1990 if let Some(mask) = plan.projection {
1993 hash.update(b"projection\0");
1994 hash.update(mask.to_le_bytes());
1995 if let Some(Projection::Columns(columns)) = projection {
1996 hash.update(b"columns\0");
1997 hash.update(columns);
1998 }
1999 }
2000 if request.distinct {
2001 hash.update(b"distinct\0");
2002 }
2003 plan.binding = hash.finalize().into();
2004 if let Some(cursor) = request.cursor {
2005 if cursor.binding != plan.binding {
2006 return Err(Error::InvalidCursor);
2007 }
2008 plan.validate_position(entity, cursor)
2009 .map_err(|_| Error::InvalidCursor)?;
2010 }
2011
2012 Ok(plan)
2013 }
2014
2015 fn validate_position(&self, entity: &EntitySchema, cursor: &QueryCursor) -> Result<(), Error> {
2016 if cursor.resume == Resume::AfterUnemittedClass
2017 && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
2018 {
2019 return Err(Error::InvalidCursor);
2020 }
2021 let bytes = cursor.position.as_slice();
2022 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
2023 return Err(Error::InvalidCursor);
2024 }
2025 if let Some(index) = self.index {
2026 let mut remaining = bytes
2027 .get(INDEX_PREFIX_BYTES..)
2028 .ok_or(Error::InvalidCursor)?;
2029 for name in index.fields {
2030 consume_index_component(entity, index, name, &mut remaining)?;
2031 }
2032 if !index.unique {
2033 key::consume(&mut remaining, entity.key_type()?)?;
2034 }
2035 if !remaining.is_empty() {
2036 return Err(Error::InvalidCursor);
2037 }
2038 } else {
2039 RowKey::decode(
2040 bytes
2041 .get(ENTITY_PREFIX_BYTES..)
2042 .ok_or(Error::InvalidCursor)?,
2043 entity.key_type()?,
2044 )?;
2045 }
2046
2047 Ok(())
2048 }
2049
2050 fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
2051 QueryCursor {
2052 binding: self.binding,
2053 position: position.to_vec(),
2054 resume,
2055 }
2056 }
2057}
2058
2059fn consume_index_component(
2061 entity: &EntitySchema,
2062 index: &IndexSchema,
2063 name: &str,
2064 remaining: &mut &[u8],
2065) -> Result<(), Error> {
2066 let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
2067
2068 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
2069}
2070
2071#[inline(never)]
2074#[expect(
2075 clippy::needless_pass_by_value,
2076 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
2077)]
2078fn fetch_rows<M: Memory>(
2079 db: &Database<M>,
2080 entity: &EntitySchema,
2081 request: Request<'_>,
2082 projection: Option<Projection<'_>>,
2083) -> Result<QueryPage<Vec<u8>>, Error> {
2084 db.schema.admits(entity)?;
2085 let plan = Plan::admit(
2086 entity,
2087 &request,
2088 db.schema.fingerprint(),
2089 db.incarnation,
2090 projection,
2091 PlanOutput::Rows,
2092 )?;
2093
2094 execute(&db.map, entity, &request, &plan, None)
2095}
2096
2097fn execute<M: Memory>(
2098 map: &Map<M>,
2099 entity: &EntitySchema,
2100 request: &Request<'_>,
2101 plan: &Plan<'_>,
2102 mut aggregate: Option<aggregate::Accumulator<'_>>,
2103) -> Result<QueryPage<Vec<u8>>, Error> {
2104 execute_inner(
2105 map,
2106 entity,
2107 request,
2108 plan,
2109 range::bounds(entity, request, plan)?,
2110 aggregate.as_mut(),
2111 None,
2112 )
2113}
2114
2115const STEP_INPUT_BYTES: usize = 64 * 1024;
2118const fn candidate_byte_limit(row_bytes: usize) -> usize {
2119 row_bytes + 2 * crate::MAX_INDEX_KEY_BYTES
2120}
2121
2122fn execute_inner<M: Memory>(
2123 map: &Map<M>,
2124 entity: &EntitySchema,
2125 request: &Request<'_>,
2126 plan: &Plan<'_>,
2127 bounds: Option<range::Bounds>,
2128 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
2129 mut input_bytes: Option<&mut usize>,
2130) -> Result<QueryPage<Vec<u8>>, Error> {
2131 let mut page = QueryPage {
2132 rows: Vec::new(),
2133 next: None,
2134 examined: 0,
2135 fetched: 0,
2136 output_bytes: 0,
2137 };
2138 let Some(bounds) = bounds else {
2139 return Ok(page);
2140 };
2141 let terminal = range::terminal_key(&bounds, plan.descending);
2142 let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
2143 let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
2144 Some(distinct::Collection::new(
2145 plan.projection.ok_or(Error::InvalidQuery)?,
2146 key_fields,
2147 ))
2148 } else {
2149 None
2150 };
2151 let mut sorted = plan
2152 .sort
2153 .as_ref()
2154 .map(|_| sort::Collection::new(request, plan.distinct));
2155 let mut component = Vec::new();
2156 let mut right_component = Vec::new();
2157 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
2159 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
2160 } else {
2161 None
2162 };
2163 let candidate_bytes = candidate_byte_limit(entity.max_row_bytes);
2164 let primary_type = entity.fields[plan.primary].value;
2165 let needs_spans = plan.index.is_some()
2166 || plan.span_fields != 0
2167 || match &aggregate {
2168 Some(accumulator) => accumulator.needs_spans(),
2169 None => plan.projection.is_some(),
2170 };
2171 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
2173 while let Some(entry) = if plan.descending {
2174 entries.next_back()
2175 } else {
2176 entries.next()
2177 } {
2178 if page.examined == request.work {
2181 return Err(Error::Limit);
2182 }
2183 page.examined += 1;
2184 let stored_key = entry.key();
2185 let mut read_bytes = stored_key.len();
2186 let (owner, bytes) = if plan.index.is_some() {
2187 let owner_bytes = entry.value();
2188 read_bytes += owner_bytes.len();
2189 read_index_owner(map, entity.id, primary_type, &owner_bytes)?
2190 } else {
2191 (
2192 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
2193 entry.value(),
2194 )
2195 };
2196 if let Some(used) = input_bytes.as_deref_mut() {
2197 read_bytes += bytes.len();
2198 if read_bytes > candidate_bytes {
2199 return Err(Error::Corrupt);
2200 }
2201 *used += read_bytes;
2202 }
2203 page.fetched += 1;
2204 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
2205 entity.inspect_fields(
2206 &bytes,
2207 plan.selected,
2208 &mut values,
2209 needs_spans.then_some(&mut spans),
2210 )?;
2211 if plan.index.is_some() {
2212 validate_index_entry(
2213 entity,
2214 &entity.row_info(&values, &bytes, &spans)?,
2215 owner,
2216 stored_key,
2217 )?;
2218 } else if RowKey::from_index(values[plan.primary])? != owner {
2219 return Err(Error::Corrupt);
2220 }
2221 let read = |position: usize, member: Option<crate::member::RecordMember>| {
2222 if let Some(member) = member {
2223 let (start, end) = spans[position];
2224 member.read(
2225 &bytes[usize::from(start)..usize::from(end)],
2226 entity.fields[position].optional,
2227 )
2228 } else {
2229 Ok(values[position])
2230 }
2231 };
2232 let mut accepts = |term: &Term, supplied: &QueryOperand<'_>| -> Result<bool, Error> {
2233 let mut value = values[term.position];
2234 component.clear();
2235 let (operand, optional) = match &term.operand {
2236 TermOperand::Nested {
2237 member,
2238 literal,
2239 absent,
2240 } => {
2241 value = read(term.position, Some(*member))?;
2242 if *absent {
2243 return Ok(term.comparison.accepts_absent(value == IndexValue::Absent));
2244 }
2245 (
2246 Some(literal.as_slice()),
2247 entity.fields[term.position].optional || member.field().optional,
2248 )
2249 }
2250 TermOperand::Literal { absent: true, .. } => {
2251 let absent = if plan.span_fields & (1 << term.position) != 0 {
2252 bytes[usize::from(spans[term.position].0)] == 0
2253 } else {
2254 value == IndexValue::Absent
2255 };
2256
2257 return Ok(term.comparison.accepts_absent(absent));
2258 }
2259 TermOperand::Member { item, needle } => {
2260 let needle = match (needle, supplied) {
2261 (MemberNeedle::Literal(_), QueryOperand::Literal(value)) => *value,
2262 (MemberNeedle::Field(right, member), QueryOperand::Field(_)) => {
2263 read(*right, *member)?
2264 }
2265 _ => return Err(Error::Corrupt),
2266 };
2267 if needle == IndexValue::Absent {
2268 return Ok(false);
2269 }
2270 let (start, end) = spans[term.position];
2271
2272 return contains_member(
2273 &bytes[usize::from(start)..usize::from(end)],
2274 entity.fields[term.position].optional,
2275 *item,
2276 needle,
2277 );
2278 }
2279 TermOperand::Length { member, threshold } => {
2280 let (start, end) = spans[term.position];
2281 let span = &bytes[usize::from(start)..usize::from(end)];
2282 let optional = entity.fields[term.position].optional;
2283 let actual = if let Some(member) = member {
2284 match member.read(span, optional)? {
2285 IndexValue::Absent => None,
2286 value => Some(scalar_bytes(value).ok_or(Error::Corrupt)?.len() as u32),
2287 }
2288 } else {
2289 crate::codec::validated_length(span, optional)
2290 };
2291
2292 return Ok(term.comparison.accepts_length(actual, *threshold));
2293 }
2294 TermOperand::Literal {
2295 bytes,
2296 absent: false,
2297 } => (
2298 Some(bytes.as_slice()),
2299 entity.fields[term.position].optional,
2300 ),
2301 TermOperand::Field {
2302 right,
2303 left_member,
2304 right_member,
2305 } => {
2306 value = read(term.position, *left_member)?;
2307 let rhs = read(*right, *right_member)?;
2308 if value == IndexValue::Absent || rhs == IndexValue::Absent {
2309 return Ok(term.comparison.accepts_absent(value == rhs));
2310 }
2311 if let Some(matches) = term.comparison.accepts_values(value, rhs) {
2312 return Ok(matches);
2313 }
2314 right_component.clear();
2315 rhs.append_component(false, &mut right_component);
2316
2317 (Some(right_component.as_slice()), false)
2318 }
2319 };
2320 if let QueryOperand::Literal(right) = supplied
2321 && let Some(matches) = term.comparison.accepts_values(value, *right)
2322 {
2323 return Ok(matches);
2324 }
2325 value.append_component(optional, &mut component);
2326
2327 Ok(term.comparison.accepts(
2328 (value != IndexValue::Absent).then_some(component.as_slice()),
2329 operand,
2330 optional,
2331 ))
2332 };
2333 let matches = 'matches: {
2334 let mut clause_matches = false;
2335 for (term, predicate) in plan.terms.iter().zip(&request.predicates) {
2336 clause_matches = clause_matches || accepts(term, &predicate.operand)?;
2337 if !term.or_next {
2338 if !clause_matches {
2339 break 'matches false;
2340 }
2341 clause_matches = false;
2342 }
2343 }
2344
2345 true
2346 };
2347 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
2348 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2349 if matches && let Some(accumulator) = aggregate.as_mut() {
2350 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2351 if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
2352 return Ok(page);
2354 }
2355 } else if matches && let Some(collection) = collected.as_mut() {
2356 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2357 if request.single_result_probe == Some(SingleResult::First) {
2359 break;
2360 }
2361 } else if matches && let Some(collection) = sorted.as_mut() {
2362 collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2363 request.check_result_count(collection.result_count())?;
2365 } else if matches && !duplicate {
2366 request.check_result_count(page.rows.len() + 1)?;
2367 let size = plan
2368 .projection
2369 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2370 if size > request.bytes {
2371 return Err(Error::RowTooLarge);
2372 }
2373 if size > request.bytes - page.output_bytes {
2374 page.next = Some(plan.cursor(stored_key, Resume::Retry));
2375
2376 return Ok(page);
2377 }
2378 page.output_bytes += size;
2379 if let Some(mask) = plan.projection {
2380 page.rows.push(copy_projection(&bytes, &spans, mask, size));
2381 } else {
2382 page.rows.push(bytes);
2383 }
2384 if request.single_result_probe == Some(SingleResult::First)
2385 || plan.distinct.finishes_on_match(plan.fixed_components)
2386 {
2387 return Ok(page);
2388 }
2389 if let Some(boundary) = boundary {
2390 previous = Some(boundary.to_vec());
2391 }
2392 }
2393 if page.rows.len() == request.rows
2394 || page.examined == request.work
2395 || input_bytes
2396 .as_deref()
2397 .is_some_and(|used| *used > STEP_INPUT_BYTES - candidate_bytes)
2398 {
2399 if terminal == Some(stored_key) {
2400 break;
2401 }
2402 if request.single_result_probe.is_some()
2403 || (aggregate.is_some() && input_bytes.is_none())
2404 || collected.is_some()
2405 || sorted.is_some()
2406 {
2407 continue;
2410 }
2411 let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
2412 Resume::AfterUnemittedClass
2413 } else {
2414 Resume::After
2415 };
2416 page.next = Some(plan.cursor(stored_key, resume));
2417
2418 return Ok(page);
2419 }
2420 }
2421 if let Some(collection) = collected {
2422 page.output_bytes = collection.output_bytes;
2423 page.rows = collection.rows;
2424 }
2425 if let Some(collection) = sorted {
2426 collection.finish(request.bytes, &mut page)?;
2427 }
2428
2429 Ok(page)
2430}