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 within_limits(&self) -> bool {
609 !self.over_limit
610 && (1..=32).contains(&self.rows)
611 && (1..=MAX_WORK).contains(&self.work)
612 && (1..=MAX_OUTPUT).contains(&self.bytes)
613 }
614
615 fn check_result_count(&self, count: usize) -> Result<(), Error> {
618 if self.single_result_probe == Some(SingleResult::Only) && count > 1 {
619 return Err(Error::MultipleMatches);
620 }
621 Ok(())
622 }
623
624 fn fixed_equalities<'r>(
626 &'r self,
627 entity: &'r EntitySchema,
628 ) -> impl Iterator<Item = (&'a str, IndexValue<'a>)> + 'r {
629 self.clauses().filter_map(move |clause| {
630 let (predicate, rest) = clause.split_first()?;
631 if !rest.is_empty() {
632 let mut candidate = predicate.fixed_equality(entity)?;
633 for alternative in rest {
634 let other = alternative.fixed_equality(entity)?;
635 if candidate.0 != other.0 {
636 return None;
637 }
638 if equal_values(candidate.1, other.1) {
639 continue;
640 }
641 if self.predicates.len() == clause.len() {
642 return None;
643 }
644 if self.excludes_literal(other.0, other.1) {
645 continue;
646 }
647 if !self.excludes_literal(candidate.0, candidate.1) {
648 return None;
649 }
650 candidate = other;
651 }
652 return Some(candidate);
655 }
656 if let Some(equality) = predicate.fixed_equality(entity) {
657 return Some(equality);
658 }
659 let QueryOperand::Literal(value) = predicate.operand else {
663 return None;
664 };
665 let lower = match predicate.comparison {
666 Comparison::Ge => value,
667 Comparison::Gt if self.predicates.len() > 1 => value.discrete_successor()?,
668 _ => return None,
669 };
670 self.clauses()
671 .any(|clause| {
672 let [upper] = clause else { return false };
673 if upper.field != predicate.field {
674 return false;
675 }
676 match (upper.comparison, upper.operand) {
677 (Comparison::Le, QueryOperand::Literal(value)) => {
678 equal_values(lower, value)
679 }
680 (Comparison::Lt, QueryOperand::Literal(value)) => {
681 consecutive_values(lower, value)
682 }
683 _ => false,
684 }
685 })
686 .then_some((predicate.field, lower))
687 })
688 }
689
690 fn excludes_literal(&self, field: &str, value: IndexValue<'_>) -> bool {
691 self.clauses().any(|clause| {
694 clause.iter().all(|predicate| {
695 if predicate.field != field {
696 return false;
697 }
698 let QueryOperand::Literal(literal) = predicate.operand else {
699 return false;
700 };
701 match predicate.comparison {
702 Comparison::Eq
703 | Comparison::Ne
704 | Comparison::Lt
705 | Comparison::Le
706 | Comparison::Gt
707 | Comparison::Ge => {
708 predicate.comparison.accepts_fixed_values(value, literal) == Some(false)
709 }
710 _ => false,
711 }
712 })
713 })
714 }
715
716 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
717 self.predicates.split_inclusive(|p| !p.or_next)
718 }
719
720 #[inline(never)]
721 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
722 if self.predicates.len() == MAX_TERMS {
723 self.over_limit = true;
724 } else {
725 self.predicates.push(Predicate {
726 field,
727 comparison,
728 operand,
729 or_next: false,
730 });
731 }
732 }
733
734 #[inline(never)]
735 fn or_clause(
736 &mut self,
737 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
738 ) {
739 let count = alternatives.len();
740
741 if count == 0 || count > MAX_TERMS - self.predicates.len() {
742 self.over_limit = true;
743 } else {
744 self.predicates.extend(alternatives.enumerate().map(
745 |(i, (field, comparison, operand))| Predicate {
746 field,
747 comparison,
748 operand,
749 or_next: i + 1 < count,
750 },
751 ));
752 }
753 }
754
755 #[inline(never)]
756 fn filter_not_in(
757 &mut self,
758 field: &'a str,
759 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
760 ) {
761 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
762 self.over_limit = true;
763
764 return;
765 }
766 for value in values {
767 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
768 }
769 }
770
771 #[inline(never)]
772 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
773 if values.len() > 4 {
774 self.over_limit = true;
775 } else {
776 self.index = Some((name, values.to_vec()));
777 }
778 }
779
780 #[inline(never)]
781 fn order_by(&mut self, fields: &[&'a str]) {
782 self.order_descending = 0;
783
784 if fields.len() > 4 {
785 self.over_limit = true;
786 } else {
787 self.order = Some(fields.to_vec());
788 }
789 }
790
791 #[inline(never)]
792 fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
793 if fields.len() > 4 {
794 self.over_limit = true;
795
796 return;
797 }
798 self.order = Some(Vec::with_capacity(fields.len()));
799 self.order_descending = 0;
800 for &(field, direction) in fields {
801 self.append_order(field, direction);
802 }
803 }
804
805 fn append_order(&mut self, field: &'a str, direction: SortDirection) {
806 let fields = self.order.get_or_insert_with(Vec::new);
807 if fields.len() == 4 {
808 self.over_limit = true;
809
810 return;
811 }
812 if direction == SortDirection::Descending {
813 self.order_descending |= 1 << fields.len();
814 }
815 fields.push(field);
816 }
817
818 fn primary_descending(&self, entity: &EntitySchema) -> bool {
819 self.order_descending != 0
820 && self.order.as_ref().is_some_and(|fields| {
821 fields.last() == Some(&entity.primary_key)
822 && self.order_descending & (1 << (fields.len() - 1)) != 0
823 })
824 }
825}
826
827pub(super) fn source_page<M: Memory>(
829 map: &Map<M>,
830 entity: &EntitySchema,
831 binding: [u8; 32],
832 incarnation: [u8; 16],
833 cursor: Option<&QueryCursor>,
834 rows: usize,
835 bytes: usize,
836) -> Result<QueryPage<Vec<u8>>, Error> {
837 let request = Request {
838 rows,
839 work: rows,
840 bytes,
841 cursor,
842 ..Request::default()
843 };
844 let plan = Plan::admit(
845 entity,
846 &request,
847 binding,
848 incarnation,
849 None,
850 PlanOutput::Rows,
851 )?;
852
853 execute(map, entity, &request, &plan, None)
854}
855
856enum QuerySource<'a, M: Memory> {
857 Direct(&'a Database<M>),
858 Session(Rc<RefCell<Database<M>>>),
859}
860
861enum QueryRead<'a, M: Memory> {
862 Direct(&'a Database<M>),
863 Session(Ref<'a, Database<M>>),
864}
865
866impl<M: Memory> Deref for QueryRead<'_, M> {
867 type Target = Database<M>;
868
869 fn deref(&self) -> &Self::Target {
870 match self {
871 Self::Direct(db) => db,
872 Self::Session(db) => db,
873 }
874 }
875}
876
877impl<M: Memory> QuerySource<'_, M> {
878 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
879 match self {
880 Self::Direct(db) => Ok(QueryRead::Direct(db)),
881 Self::Session(db) => db
882 .try_borrow()
883 .map(QueryRead::Session)
884 .map_err(|_| Error::BorrowConflict),
885 }
886 }
887}
888
889pub struct Query<'a, E, M: Memory> {
893 db: QuerySource<'a, M>,
894 request: Request<'a>,
895 entity: PhantomData<E>,
896}
897impl<M: Memory> Database<M> {
898 #[must_use]
900 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
901 Query {
902 db: QuerySource::Direct(self),
903 entity: PhantomData,
904 request: Request::default(),
905 }
906 }
907}
908impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
909 pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
910 Self {
911 db: QuerySource::Session(db),
912 request: Request::default(),
913 entity: PhantomData,
914 }
915 }
916
917 #[must_use]
931 pub fn distinct(mut self) -> Self {
932 self.request.distinct = true;
933
934 self
935 }
936
937 #[must_use]
950 pub fn filter(
951 mut self,
952 field: &'a str,
953 comparison: Comparison,
954 value: impl Into<IndexValue<'a>>,
955 ) -> Self {
956 self.request
957 .filter(field, comparison, QueryOperand::Literal(value.into()));
958
959 self
960 }
961
962 #[must_use]
964 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
965 self.filter(field, Comparison::Eq, value)
966 }
967
968 #[must_use]
970 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
971 self.filter(field, Comparison::Ne, value)
972 }
973
974 #[must_use]
976 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
977 self.filter(field, Comparison::Lt, value)
978 }
979
980 #[must_use]
982 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
983 self.filter(field, Comparison::Le, value)
984 }
985
986 #[must_use]
988 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
989 self.filter(field, Comparison::Gt, value)
990 }
991
992 #[must_use]
994 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
995 self.filter(field, Comparison::Ge, value)
996 }
997
998 #[must_use]
1006 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
1007 self.request
1008 .filter(left, comparison, QueryOperand::Field(right));
1009
1010 self
1011 }
1012
1013 #[must_use]
1018 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
1019 self.request
1020 .filter(field, comparison, QueryOperand::Length(length));
1021
1022 self
1023 }
1024
1025 #[must_use]
1028 pub fn filter_present(self, field: &'a str) -> Self {
1029 self.filter(field, Comparison::Ne, IndexValue::Absent)
1030 }
1031
1032 #[must_use]
1035 pub fn filter_absent(self, field: &'a str) -> Self {
1036 self.filter(field, Comparison::Eq, IndexValue::Absent)
1037 }
1038
1039 #[must_use]
1046 pub fn filter_between(
1047 self,
1048 field: &'a str,
1049 lower: impl Into<IndexValue<'a>>,
1050 upper: impl Into<IndexValue<'a>>,
1051 ) -> Self {
1052 self.filter(field, Comparison::Ge, lower)
1053 .filter(field, Comparison::Le, upper)
1054 }
1055
1056 #[must_use]
1064 pub fn filter_not_between(
1065 self,
1066 field: &'a str,
1067 lower: impl Into<IndexValue<'a>>,
1068 upper: impl Into<IndexValue<'a>>,
1069 ) -> Self {
1070 self.filter_any(&[
1071 (field, Comparison::Lt, lower.into()),
1072 (field, Comparison::Gt, upper.into()),
1073 ])
1074 }
1075
1076 #[must_use]
1081 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1082 self.filter_fields(field, Comparison::Ge, lower)
1083 .filter_fields(field, Comparison::Le, upper)
1084 }
1085
1086 #[must_use]
1091 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1092 self.filter_any_operands(&[
1093 (field, Comparison::Lt, QueryOperand::Field(lower)),
1094 (field, Comparison::Gt, QueryOperand::Field(upper)),
1095 ])
1096 }
1097
1098 #[must_use]
1106 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
1107 self.request.or_clause(
1108 alternatives
1109 .iter()
1110 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
1111 );
1112
1113 self
1114 }
1115
1116 #[must_use]
1121 pub fn filter_any_operands(
1122 mut self,
1123 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
1124 ) -> Self {
1125 self.request.or_clause(alternatives.iter().copied());
1126
1127 self
1128 }
1129
1130 #[must_use]
1140 pub fn filter_in(
1141 mut self,
1142 field: &'a str,
1143 values: &[impl Copy + Into<IndexValue<'a>>],
1144 ) -> Self {
1145 self.request.or_clause(
1146 values
1147 .iter()
1148 .copied()
1149 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
1150 );
1151
1152 self
1153 }
1154
1155 #[must_use]
1163 pub fn filter_not_in(
1164 mut self,
1165 field: &'a str,
1166 values: &[impl Copy + Into<IndexValue<'a>>],
1167 ) -> Self {
1168 self.request
1169 .filter_not_in(field, values.iter().copied().map(Into::into));
1170
1171 self
1172 }
1173
1174 #[must_use]
1179 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
1180 self.request.using_index(name, values);
1181
1182 self
1183 }
1184
1185 #[must_use]
1188 pub fn order_asc(mut self, field: &'a str) -> Self {
1189 self.request.append_order(field, SortDirection::Ascending);
1190
1191 self
1192 }
1193
1194 #[must_use]
1197 pub fn order_desc(mut self, field: &'a str) -> Self {
1198 self.request.append_order(field, SortDirection::Descending);
1199
1200 self
1201 }
1202
1203 #[must_use]
1214 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
1215 self.request.order_by(fields);
1216
1217 self
1218 }
1219
1220 #[must_use]
1225 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
1226 self.request.order_by_each(fields);
1227
1228 self
1229 }
1230
1231 #[must_use]
1233 pub fn descending(mut self) -> Self {
1234 self.request.descending = true;
1235
1236 self
1237 }
1238
1239 #[must_use]
1246 pub fn limit(mut self, rows: usize) -> Self {
1247 self.request.rows = rows;
1248
1249 self
1250 }
1251
1252 #[must_use]
1254 pub fn work_limit(mut self, candidates: usize) -> Self {
1255 self.request.work = candidates;
1256
1257 self
1258 }
1259
1260 #[cfg(feature = "test-support")]
1262 #[doc(hidden)]
1263 #[must_use]
1264 pub fn test_output_limit(mut self, bytes: usize) -> Self {
1265 self.request.bytes = bytes;
1266
1267 self
1268 }
1269
1270 #[must_use]
1272 pub fn after(self, cursor: &'a QueryCursor) -> Self {
1273 self.after_optional(Some(cursor))
1274 }
1275
1276 #[must_use]
1278 pub fn after_optional(mut self, cursor: Option<&'a QueryCursor>) -> Self {
1279 self.request.cursor = cursor;
1280
1281 self
1282 }
1283
1284 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
1291 observe!(query, { self.entity_page() })
1292 }
1293
1294 fn entity_page(self) -> Result<QueryPage<E>, Error> {
1295 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
1296 }
1297
1298 pub fn first(self) -> Result<Option<E>, Error> {
1304 self.first_with(Self::entity_page)
1305 }
1306
1307 pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
1311 self.first_with(Self::projected_page::<R>)
1312 }
1313
1314 fn first_with<R>(
1315 self,
1316 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1317 ) -> Result<Option<R>, Error> {
1318 observe!(query, { fetch(self.probe_matches(SingleResult::First)?) })
1319 .map(|mut page| page.rows.pop())
1320 }
1321
1322 pub fn try_one(self) -> Result<Option<E>, Error> {
1329 self.try_one_with(Self::entity_page)
1330 }
1331
1332 pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
1338 self.try_one_with(Self::projected_page::<R>)
1339 }
1340
1341 fn try_one_with<R>(
1342 self,
1343 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1344 ) -> Result<Option<R>, Error> {
1345 observe!(query, {
1346 if self.request.cursor.is_some() {
1347 return Err(Error::InvalidQuery);
1348 }
1349 fetch(self.probe_matches(SingleResult::Only)?)
1350 })
1351 .map(|mut page| page.rows.pop())
1352 }
1353
1354 fn probe_matches(mut self, probe: SingleResult) -> Result<Self, Error> {
1355 if !(1..=32).contains(&self.request.rows) {
1356 return Err(Error::Limit);
1357 }
1358
1359 self.request.single_result_probe = Some(probe);
1360
1361 Ok(self.limit(match probe {
1362 SingleResult::First => 1,
1363 SingleResult::Only => 2,
1364 }))
1365 }
1366
1367 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1377 observe!(query, { self.projected_page() })
1378 }
1379
1380 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1381 let raw = fetch_rows(
1382 &*self.db.read()?,
1383 E::SCHEMA,
1384 self.request,
1385 Some(Projection::Record(R::definition())),
1386 )?;
1387
1388 raw.decode_with(R::decode_from)
1389 }
1390}
1391
1392#[derive(Clone, Copy)]
1393enum Projection<'a> {
1394 Record(&'a TypeSchema),
1395 Columns(&'a [u8]),
1396}
1397
1398impl Projection<'_> {
1399 fn mask(self, entity: &EntitySchema) -> Result<u32, Error> {
1400 match self {
1401 Self::Record(record) => admit_projection(entity, record),
1402 Self::Columns(columns) => {
1403 let mut mask = 0;
1404 for &column in columns {
1405 if usize::from(column) >= entity.fields.len() || mask & (1 << column) != 0 {
1406 return Err(Error::InvalidQuery);
1407 }
1408 mask |= 1 << column;
1409 }
1410 Ok(mask)
1411 }
1412 }
1413 }
1414}
1415
1416fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u32, Error> {
1420 let TypeBody::Record(fields) = &output.body else {
1421 return Err(Error::InvalidQuery);
1422 };
1423 if fields.is_empty()
1424 || fields.len() > crate::schema::MAX_FIELDS
1425 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1426 {
1427 return Err(Error::InvalidQuery);
1428 }
1429 let mut source = TypeGraph::default();
1430 let mut target = TypeGraph::default();
1431 let mut mask = 0;
1432 for field in *fields {
1433 let position = entity
1434 .field_position(field.name)
1435 .ok_or(Error::InvalidQuery)?;
1436 let stored = &entity.fields[position];
1437 if stored.value != field.value || stored.optional != field.optional {
1438 return Err(Error::InvalidQuery);
1439 }
1440 source
1441 .include(stored.value)
1442 .map_err(|_| Error::InvalidQuery)?;
1443 target
1444 .include(field.value)
1445 .map_err(|_| Error::InvalidQuery)?;
1446 mask |= 1 << position;
1447 }
1448 if !source.contains(&target) {
1449 return Err(Error::InvalidQuery);
1450 }
1451
1452 Ok(mask)
1453}
1454
1455struct Term {
1456 tests_presence: bool,
1457 position: usize,
1458 comparison: Comparison,
1459 operand: TermOperand,
1460 or_next: bool,
1461}
1462
1463enum TermOperand {
1464 Literal {
1465 bytes: Vec<u8>,
1466 absent: bool,
1467 },
1468 Member {
1469 item: FieldType,
1470 needle: MemberNeedle,
1471 },
1472 Nested {
1473 member: crate::member::RecordMember,
1474 literal: Vec<u8>,
1475 absent: bool,
1476 },
1477 Field {
1478 right: usize,
1479 left_member: Option<crate::member::RecordMember>,
1480 right_member: Option<crate::member::RecordMember>,
1481 },
1482 Length {
1483 member: Option<crate::member::RecordMember>,
1484 threshold: u32,
1485 },
1486}
1487
1488enum MemberNeedle {
1489 Literal(Vec<u8>),
1490 Field(usize, Option<crate::member::RecordMember>),
1491}
1492
1493fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1496 match value {
1497 IndexValue::Text(text) => Some(text.as_bytes()),
1498 IndexValue::Blob(bytes) => Some(bytes),
1499 _ => None,
1500 }
1501}
1502
1503fn consecutive_values(low: IndexValue<'_>, high: IndexValue<'_>) -> bool {
1504 low.discrete_successor()
1505 .is_some_and(|next| equal_values(next, high))
1506}
1507
1508fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1509 match (left, right) {
1511 (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1512 a == b
1513 }
1514 _ => left == right,
1515 }
1516}
1517
1518fn length_limit(field: FieldType) -> Option<u32> {
1519 match key::operand_type(field) {
1520 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1521 FieldType::List { max_items, .. } => Some(max_items),
1522 FieldType::Named(link) => match (link.definition)().body {
1523 TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1524 _ => None,
1525 },
1526 _ => None,
1527 }
1528}
1529
1530fn member_type(field: FieldType) -> Option<FieldType> {
1531 match key::operand_type(field) {
1532 FieldType::List { item, .. } => Some(*item),
1533 FieldType::Named(link) => match (link.definition)().body {
1534 TypeBody::Set { item, .. } => Some(item),
1535 _ => None,
1536 },
1537 _ => None,
1538 }
1539}
1540
1541fn contains_member(
1543 span: &[u8],
1544 optional: bool,
1545 item: FieldType,
1546 needle: IndexValue<'_>,
1547) -> Result<bool, Error> {
1548 let mut reader = Decoder::new(span)?;
1549 if optional && !reader.boolean()? {
1550 return Ok(false);
1551 }
1552 for _ in 0..reader.nat32()? {
1553 let value = IndexValue::read(&mut reader, item)?;
1554 if equal_values(value, needle) {
1555 return Ok(true);
1556 }
1557 }
1558
1559 Ok(false)
1560}
1561
1562fn projection_positions(mut mask: u32) -> impl Iterator<Item = usize> {
1565 std::iter::from_fn(move || {
1566 if mask == 0 {
1567 return None;
1568 }
1569 let position = mask.trailing_zeros() as usize;
1570 mask &= mask - 1;
1571 Some(position)
1572 })
1573}
1574
1575fn admit_ordered_fields(entity: &EntitySchema, mask: u32) -> Result<(), Error> {
1576 for i in projection_positions(mask) {
1577 if !key::supports(entity.fields[i].value) {
1578 return Err(Error::InvalidQuery);
1579 }
1580 }
1581
1582 Ok(())
1583}
1584
1585fn comparison_key(
1587 entity: &EntitySchema,
1588 mask: u32,
1589 values: &[IndexValue<'_>],
1590 scratch: &mut Vec<u8>,
1591) -> Result<(), Error> {
1592 build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1593}
1594
1595fn build_comparison_key<'a>(
1596 entity: &EntitySchema,
1597 mask: u32,
1598 key: &mut Vec<u8>,
1599 mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1600) -> Result<(), Error> {
1601 key.clear();
1602 for i in projection_positions(mask) {
1603 let field = &entity.fields[i];
1604 value(i, field)?.append_component(field.optional, key);
1605 if key.len() > MAX_COMPARISON_KEY {
1606 return Err(Error::Limit);
1607 }
1608 }
1609
1610 Ok(())
1611}
1612
1613fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1614 if size > limit {
1615 return Err(Error::RowTooLarge);
1616 }
1617 if size > limit - *used {
1618 return Err(Error::Limit);
1619 }
1620 *used += size;
1621
1622 Ok(())
1623}
1624
1625fn projection_size(spans: &[(u16, u16)], mask: u32) -> usize {
1627 projection_positions(mask)
1628 .map(|i| {
1629 let (start, end) = spans[i];
1630 usize::from(end - start)
1631 })
1632 .sum()
1633}
1634
1635fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u32, size: usize) -> Vec<u8> {
1636 let mut output = Vec::with_capacity(size);
1637 for i in projection_positions(mask) {
1638 let (start, end) = spans[i];
1639 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1640 }
1641
1642 output
1643}
1644#[derive(Clone, Copy)]
1645enum PlanOutput {
1646 Rows,
1647 Aggregate { grouped: bool },
1648}
1649
1650struct Plan<'a> {
1651 primary: usize,
1652 index: Option<&'a IndexSchema>,
1653 prefix: Vec<u8>,
1654 fixed_components: usize,
1655 terms: Vec<Term>,
1656 selected: u32,
1657 span_fields: u32,
1659 binding: [u8; 32],
1660 projection: Option<u32>,
1661 distinct: distinct::Strategy,
1662 sort: Option<Vec<order::SortField>>,
1663 descending: bool,
1664}
1665impl<'a> Plan<'a> {
1666 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1667 self.terms.split_inclusive(|term| !term.or_next)
1668 }
1669
1670 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1671 self.index = Some(path.index);
1672 self.prefix = path.prefix;
1673 self.fixed_components = path.fixed;
1674 self.selected |= entity.key_fields();
1675 }
1676
1677 fn admit(
1678 entity: &'a EntitySchema,
1679 request: &Request<'_>,
1680 schema: [u8; 32],
1681 incarnation: [u8; 16],
1682 projection: Option<Projection<'_>>,
1683 output: PlanOutput,
1684 ) -> Result<Self, Error> {
1685 if !request.within_limits() {
1686 return Err(Error::Limit);
1687 }
1688 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1689 {
1690 return Err(Error::InvalidQuery);
1691 }
1692 for value in request
1694 .predicates
1695 .iter()
1696 .filter_map(|p| match &p.operand {
1697 QueryOperand::Literal(value) => Some(value),
1698 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1699 })
1700 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1701 {
1702 if match value {
1703 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1704 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1705 _ => false,
1706 } {
1707 return Err(Error::Limit);
1708 }
1709 }
1710 let primary = entity
1711 .field_position(entity.primary_key)
1712 .filter(|&i| !entity.fields[i].optional)
1713 .ok_or(Error::InvalidQuery)?;
1714 let mut plan = Self {
1715 primary,
1716 index: None,
1717 prefix: prefix(2, entity.id, &[]),
1718 fixed_components: 0,
1719 terms: Vec::new(),
1720 selected: 1 << primary,
1721 span_fields: 0,
1722 binding: [0; 32],
1723 projection: projection.map(|output| output.mask(entity)).transpose()?,
1724 distinct: distinct::Strategy::Identity,
1725 sort: None,
1726 descending: request.descending ^ request.primary_descending(entity),
1727 };
1728 for predicate in &request.predicates {
1729 let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
1730 let field = &entity.fields[position];
1731 let member = if predicate.comparison == Comparison::Contains {
1732 member_type(field.value)
1733 } else {
1734 None
1735 };
1736 let operand = match (predicate.operand, record_member) {
1737 (QueryOperand::Literal(value), Some(member)) => {
1738 if !predicate.comparison.supports_record_member() {
1739 return Err(Error::InvalidQuery);
1740 }
1741 let leaf = member.field();
1742 predicate.comparison.admit(
1743 leaf.value,
1744 field.optional || leaf.optional,
1745 value,
1746 )?;
1747 let mut literal = Vec::new();
1748 value.append_component(field.optional || leaf.optional, &mut literal);
1749 plan.span_fields |= 1 << position;
1750 TermOperand::Nested {
1751 member,
1752 literal,
1753 absent: value == IndexValue::Absent,
1754 }
1755 }
1756 (QueryOperand::Length(length), member) => {
1757 let selected = member.map_or(field.value, |m| m.field().value);
1758 if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1759 return Err(Error::InvalidQuery);
1760 }
1761 plan.span_fields |= 1 << position;
1762
1763 TermOperand::Length {
1764 member,
1765 threshold: length,
1766 }
1767 }
1768 (QueryOperand::Field(name), left_member) => {
1769 let (right, right_member) = crate::member::resolve_field(entity, name)?;
1770 if (left_member.is_some() || right_member.is_some())
1771 && member.is_none()
1772 && !predicate.comparison.supports_record_member()
1773 {
1774 return Err(Error::InvalidQuery);
1775 }
1776 let right_type =
1777 right_member.map_or(entity.fields[right].value, |m| m.field().value);
1778 let left_type =
1779 left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1780 let compatible = left_type == right_type
1781 || matches!(
1782 (left_type, right_type),
1783 (FieldType::Text { .. }, FieldType::Text { .. })
1784 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1785 );
1786 if !compatible
1787 || !key::supports(left_type)
1788 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1789 {
1790 return Err(Error::InvalidQuery);
1791 }
1792 if right_member.is_some() {
1793 plan.span_fields |= 1 << right;
1794 } else {
1795 plan.selected |= 1 << right;
1796 }
1797
1798 if let Some(item) = member {
1799 plan.span_fields |= 1 << position;
1800
1801 TermOperand::Member {
1802 item,
1803 needle: MemberNeedle::Field(right, right_member),
1804 }
1805 } else {
1806 if left_member.is_some() {
1807 plan.span_fields |= 1 << position;
1808 } else {
1809 plan.selected |= 1 << position;
1810 }
1811 TermOperand::Field {
1812 right,
1813 left_member,
1814 right_member,
1815 }
1816 }
1817 }
1818 (QueryOperand::Literal(value), None) => {
1819 if let Some(item) = member {
1820 if !key::supports(item) {
1821 return Err(Error::InvalidQuery);
1822 }
1823 value.admit(item, false)?;
1824 let mut bytes = Vec::new();
1825 value.append_component(false, &mut bytes);
1826 plan.span_fields |= 1 << position;
1827
1828 TermOperand::Member {
1829 item,
1830 needle: MemberNeedle::Literal(bytes),
1831 }
1832 } else {
1833 let absent = value == IndexValue::Absent;
1834 if key::supports(field.value) {
1835 plan.selected |= 1 << position;
1836 } else if absent
1837 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1838 {
1839 plan.span_fields |= 1 << position;
1840 } else {
1841 return Err(Error::InvalidQuery);
1842 }
1843 predicate
1844 .comparison
1845 .admit(field.value, field.optional, value)?;
1846 let mut bytes = Vec::new();
1847 value.append_component(field.optional, &mut bytes);
1848
1849 TermOperand::Literal { bytes, absent }
1850 }
1851 }
1852 };
1853 plan.terms.push(Term {
1854 tests_presence: predicate.tests_presence(entity, &operand),
1855 position,
1856 comparison: predicate.comparison,
1857 operand,
1858 or_next: predicate.or_next,
1859 });
1860 }
1861 match order::select(entity, request, output)? {
1864 order::Path::Primary => {}
1865 order::Path::Index(path, descending) => {
1866 plan.use_index(entity, path);
1867 plan.descending = request.descending ^ descending;
1868 }
1869 order::Path::Filtered { sort } => {
1870 order::select_filtered_path(entity, request, &mut plan, None)?;
1871 for field in sort.iter().flatten() {
1872 if field.member.is_some() {
1873 plan.span_fields |= 1 << field.position;
1874 } else {
1875 plan.selected |= 1 << field.position;
1876 }
1877 }
1878 plan.sort = sort;
1879 }
1880 }
1881 if request.distinct {
1882 plan.distinct = distinct::admit(entity, request, &plan)?;
1883 match plan.distinct {
1884 distinct::Strategy::FirstMatch => plan.sort = None,
1885 distinct::Strategy::Complete { key_fields } => plan.selected |= key_fields,
1886 _ => {}
1887 }
1888 }
1889 let mut hash = Sha256::new();
1890 hash.update(b"ic-db:query:v1\0");
1891 hash.update(schema);
1892 hash.update(incarnation);
1893 hash.update([u8::from(request.descending)]);
1894 hash.update((plan.prefix.len() as u32).to_le_bytes());
1895 hash.update(&plan.prefix);
1896 for term in &plan.terms {
1897 hash.update([term.position as u8, term.comparison as u8]);
1898
1899 match &term.operand {
1900 TermOperand::Nested {
1901 member,
1902 literal,
1903 absent,
1904 } => {
1905 hash.update((u32::MAX - 2).to_le_bytes());
1906 hash.update([member.position() as u8, u8::from(*absent)]);
1907 let literal = &literal[usize::from(
1909 entity.fields[term.position].optional || member.field().optional,
1910 )..];
1911 hash.update((literal.len() as u32).to_le_bytes());
1912 hash.update(literal);
1913 }
1914 TermOperand::Literal { bytes, .. }
1915 | TermOperand::Member {
1916 needle: MemberNeedle::Literal(bytes),
1917 ..
1918 } => {
1919 hash.update((bytes.len() as u32).to_le_bytes());
1920 hash.update(bytes);
1921 }
1922 TermOperand::Length { member, threshold } => {
1923 if let Some(member) = member {
1924 hash.update((u32::MAX - 3).to_le_bytes());
1925 hash.update([member.position() as u8]);
1926 } else {
1927 hash.update((u32::MAX - 1).to_le_bytes());
1928 }
1929 hash.update(threshold.to_le_bytes());
1930 }
1931 TermOperand::Field {
1932 right,
1933 left_member: None,
1934 right_member: None,
1935 }
1936 | TermOperand::Member {
1937 needle: MemberNeedle::Field(right, None),
1938 ..
1939 } => {
1940 hash.update(u32::MAX.to_le_bytes());
1942 hash.update([*right as u8]);
1943 }
1944 TermOperand::Member {
1945 needle: MemberNeedle::Field(right, Some(member)),
1946 ..
1947 } => {
1948 hash.update((u32::MAX - 4).to_le_bytes());
1949 hash.update([u8::MAX, *right as u8, member.position() as u8]);
1950 }
1951 TermOperand::Field {
1952 right,
1953 left_member,
1954 right_member,
1955 } => {
1956 hash.update((u32::MAX - 4).to_le_bytes());
1957 let slot = |member: &Option<crate::member::RecordMember>| {
1958 member.map_or(u8::MAX, |m| m.position() as u8)
1959 };
1960 hash.update([slot(left_member), *right as u8, slot(right_member)]);
1961 }
1962 }
1963 }
1964 let clauses = plan
1967 .terms
1968 .iter()
1969 .enumerate()
1970 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1971 if clauses != 0 {
1972 hash.update(b"or-clauses\0");
1973 hash.update([clauses]);
1974 }
1975 if let Some(order) = &request.order {
1976 hash.update(b"order\0");
1977 hash.update([order.len() as u8]);
1978 for name in order {
1979 if let Some(position) = entity.field_position(name) {
1981 hash.update([position as u8]);
1982 } else {
1983 hash.update([u8::MAX, name.len() as u8]);
1985 hash.update(name.as_bytes());
1986 }
1987 }
1988 }
1989 if request.order_descending != 0 {
1990 hash.update(b"order-directions\0");
1991 hash.update([request.order_descending]);
1992 }
1993 if let Some(mask) = plan.projection {
1996 hash.update(b"projection\0");
1997 hash.update(mask.to_le_bytes());
1998 if let Some(Projection::Columns(columns)) = projection {
1999 hash.update(b"columns\0");
2000 hash.update(columns);
2001 }
2002 }
2003 if request.distinct {
2004 hash.update(b"distinct\0");
2005 }
2006 plan.binding = hash.finalize().into();
2007 if let Some(cursor) = request.cursor {
2008 if cursor.binding != plan.binding {
2009 return Err(Error::InvalidCursor);
2010 }
2011 plan.validate_position(entity, cursor)
2012 .map_err(|_| Error::InvalidCursor)?;
2013 }
2014
2015 Ok(plan)
2016 }
2017
2018 fn validate_position(&self, entity: &EntitySchema, cursor: &QueryCursor) -> Result<(), Error> {
2019 if cursor.resume == Resume::AfterUnemittedClass
2020 && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
2021 {
2022 return Err(Error::InvalidCursor);
2023 }
2024 let bytes = cursor.position.as_slice();
2025 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
2026 return Err(Error::InvalidCursor);
2027 }
2028 if let Some(index) = self.index {
2029 let mut remaining = bytes
2030 .get(INDEX_PREFIX_BYTES..)
2031 .ok_or(Error::InvalidCursor)?;
2032 for name in index.fields {
2033 consume_index_component(entity, index, name, &mut remaining)?;
2034 }
2035 if !index.unique {
2036 key::consume(&mut remaining, entity.key_type()?)?;
2037 }
2038 if !remaining.is_empty() {
2039 return Err(Error::InvalidCursor);
2040 }
2041 } else {
2042 RowKey::decode(
2043 bytes
2044 .get(ENTITY_PREFIX_BYTES..)
2045 .ok_or(Error::InvalidCursor)?,
2046 entity.key_type()?,
2047 )?;
2048 }
2049
2050 Ok(())
2051 }
2052
2053 fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
2054 QueryCursor {
2055 binding: self.binding,
2056 position: position.to_vec(),
2057 resume,
2058 }
2059 }
2060}
2061
2062fn consume_index_component(
2064 entity: &EntitySchema,
2065 index: &IndexSchema,
2066 name: &str,
2067 remaining: &mut &[u8],
2068) -> Result<(), Error> {
2069 let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
2070
2071 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
2072}
2073
2074#[inline(never)]
2077#[expect(
2078 clippy::needless_pass_by_value,
2079 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
2080)]
2081fn fetch_rows<M: Memory>(
2082 db: &Database<M>,
2083 entity: &EntitySchema,
2084 request: Request<'_>,
2085 projection: Option<Projection<'_>>,
2086) -> Result<QueryPage<Vec<u8>>, Error> {
2087 db.schema.admits(entity)?;
2088 let plan = Plan::admit(
2089 entity,
2090 &request,
2091 db.schema.fingerprint(),
2092 db.incarnation,
2093 projection,
2094 PlanOutput::Rows,
2095 )?;
2096
2097 execute(&db.map, entity, &request, &plan, None)
2098}
2099
2100fn execute<M: Memory>(
2101 map: &Map<M>,
2102 entity: &EntitySchema,
2103 request: &Request<'_>,
2104 plan: &Plan<'_>,
2105 mut aggregate: Option<aggregate::Accumulator<'_>>,
2106) -> Result<QueryPage<Vec<u8>>, Error> {
2107 execute_inner(
2108 map,
2109 entity,
2110 request,
2111 plan,
2112 range::bounds(entity, request, plan)?,
2113 aggregate.as_mut(),
2114 None,
2115 )
2116}
2117
2118const STEP_INPUT_BYTES: usize = 64 * 1024;
2121const fn candidate_byte_limit(row_bytes: usize) -> usize {
2122 row_bytes + 2 * crate::MAX_INDEX_KEY_BYTES
2123}
2124
2125fn execute_inner<M: Memory>(
2126 map: &Map<M>,
2127 entity: &EntitySchema,
2128 request: &Request<'_>,
2129 plan: &Plan<'_>,
2130 bounds: Option<range::Bounds>,
2131 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
2132 mut input_bytes: Option<&mut usize>,
2133) -> Result<QueryPage<Vec<u8>>, Error> {
2134 let mut page = QueryPage {
2135 rows: Vec::new(),
2136 next: None,
2137 examined: 0,
2138 fetched: 0,
2139 output_bytes: 0,
2140 };
2141 let Some(bounds) = bounds else {
2142 return Ok(page);
2143 };
2144 let terminal = range::terminal_key(&bounds, plan.descending);
2145 let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
2146 let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
2147 Some(distinct::Collection::new(
2148 plan.projection.ok_or(Error::InvalidQuery)?,
2149 key_fields,
2150 ))
2151 } else {
2152 None
2153 };
2154 let mut sorted = plan
2155 .sort
2156 .as_ref()
2157 .map(|_| sort::Collection::new(request, plan.distinct));
2158 let mut component = Vec::new();
2159 let mut right_component = Vec::new();
2160 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
2162 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
2163 } else {
2164 None
2165 };
2166 let candidate_bytes = candidate_byte_limit(entity.max_row_bytes);
2167 let primary_type = entity.fields[plan.primary].value;
2168 let needs_spans = plan.index.is_some()
2169 || plan.span_fields != 0
2170 || match &aggregate {
2171 Some(accumulator) => accumulator.needs_spans(),
2172 None => plan.projection.is_some(),
2173 };
2174 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
2176 let mut next_entry = || {
2177 if plan.descending {
2178 entries.next_back()
2179 } else {
2180 entries.next()
2181 }
2182 };
2183 while let Some(entry) = next_entry() {
2184 if page.examined == request.work {
2187 return Err(Error::Limit);
2188 }
2189 page.examined += 1;
2190 let stored_key = entry.key();
2191 let mut read_bytes = stored_key.len();
2192 let (owner, bytes) = if plan.index.is_some() {
2193 let owner_bytes = entry.value();
2194 read_bytes += owner_bytes.len();
2195 read_index_owner(map, entity.id, primary_type, &owner_bytes)?
2196 } else {
2197 (
2198 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
2199 entry.value(),
2200 )
2201 };
2202 if let Some(used) = input_bytes.as_deref_mut() {
2203 read_bytes += bytes.len();
2204 if read_bytes > candidate_bytes {
2205 return Err(Error::Corrupt);
2206 }
2207 *used += read_bytes;
2208 }
2209 page.fetched += 1;
2210 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
2211 entity.inspect_fields(
2212 &bytes,
2213 plan.selected,
2214 &mut values,
2215 needs_spans.then_some(&mut spans),
2216 )?;
2217 if plan.index.is_some() {
2218 validate_index_entry(
2219 entity,
2220 &entity.row_info(&values, &bytes, &spans)?,
2221 owner,
2222 stored_key,
2223 )?;
2224 } else if RowKey::from_index(values[plan.primary])? != owner {
2225 return Err(Error::Corrupt);
2226 }
2227 let read = |position: usize, member: Option<crate::member::RecordMember>| {
2228 if let Some(member) = member {
2229 let (start, end) = spans[position];
2230 member.read(
2231 &bytes[usize::from(start)..usize::from(end)],
2232 entity.fields[position].optional,
2233 )
2234 } else {
2235 Ok(values[position])
2236 }
2237 };
2238 let mut accepts = |term: &Term, supplied: &QueryOperand<'_>| -> Result<bool, Error> {
2239 let mut value = values[term.position];
2240 component.clear();
2241 let (operand, optional) = match &term.operand {
2242 TermOperand::Nested {
2243 member,
2244 literal,
2245 absent,
2246 } => {
2247 value = read(term.position, Some(*member))?;
2248 if *absent {
2249 return Ok(term.comparison.accepts_absent(value == IndexValue::Absent));
2250 }
2251 (
2252 Some(literal.as_slice()),
2253 entity.fields[term.position].optional || member.field().optional,
2254 )
2255 }
2256 TermOperand::Literal { absent: true, .. } => {
2257 let absent = if plan.span_fields & (1 << term.position) != 0 {
2258 bytes[usize::from(spans[term.position].0)] == 0
2259 } else {
2260 value == IndexValue::Absent
2261 };
2262
2263 return Ok(term.comparison.accepts_absent(absent));
2264 }
2265 TermOperand::Member { item, needle } => {
2266 let needle = match (needle, supplied) {
2267 (MemberNeedle::Literal(_), QueryOperand::Literal(value)) => *value,
2268 (MemberNeedle::Field(right, member), QueryOperand::Field(_)) => {
2269 read(*right, *member)?
2270 }
2271 _ => return Err(Error::Corrupt),
2272 };
2273 if needle == IndexValue::Absent {
2274 return Ok(false);
2275 }
2276 let (start, end) = spans[term.position];
2277
2278 return contains_member(
2279 &bytes[usize::from(start)..usize::from(end)],
2280 entity.fields[term.position].optional,
2281 *item,
2282 needle,
2283 );
2284 }
2285 TermOperand::Length { member, threshold } => {
2286 let (start, end) = spans[term.position];
2287 let span = &bytes[usize::from(start)..usize::from(end)];
2288 let optional = entity.fields[term.position].optional;
2289 let actual = if let Some(member) = member {
2290 match member.read(span, optional)? {
2291 IndexValue::Absent => None,
2292 value => Some(scalar_bytes(value).ok_or(Error::Corrupt)?.len() as u32),
2293 }
2294 } else {
2295 crate::codec::validated_length(span, optional)
2296 };
2297
2298 return Ok(term.comparison.accepts_length(actual, *threshold));
2299 }
2300 TermOperand::Literal {
2301 bytes,
2302 absent: false,
2303 } => (
2304 Some(bytes.as_slice()),
2305 entity.fields[term.position].optional,
2306 ),
2307 TermOperand::Field {
2308 right,
2309 left_member,
2310 right_member,
2311 } => {
2312 value = read(term.position, *left_member)?;
2313 let rhs = read(*right, *right_member)?;
2314 if value == IndexValue::Absent || rhs == IndexValue::Absent {
2315 return Ok(term.comparison.accepts_absent(value == rhs));
2316 }
2317 if let Some(matches) = term.comparison.accepts_values(value, rhs) {
2318 return Ok(matches);
2319 }
2320 right_component.clear();
2321 rhs.append_component(false, &mut right_component);
2322
2323 (Some(right_component.as_slice()), false)
2324 }
2325 };
2326 if let QueryOperand::Literal(right) = supplied
2327 && let Some(matches) = term.comparison.accepts_values(value, *right)
2328 {
2329 return Ok(matches);
2330 }
2331 value.append_component(optional, &mut component);
2332
2333 Ok(term.comparison.accepts(
2334 (value != IndexValue::Absent).then_some(component.as_slice()),
2335 operand,
2336 optional,
2337 ))
2338 };
2339 let matches = 'matches: {
2340 let mut clause_matches = false;
2341 for (term, predicate) in plan.terms.iter().zip(&request.predicates) {
2342 clause_matches = clause_matches || accepts(term, &predicate.operand)?;
2343 if !term.or_next {
2344 if !clause_matches {
2345 break 'matches false;
2346 }
2347 clause_matches = false;
2348 }
2349 }
2350
2351 true
2352 };
2353 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
2354 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2355 if matches && let Some(accumulator) = aggregate.as_mut() {
2356 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2357 if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
2358 return Ok(page);
2360 }
2361 } else if matches && let Some(collection) = collected.as_mut() {
2362 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2363 if request.single_result_probe == Some(SingleResult::First) {
2365 break;
2366 }
2367 } else if matches && let Some(collection) = sorted.as_mut() {
2368 collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2369 request.check_result_count(collection.result_count())?;
2371 } else if matches && !duplicate {
2372 request.check_result_count(page.rows.len() + 1)?;
2373 let size = plan
2374 .projection
2375 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2376 if size > request.bytes {
2377 return Err(Error::RowTooLarge);
2378 }
2379 if size > request.bytes - page.output_bytes {
2380 page.next = Some(plan.cursor(stored_key, Resume::Retry));
2381
2382 return Ok(page);
2383 }
2384 page.output_bytes += size;
2385 if let Some(mask) = plan.projection {
2386 page.rows.push(copy_projection(&bytes, &spans, mask, size));
2387 } else {
2388 page.rows.push(bytes);
2389 }
2390 if request.single_result_probe == Some(SingleResult::First)
2391 || plan.distinct.finishes_on_match(plan.fixed_components)
2392 {
2393 return Ok(page);
2394 }
2395 if let Some(boundary) = boundary {
2396 previous = Some(boundary.to_vec());
2397 }
2398 }
2399 if page.rows.len() == request.rows
2400 || page.examined == request.work
2401 || input_bytes
2402 .as_deref()
2403 .is_some_and(|used| *used > STEP_INPUT_BYTES - candidate_bytes)
2404 {
2405 if terminal == Some(stored_key) {
2406 break;
2407 }
2408 if request.single_result_probe.is_some()
2409 || (aggregate.is_some() && input_bytes.is_none())
2410 || collected.is_some()
2411 || sorted.is_some()
2412 {
2413 continue;
2416 }
2417 if input_bytes.is_some() && next_entry().is_none() {
2421 break;
2422 }
2423 let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
2424 Resume::AfterUnemittedClass
2425 } else {
2426 Resume::After
2427 };
2428 page.next = Some(plan.cursor(stored_key, resume));
2429
2430 return Ok(page);
2431 }
2432 }
2433 if let Some(collection) = collected {
2434 page.output_bytes = collection.output_bytes;
2435 page.rows = collection.rows;
2436 }
2437 if let Some(collection) = sorted {
2438 collection.finish(request.bytes, &mut page)?;
2439 }
2440
2441 Ok(page)
2442}