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