1mod aggregate;
4mod distinct;
5mod get_many;
6pub use get_many::{GetMany, SelectedGetMany};
7mod order;
8mod probe;
9mod range;
10mod select;
11mod sort;
12pub use select::{Column, SelectColumns, SelectedQuery, Selection};
13
14pub use aggregate::{
15 Aggregate, GroupCount, GroupOrder, GroupSummaries, GroupSummary, GroupSummaryPage, GroupValue,
16 SummaryMeasure,
17 jobs::{AggregateJobs, GroupCursor, GroupPage, JobHandle, JobOutcome, JobStep},
18};
19
20use super::{
21 Database, ENTITY_PREFIX_BYTES, INDEX_PREFIX_BYTES, Map, prefix, read_index_owner,
22 validate_index_entry,
23};
24use crate::{
25 Entity, EntitySchema, Error, FieldType, IndexSchema, IndexValue, TypeBody, TypeSchema, Value,
26 codec::Decoder, key, named_schema::TypeGraph, primary::RowKey,
27};
28use ic_storage::Memory;
29use sha2::{Digest, Sha256};
30use std::{
31 cell::{Ref, RefCell},
32 marker::PhantomData,
33 ops::Deref,
34 rc::Rc,
35};
36
37const MAX_TERMS: usize = 8;
38const MAX_WORK: usize = 512;
39const MAX_OUTPUT: usize = 128 * 1024;
40const MAX_COMPARISON_KEY: usize = 4096;
41const MAX_DISTINCT_VALUES: usize = 32;
42const MAX_STATE_BYTES: usize = 128 * 1024;
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum SortDirection {
47 Ascending,
49 Descending,
51}
52
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55#[repr(u8)]
56pub enum Comparison {
57 Eq = 0,
59 Ne = 1,
61 Lt = 2,
63 Le = 3,
65 Gt = 4,
67 Ge = 5,
69 StartsWith = 6,
73 EndsWith = 7,
76 Contains = 8,
80}
81
82impl Comparison {
83 fn supports_record_member(self) -> bool {
84 self.is_relational() || matches!(self, Self::StartsWith | Self::EndsWith)
85 }
86
87 fn is_relational(self) -> bool {
88 matches!(
89 self,
90 Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge
91 )
92 }
93
94 fn supports_scalar(self, field: FieldType) -> bool {
95 self.is_relational()
96 || matches!(
97 key::operand_type(field),
98 FieldType::Text { .. } | FieldType::Blob { .. }
99 )
100 }
101
102 fn admit(self, field: FieldType, optional: bool, value: IndexValue<'_>) -> Result<(), Error> {
103 value.admit(field, optional)?;
104 if !self.supports_scalar(field) {
105 return Err(Error::InvalidQuery);
106 }
107 if value == IndexValue::Absent && !matches!(self, Self::Eq | Self::Ne) {
108 return Err(Error::InvalidOperand);
109 }
110
111 Ok(())
112 }
113
114 fn accepts(self, actual: Option<&[u8]>, operand: Option<&[u8]>, optional: bool) -> bool {
115 if actual.is_none() {
116 return self.accepts_absent(operand.is_none());
117 }
118
119 match self {
120 Self::Eq => actual == operand,
121 Self::Ne => actual != operand,
122 Self::StartsWith | Self::EndsWith | Self::Contains => {
123 fn content(key: &[u8], optional: bool) -> Option<&[u8]> {
126 crate::key::bytes_prefix(key.get(usize::from(optional)..)?)
127 }
128
129 actual
130 .and_then(|key| content(key, optional))
131 .zip(operand.and_then(|key| content(key, optional)))
132 .is_some_and(|(actual, operand)| match self {
133 Self::StartsWith => actual.starts_with(operand),
136 Self::EndsWith => actual
140 .strip_suffix(operand)
141 .is_some_and(|prefix| prefix.last() != Some(&0)),
142 _ => contains_component(actual, operand),
143 })
144 }
145 _ if actual.is_none() || operand.is_none() => false,
146 Self::Lt => actual < operand,
147 Self::Le => actual <= operand,
148 Self::Gt => actual > operand,
149 Self::Ge => actual >= operand,
150 }
151 }
152
153 fn accepts_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
155 match self {
156 Self::Eq => Some(equal_values(left, right)),
157 Self::Ne => Some(!equal_values(left, right)),
158 _ => Some(self.accepts_bytes(scalar_bytes(left)?, scalar_bytes(right)?)),
159 }
160 }
161
162 fn accepts_fixed_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
164 if left == IndexValue::Absent || right == IndexValue::Absent {
165 return Some(self.accepts_absent(left == right));
166 }
167 if let Some(result) = self.accepts_values(left, right) {
168 return Some(result);
169 }
170 match self {
171 Comparison::Lt | Comparison::Le | Comparison::Gt | Comparison::Ge => {
172 let mut encoded = Vec::new();
174 left.append_component(false, &mut encoded);
175 let split = encoded.len();
176 right.append_component(false, &mut encoded);
177 let (left, right) = encoded.split_at(split);
178
179 Some(self.accepts(Some(left), Some(right), false))
180 }
181 _ => None,
182 }
183 }
184
185 fn accepts_bytes(self, actual: &[u8], operand: &[u8]) -> bool {
187 match self {
188 Self::StartsWith => actual.starts_with(operand),
189 Self::EndsWith => actual.ends_with(operand),
190 Self::Contains => memchr::memmem::find(actual, operand).is_some(),
191 _ => self.accepts(Some(actual), Some(operand), false),
192 }
193 }
194
195 fn accepts_length(self, actual: Option<u32>, threshold: u32) -> bool {
196 let encoded = actual.map(u32::to_be_bytes);
197
198 self.accepts(
199 encoded.as_ref().map(|v| v.as_slice()),
200 Some(&threshold.to_be_bytes()),
201 false,
202 )
203 }
204
205 fn empty_length_value(self, threshold: u32, field: FieldType) -> Option<IndexValue<'static>> {
207 if !matches!((self, threshold), (Self::Eq | Self::Le, 0) | (Self::Lt, 1)) {
208 return None;
209 }
210 match key::operand_type(field) {
211 FieldType::Text { .. } => Some(IndexValue::Text("")),
212 FieldType::Blob { .. } => Some(IndexValue::Blob(&[])),
213 _ => None,
214 }
215 }
216
217 fn uniform_length_result(self, min: u32, max: u32, n: u32) -> Option<bool> {
219 match self {
220 Self::Eq | Self::Ne if min == max || n < min || n > max => {
221 Some(self.accepts_length(Some(min), n))
222 }
223 Self::Lt | Self::Ge if max < n || min >= n => Some(self.accepts_length(Some(min), n)),
224 Self::Le | Self::Gt if max <= n || min > n => Some(self.accepts_length(Some(min), n)),
225 _ => None,
226 }
227 }
228
229 fn accepts_absent(self, other_absent: bool) -> bool {
232 match self {
233 Self::Eq => other_absent,
234 Self::Ne => !other_absent,
235 _ => false,
236 }
237 }
238}
239
240fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
242 let Some(start) = memchr::memmem::find(actual, needle) else {
243 return false;
244 };
245 if start == 0 || actual[start - 1] != 0 {
246 return true;
247 }
248 fn raw(content: &[u8]) -> Vec<u8> {
252 let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
253 let mut encoded = content.iter();
254 while let Some(&byte) = encoded.next() {
255 bytes.push(byte);
256 if byte == 0 {
257 encoded.next();
258 }
259 }
260
261 bytes
262 }
263
264 memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
265}
266
267#[derive(Clone, Debug, PartialEq, Eq)]
271pub struct QueryCursor {
272 binding: [u8; 32],
273 position: Vec<u8>,
274 resume: Resume,
275}
276
277#[derive(Clone, Copy, Debug, PartialEq, Eq)]
278enum Resume {
279 After = 0,
280 Retry = 1,
281 AfterUnemittedClass = 2,
282}
283impl QueryCursor {
284 pub(crate) const MAX_ENCODED_BYTES: usize = 34 + crate::MAX_INDEX_KEY_BYTES;
285
286 #[must_use]
288 pub fn to_bytes(&self) -> Vec<u8> {
289 let mut bytes = vec![1, self.resume as u8];
290 bytes.extend(self.binding);
291 bytes.extend(&self.position);
292
293 bytes
294 }
295
296 pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
300 if !(35..=Self::MAX_ENCODED_BYTES).contains(&bytes.len()) || bytes[0] != 1 {
301 return Err(Error::InvalidCursor);
302 }
303
304 Ok(Self {
305 binding: bytes[2..34].try_into().map_err(|_| Error::InvalidCursor)?,
306 position: bytes[34..].to_vec(),
307 resume: match bytes[1] {
308 0 => Resume::After,
309 1 => Resume::Retry,
310 2 => Resume::AfterUnemittedClass,
311 _ => return Err(Error::InvalidCursor),
312 },
313 })
314 }
315}
316
317impl serde::Serialize for QueryCursor {
318 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
319 serializer.serialize_bytes(&self.to_bytes())
320 }
321}
322
323impl<'de> serde::Deserialize<'de> for QueryCursor {
324 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
325 struct Frame;
326
327 impl<'de> serde::de::Visitor<'de> for Frame {
328 type Value = QueryCursor;
329
330 fn expecting(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
331 fmt.write_str("a bounded IC DB query cursor frame")
332 }
333
334 fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<QueryCursor, E> {
335 QueryCursor::from_bytes(bytes).map_err(E::custom)
336 }
337
338 fn visit_seq<A: serde::de::SeqAccess<'de>>(
339 self,
340 mut seq: A,
341 ) -> Result<QueryCursor, A::Error> {
342 let size = seq.size_hint().unwrap_or(0);
343 if size > QueryCursor::MAX_ENCODED_BYTES {
344 return Err(serde::de::Error::custom(Error::InvalidCursor));
345 }
346 let mut frame = Vec::with_capacity(size);
347 while let Some(byte) = seq.next_element()? {
348 if frame.len() == QueryCursor::MAX_ENCODED_BYTES {
349 return Err(serde::de::Error::custom(Error::InvalidCursor));
350 }
351 frame.push(byte);
352 }
353 QueryCursor::from_bytes(&frame).map_err(serde::de::Error::custom)
354 }
355 }
356
357 deserializer.deserialize_bytes(Frame)
358 }
359}
360
361#[derive(Debug)]
364pub struct QueryPage<T> {
365 pub rows: Vec<T>,
367 pub next: Option<QueryCursor>,
369 pub examined: usize,
371 pub fetched: usize,
373 pub output_bytes: usize,
375}
376
377impl QueryPage<Vec<u8>> {
378 #[inline(never)]
379 pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
380 Ok(QueryPage {
381 rows: self
382 .rows
383 .iter()
384 .map(|bytes| E::decode(bytes))
385 .collect::<Result<_, _>>()?,
386 next: self.next,
387 examined: self.examined,
388 fetched: self.fetched,
389 output_bytes: self.output_bytes,
390 })
391 }
392
393 #[inline(never)]
394 fn decode_with<R>(
395 self,
396 decode: impl Fn(&mut Decoder<'_>) -> Result<R, Error>,
397 ) -> Result<QueryPage<R>, Error> {
398 Ok(QueryPage {
399 rows: self
400 .rows
401 .iter()
402 .map(|bytes| {
403 let mut reader = Decoder::new(bytes)?;
404 let row = decode(&mut reader)?;
406 reader.finish()?;
407
408 Ok(row)
409 })
410 .collect::<Result<_, Error>>()?,
411 next: self.next,
412 examined: self.examined,
413 fetched: self.fetched,
414 output_bytes: self.output_bytes,
415 })
416 }
417}
418
419#[derive(Clone, Copy, Debug, PartialEq, Eq)]
421pub enum QueryOperand<'a> {
422 Literal(IndexValue<'a>),
424 Length(u32),
426 Field(&'a str),
428}
429
430struct Predicate<'a> {
431 field: &'a str,
432 comparison: Comparison,
433 operand: QueryOperand<'a>,
434 or_next: bool,
436}
437
438impl<'a> Predicate<'a> {
439 fn compared_field(&self, name: &str) -> Option<&'a str> {
441 let QueryOperand::Field(right) = self.operand else {
442 return None;
443 };
444 if self.field == name {
445 Some(right)
446 } else if right == name {
447 Some(self.field)
448 } else {
449 None
450 }
451 }
452
453 fn at_extreme(&self, entity: &EntitySchema, value: IndexValue<'_>, upper: bool) -> bool {
455 use crate::{Date, Duration, Timestamp, Ulid};
456
457 match value {
458 IndexValue::Bool(b) => b == upper,
459 IndexValue::Date(d) => d == if upper { Date::MAX } else { Date::MIN },
460 IndexValue::Timestamp(t) => {
461 t == if upper {
462 Timestamp::MAX
463 } else {
464 Timestamp::MIN
465 }
466 }
467 IndexValue::Duration(d) => d == if upper { Duration::MAX } else { Duration::MIN },
468 IndexValue::Ulid(id) => id == if upper { Ulid::MAX } else { Ulid::MIN },
469 IndexValue::UnitEnum { ordinal, .. } => entity
470 .index_field(self.field)
471 .is_some_and(|field| key::is_fixed_extreme(field.value, &[ordinal], upper)),
472 IndexValue::Text("") | IndexValue::Blob([]) => !upper,
473 _ => value.is_integer_extreme(upper),
474 }
475 }
476
477 fn fixed_equality(&self, entity: &EntitySchema) -> Option<(&'a str, IndexValue<'a>)> {
479 if let QueryOperand::Length(n) = self.operand {
480 let empty = self
481 .comparison
482 .empty_length_value(n, entity.index_field(self.field)?.value)?;
483 return Some((self.field, empty));
484 }
485 let QueryOperand::Literal(value) = self.operand else {
486 return None;
487 };
488 let fixed = match (self.comparison, value) {
490 (Comparison::Eq, _) => value,
491 (Comparison::Ne, IndexValue::Bool(excluded))
492 if entity.field_is_required(self.field) =>
493 {
494 IndexValue::Bool(!excluded)
495 }
496 (cmp @ (Comparison::Ge | Comparison::Le), _)
497 if self.at_extreme(entity, value, cmp == Comparison::Ge) =>
498 {
499 value
500 }
501 (Comparison::Gt, IndexValue::Bool(false)) => IndexValue::Bool(true),
502 (Comparison::Lt, IndexValue::Bool(true)) => IndexValue::Bool(false),
503 _ => return None,
504 };
505 Some((self.field, fixed))
506 }
507
508 fn tests_presence(&self, entity: &EntitySchema, operand: &TermOperand) -> bool {
510 match (self.comparison, self.operand) {
511 (Comparison::Ne, QueryOperand::Literal(IndexValue::Absent)) => true,
512 (cmp @ (Comparison::Le | Comparison::Ge), QueryOperand::Literal(value)) => {
513 self.at_extreme(entity, value, cmp == Comparison::Le)
514 }
515 (_, QueryOperand::Length(_)) => {
516 self.present_length_result(entity) == Some(true)
517 && self.comparison != Comparison::Ne
518 }
519 (
520 Comparison::Le
521 | Comparison::Ge
522 | Comparison::StartsWith
523 | Comparison::EndsWith
524 | Comparison::Contains,
525 QueryOperand::Field(right),
526 ) => right == self.field,
527 (
528 Comparison::StartsWith | Comparison::EndsWith | Comparison::Contains,
529 QueryOperand::Literal(needle),
530 ) => {
531 !matches!(operand, TermOperand::Member { .. })
533 && scalar_bytes(needle).is_some_and(<[u8]>::is_empty)
534 }
535 _ => false,
536 }
537 }
538
539 fn present_length_result(&self, entity: &EntitySchema) -> Option<bool> {
541 let QueryOperand::Length(n) = self.operand else {
542 return None;
543 };
544 let max = length_limit(entity.index_field(self.field)?.value)?;
545 self.comparison.uniform_length_result(0, max, n)
546 }
547
548 fn constant_comparison(&self, entity: &EntitySchema) -> Option<bool> {
549 if let QueryOperand::Literal(value) = self.operand {
550 return match (self.comparison, value) {
552 (cmp @ (Comparison::Lt | Comparison::Gt), value)
553 if self.at_extreme(entity, value, cmp == Comparison::Gt) =>
554 {
555 Some(false)
556 }
557 _ => None,
558 };
559 }
560 if matches!(self.operand, QueryOperand::Length(_)) {
561 let result = self.present_length_result(entity)?;
562 return (result == self.comparison.accepts_absent(false)
563 || entity.field_is_required(self.field))
564 .then_some(result);
565 }
566 if !matches!(self.operand, QueryOperand::Field(right) if right == self.field) {
567 return None;
568 }
569 match self.comparison {
570 Comparison::Eq => Some(true),
571 Comparison::Ne | Comparison::Lt | Comparison::Gt => Some(false),
572 _ => None,
573 }
574 }
575}
576
577#[derive(Clone, Copy, PartialEq, Eq)]
578enum SingleResult {
579 First,
580 Only,
581}
582
583struct Request<'a> {
584 groups: aggregate::GroupRequest<'a>,
585 predicates: Vec<Predicate<'a>>,
586 index: Option<(&'a str, Vec<IndexValue<'a>>)>,
587 order: Option<Vec<&'a str>>,
588 order_descending: u8,
589 descending: bool,
590 distinct: bool,
591 single_result_probe: Option<SingleResult>,
592 rows: usize,
593 work: usize,
594 bytes: usize,
595 cursor: Option<&'a QueryCursor>,
596 over_limit: bool,
597}
598
599impl Default for Request<'_> {
600 fn default() -> Self {
601 Self {
602 groups: aggregate::GroupRequest::default(),
603 predicates: Vec::new(),
604 index: None,
605 order: None,
606 order_descending: 0,
607 descending: false,
608 distinct: false,
609 single_result_probe: None,
610 rows: 32,
611 work: 128,
612 bytes: MAX_OUTPUT,
613 cursor: None,
614 over_limit: false,
615 }
616 }
617}
618
619impl<'a> Request<'a> {
622 fn within_limits(&self) -> bool {
623 !self.over_limit
624 && (1..=32).contains(&self.rows)
625 && (1..=MAX_WORK).contains(&self.work)
626 && (1..=MAX_OUTPUT).contains(&self.bytes)
627 }
628
629 fn check_result_count(&self, count: usize) -> Result<(), Error> {
632 if self.single_result_probe == Some(SingleResult::Only) && count > 1 {
633 return Err(Error::MultipleMatches);
634 }
635 Ok(())
636 }
637
638 fn fixed_equalities<'r>(
640 &'r self,
641 entity: &'r EntitySchema,
642 ) -> impl Iterator<Item = (&'a str, IndexValue<'a>)> + 'r {
643 self.clauses().filter_map(move |clause| {
644 let (predicate, rest) = clause.split_first()?;
645 if !rest.is_empty() {
646 let mut candidate = predicate.fixed_equality(entity)?;
647 for alternative in rest {
648 let other = alternative.fixed_equality(entity)?;
649 if candidate.0 != other.0 {
650 return None;
651 }
652 if equal_values(candidate.1, other.1) {
653 continue;
654 }
655 if self.predicates.len() == clause.len() {
656 return None;
657 }
658 if self.excludes_literal(other.0, other.1) {
659 continue;
660 }
661 if !self.excludes_literal(candidate.0, candidate.1) {
662 return None;
663 }
664 candidate = other;
665 }
666 return Some(candidate);
669 }
670 if let Some(equality) = predicate.fixed_equality(entity) {
671 return Some(equality);
672 }
673 let QueryOperand::Literal(value) = predicate.operand else {
676 return None;
677 };
678 let lower = match predicate.comparison {
679 Comparison::Ge => value,
680 Comparison::Gt if self.predicates.len() > 1 => value.discrete_successor()?,
681 _ => return None,
682 };
683 self.clauses()
684 .any(|clause| {
685 let [upper] = clause else { return false };
686 if upper.field != predicate.field {
687 return false;
688 }
689 match (upper.comparison, upper.operand) {
690 (Comparison::Le, QueryOperand::Literal(value)) => {
691 equal_values(lower, value)
692 }
693 (Comparison::Lt, QueryOperand::Literal(value)) => {
694 consecutive_values(lower, value)
695 }
696 _ => false,
697 }
698 })
699 .then_some((predicate.field, lower))
700 })
701 }
702
703 fn excludes_literal(&self, field: &str, value: IndexValue<'_>) -> bool {
704 self.clauses().any(|clause| {
707 clause.iter().all(|predicate| {
708 if predicate.field != field {
709 return false;
710 }
711 let QueryOperand::Literal(literal) = predicate.operand else {
712 return false;
713 };
714 match predicate.comparison {
715 Comparison::Eq
716 | Comparison::Ne
717 | Comparison::Lt
718 | Comparison::Le
719 | Comparison::Gt
720 | Comparison::Ge => {
721 predicate.comparison.accepts_fixed_values(value, literal) == Some(false)
722 }
723 _ => false,
724 }
725 })
726 })
727 }
728
729 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
730 self.predicates.split_inclusive(|p| !p.or_next)
731 }
732
733 #[inline(never)]
734 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
735 if self.predicates.len() == MAX_TERMS {
736 self.over_limit = true;
737 } else {
738 self.predicates.push(Predicate {
739 field,
740 comparison,
741 operand,
742 or_next: false,
743 });
744 }
745 }
746
747 #[inline(never)]
748 fn or_clause(
749 &mut self,
750 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
751 ) {
752 let count = alternatives.len();
753
754 if count == 0 || count > MAX_TERMS - self.predicates.len() {
755 self.over_limit = true;
756 } else {
757 self.predicates.extend(alternatives.enumerate().map(
758 |(i, (field, comparison, operand))| Predicate {
759 field,
760 comparison,
761 operand,
762 or_next: i + 1 < count,
763 },
764 ));
765 }
766 }
767
768 #[inline(never)]
769 fn filter_not_in(
770 &mut self,
771 field: &'a str,
772 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
773 ) {
774 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
775 self.over_limit = true;
776
777 return;
778 }
779 for value in values {
780 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
781 }
782 }
783
784 #[inline(never)]
785 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
786 if values.len() > 4 {
787 self.over_limit = true;
788 } else {
789 self.index = Some((name, values.to_vec()));
790 }
791 }
792
793 #[inline(never)]
794 fn order_by(&mut self, fields: &[&'a str]) {
795 self.order_descending = 0;
796
797 if fields.len() > 4 {
798 self.over_limit = true;
799 } else {
800 self.order = Some(fields.to_vec());
801 }
802 }
803
804 #[inline(never)]
805 fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
806 if fields.len() > 4 {
807 self.over_limit = true;
808
809 return;
810 }
811 self.order = Some(Vec::with_capacity(fields.len()));
812 self.order_descending = 0;
813 for &(field, direction) in fields {
814 self.append_order(field, direction);
815 }
816 }
817
818 fn append_order(&mut self, field: &'a str, direction: SortDirection) {
819 let fields = self.order.get_or_insert_with(Vec::new);
820 if fields.len() == 4 {
821 self.over_limit = true;
822
823 return;
824 }
825 if direction == SortDirection::Descending {
826 self.order_descending |= 1 << fields.len();
827 }
828 fields.push(field);
829 }
830
831 fn primary_descending(&self, entity: &EntitySchema) -> bool {
832 self.order_descending != 0
833 && self.order.as_ref().is_some_and(|fields| {
834 fields.last() == Some(&entity.primary_key)
835 && self.order_descending & (1 << (fields.len() - 1)) != 0
836 })
837 }
838}
839
840pub(super) fn source_page<M: Memory>(
842 map: &Map<M>,
843 entity: &EntitySchema,
844 binding: [u8; 32],
845 incarnation: [u8; 16],
846 cursor: Option<&QueryCursor>,
847 rows: usize,
848 bytes: usize,
849) -> Result<QueryPage<Vec<u8>>, Error> {
850 let request = Request {
851 rows,
852 work: rows,
853 bytes,
854 cursor,
855 ..Request::default()
856 };
857 let plan = Plan::admit(
858 entity,
859 &request,
860 binding,
861 incarnation,
862 None,
863 PlanOutput::Rows,
864 )?;
865
866 execute(map, entity, &request, &plan, None)
867}
868
869enum QuerySource<'a, M: Memory> {
870 Direct(&'a Database<M>),
871 Session(Rc<RefCell<Database<M>>>),
872}
873
874enum QueryRead<'a, M: Memory> {
875 Direct(&'a Database<M>),
876 Session(Ref<'a, Database<M>>),
877}
878
879impl<M: Memory> Deref for QueryRead<'_, M> {
880 type Target = Database<M>;
881
882 fn deref(&self) -> &Self::Target {
883 match self {
884 Self::Direct(db) => db,
885 Self::Session(db) => db,
886 }
887 }
888}
889
890impl<M: Memory> QuerySource<'_, M> {
891 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
892 match self {
893 Self::Direct(db) => Ok(QueryRead::Direct(db)),
894 Self::Session(db) => db
895 .try_borrow()
896 .map(QueryRead::Session)
897 .map_err(|_| Error::BorrowConflict),
898 }
899 }
900}
901
902pub struct Query<'a, E, M: Memory> {
906 db: QuerySource<'a, M>,
907 request: Request<'a>,
908 entity: PhantomData<E>,
909}
910impl<M: Memory> Database<M> {
911 #[must_use]
913 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
914 Query {
915 db: QuerySource::Direct(self),
916 entity: PhantomData,
917 request: Request::default(),
918 }
919 }
920}
921impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
922 pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
923 Self {
924 db: QuerySource::Session(db),
925 request: Request::default(),
926 entity: PhantomData,
927 }
928 }
929
930 #[must_use]
944 pub fn distinct(mut self) -> Self {
945 self.request.distinct = true;
946
947 self
948 }
949
950 #[must_use]
963 pub fn filter(
964 mut self,
965 field: &'a str,
966 comparison: Comparison,
967 value: impl Into<IndexValue<'a>>,
968 ) -> Self {
969 self.request
970 .filter(field, comparison, QueryOperand::Literal(value.into()));
971
972 self
973 }
974
975 #[must_use]
977 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
978 self.filter(field, Comparison::Eq, value)
979 }
980
981 #[must_use]
983 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
984 self.filter(field, Comparison::Ne, value)
985 }
986
987 #[must_use]
989 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
990 self.filter(field, Comparison::Lt, value)
991 }
992
993 #[must_use]
995 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
996 self.filter(field, Comparison::Le, value)
997 }
998
999 #[must_use]
1001 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
1002 self.filter(field, Comparison::Gt, value)
1003 }
1004
1005 #[must_use]
1007 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
1008 self.filter(field, Comparison::Ge, value)
1009 }
1010
1011 #[must_use]
1019 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
1020 self.request
1021 .filter(left, comparison, QueryOperand::Field(right));
1022
1023 self
1024 }
1025
1026 #[must_use]
1031 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
1032 self.request
1033 .filter(field, comparison, QueryOperand::Length(length));
1034
1035 self
1036 }
1037
1038 #[must_use]
1041 pub fn filter_present(self, field: &'a str) -> Self {
1042 self.filter(field, Comparison::Ne, IndexValue::Absent)
1043 }
1044
1045 #[must_use]
1048 pub fn filter_absent(self, field: &'a str) -> Self {
1049 self.filter(field, Comparison::Eq, IndexValue::Absent)
1050 }
1051
1052 #[must_use]
1056 pub fn filter_range<T: Into<IndexValue<'a>>>(
1057 self,
1058 field: &'a str,
1059 range: std::ops::Range<T>,
1060 ) -> Self {
1061 self.gte(field, range.start).lt(field, range.end)
1062 }
1063
1064 #[must_use]
1068 pub fn filter_ulid_time(
1069 self,
1070 field: &'a str,
1071 range: std::ops::Range<crate::Timestamp>,
1072 ) -> Self {
1073 let (first, last) =
1074 crate::Ulid::time_bounds(range).unwrap_or((crate::Ulid::MAX, crate::Ulid::MIN));
1075 self.filter_between(field, first, last)
1076 }
1077
1078 #[must_use]
1085 pub fn filter_between(
1086 self,
1087 field: &'a str,
1088 lower: impl Into<IndexValue<'a>>,
1089 upper: impl Into<IndexValue<'a>>,
1090 ) -> Self {
1091 self.filter(field, Comparison::Ge, lower)
1092 .filter(field, Comparison::Le, upper)
1093 }
1094
1095 #[must_use]
1103 pub fn filter_not_between(
1104 self,
1105 field: &'a str,
1106 lower: impl Into<IndexValue<'a>>,
1107 upper: impl Into<IndexValue<'a>>,
1108 ) -> Self {
1109 self.filter_any(&[
1110 (field, Comparison::Lt, lower.into()),
1111 (field, Comparison::Gt, upper.into()),
1112 ])
1113 }
1114
1115 #[must_use]
1120 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1121 self.filter_fields(field, Comparison::Ge, lower)
1122 .filter_fields(field, Comparison::Le, upper)
1123 }
1124
1125 #[must_use]
1130 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1131 self.filter_any_operands(&[
1132 (field, Comparison::Lt, QueryOperand::Field(lower)),
1133 (field, Comparison::Gt, QueryOperand::Field(upper)),
1134 ])
1135 }
1136
1137 #[must_use]
1145 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
1146 self.request.or_clause(
1147 alternatives
1148 .iter()
1149 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
1150 );
1151
1152 self
1153 }
1154
1155 #[must_use]
1160 pub fn filter_any_operands(
1161 mut self,
1162 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
1163 ) -> Self {
1164 self.request.or_clause(alternatives.iter().copied());
1165
1166 self
1167 }
1168
1169 #[must_use]
1179 pub fn filter_in(
1180 mut self,
1181 field: &'a str,
1182 values: &[impl Copy + Into<IndexValue<'a>>],
1183 ) -> Self {
1184 self.request.or_clause(
1185 values
1186 .iter()
1187 .copied()
1188 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
1189 );
1190
1191 self
1192 }
1193
1194 #[must_use]
1202 pub fn filter_not_in(
1203 mut self,
1204 field: &'a str,
1205 values: &[impl Copy + Into<IndexValue<'a>>],
1206 ) -> Self {
1207 self.request
1208 .filter_not_in(field, values.iter().copied().map(Into::into));
1209
1210 self
1211 }
1212
1213 #[must_use]
1218 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
1219 self.request.using_index(name, values);
1220
1221 self
1222 }
1223
1224 #[must_use]
1227 pub fn order_asc(mut self, field: &'a str) -> Self {
1228 self.request.append_order(field, SortDirection::Ascending);
1229
1230 self
1231 }
1232
1233 #[must_use]
1236 pub fn order_desc(mut self, field: &'a str) -> Self {
1237 self.request.append_order(field, SortDirection::Descending);
1238
1239 self
1240 }
1241
1242 #[must_use]
1253 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
1254 self.request.order_by(fields);
1255
1256 self
1257 }
1258
1259 #[must_use]
1264 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
1265 self.request.order_by_each(fields);
1266
1267 self
1268 }
1269
1270 #[must_use]
1272 pub fn descending(mut self) -> Self {
1273 self.request.descending = true;
1274
1275 self
1276 }
1277
1278 #[must_use]
1285 pub fn limit(mut self, rows: usize) -> Self {
1286 self.request.rows = rows;
1287
1288 self
1289 }
1290
1291 #[must_use]
1293 pub fn work_limit(mut self, candidates: usize) -> Self {
1294 self.request.work = candidates;
1295
1296 self
1297 }
1298
1299 #[cfg(feature = "test-support")]
1301 #[doc(hidden)]
1302 #[must_use]
1303 pub fn test_output_limit(mut self, bytes: usize) -> Self {
1304 self.request.bytes = bytes;
1305
1306 self
1307 }
1308
1309 #[must_use]
1311 pub fn after(self, cursor: &'a QueryCursor) -> Self {
1312 self.after_optional(Some(cursor))
1313 }
1314
1315 #[must_use]
1317 pub fn after_optional(mut self, cursor: Option<&'a QueryCursor>) -> Self {
1318 self.request.cursor = cursor;
1319
1320 self
1321 }
1322
1323 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
1330 observe!(query, { self.entity_page() })
1331 }
1332
1333 fn entity_page(self) -> Result<QueryPage<E>, Error> {
1334 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
1335 }
1336
1337 pub fn first(self) -> Result<Option<E>, Error> {
1343 self.first_with(Self::entity_page)
1344 }
1345
1346 pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
1350 self.first_with(Self::projected_page::<R>)
1351 }
1352
1353 fn first_with<R>(
1354 self,
1355 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1356 ) -> Result<Option<R>, Error> {
1357 observe!(query, { fetch(self.probe_matches(SingleResult::First)?) })
1358 .map(|mut page| page.rows.pop())
1359 }
1360
1361 pub fn try_one(self) -> Result<Option<E>, Error> {
1368 self.try_one_with(Self::entity_page)
1369 }
1370
1371 pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
1377 self.try_one_with(Self::projected_page::<R>)
1378 }
1379
1380 fn try_one_with<R>(
1381 self,
1382 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1383 ) -> Result<Option<R>, Error> {
1384 observe!(query, {
1385 if self.request.cursor.is_some() {
1386 return Err(Error::InvalidQuery);
1387 }
1388 fetch(self.probe_matches(SingleResult::Only)?)
1389 })
1390 .map(|mut page| page.rows.pop())
1391 }
1392
1393 fn probe_matches(mut self, probe: SingleResult) -> Result<Self, Error> {
1394 if !(1..=32).contains(&self.request.rows) {
1395 return Err(Error::Limit);
1396 }
1397
1398 self.request.single_result_probe = Some(probe);
1399
1400 Ok(self.limit(match probe {
1401 SingleResult::First => 1,
1402 SingleResult::Only => 2,
1403 }))
1404 }
1405
1406 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1416 observe!(query, { self.projected_page() })
1417 }
1418
1419 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1420 let raw = fetch_rows(
1421 &*self.db.read()?,
1422 E::SCHEMA,
1423 self.request,
1424 Some(Projection::Record(R::definition())),
1425 )?;
1426
1427 raw.decode_with(R::decode_from)
1428 }
1429}
1430
1431#[derive(Clone, Copy)]
1432enum Projection<'a> {
1433 Record(&'a TypeSchema),
1434 Columns(&'a [u8]),
1435}
1436
1437impl Projection<'_> {
1438 fn mask(self, entity: &EntitySchema) -> Result<u32, Error> {
1439 match self {
1440 Self::Record(record) => admit_projection(entity, record),
1441 Self::Columns(columns) => {
1442 let mut mask = 0;
1443 for &column in columns {
1444 if usize::from(column) >= entity.fields.len() || mask & (1 << column) != 0 {
1445 return Err(Error::InvalidQuery);
1446 }
1447 mask |= 1 << column;
1448 }
1449 Ok(mask)
1450 }
1451 }
1452 }
1453}
1454
1455fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u32, Error> {
1459 let TypeBody::Record(fields) = &output.body else {
1460 return Err(Error::InvalidQuery);
1461 };
1462 if fields.is_empty()
1463 || fields.len() > crate::schema::MAX_FIELDS
1464 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1465 {
1466 return Err(Error::InvalidQuery);
1467 }
1468 let mut source = TypeGraph::default();
1469 let mut target = TypeGraph::default();
1470 let mut mask = 0;
1471 for field in *fields {
1472 let position = entity
1473 .field_position(field.name)
1474 .ok_or(Error::InvalidQuery)?;
1475 let stored = &entity.fields[position];
1476 if stored.value != field.value || stored.optional != field.optional {
1477 return Err(Error::InvalidQuery);
1478 }
1479 source
1480 .include(stored.value)
1481 .map_err(|_| Error::InvalidQuery)?;
1482 target
1483 .include(field.value)
1484 .map_err(|_| Error::InvalidQuery)?;
1485 mask |= 1 << position;
1486 }
1487 if !source.contains(&target) {
1488 return Err(Error::InvalidQuery);
1489 }
1490
1491 Ok(mask)
1492}
1493
1494struct Term {
1495 tests_presence: bool,
1496 position: usize,
1497 comparison: Comparison,
1498 operand: TermOperand,
1499 or_next: bool,
1500}
1501
1502enum TermOperand {
1503 Literal {
1504 bytes: Vec<u8>,
1505 absent: bool,
1506 },
1507 Member {
1508 item: FieldType,
1509 needle: MemberNeedle,
1510 },
1511 Nested {
1512 member: crate::member::RecordMember,
1513 literal: Vec<u8>,
1514 absent: bool,
1515 },
1516 Field {
1517 right: usize,
1518 left_member: Option<crate::member::RecordMember>,
1519 right_member: Option<crate::member::RecordMember>,
1520 },
1521 Length {
1522 member: Option<crate::member::RecordMember>,
1523 threshold: u32,
1524 },
1525}
1526
1527enum MemberNeedle {
1528 Literal(Vec<u8>),
1529 Field(usize, Option<crate::member::RecordMember>),
1530}
1531
1532fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1535 match value {
1536 IndexValue::Text(text) => Some(text.as_bytes()),
1537 IndexValue::Blob(bytes) => Some(bytes),
1538 _ => None,
1539 }
1540}
1541
1542fn consecutive_values(low: IndexValue<'_>, high: IndexValue<'_>) -> bool {
1543 low.discrete_successor()
1544 .is_some_and(|next| equal_values(next, high))
1545}
1546
1547fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1548 match (left, right) {
1550 (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1551 a == b
1552 }
1553 _ => left == right,
1554 }
1555}
1556
1557fn length_limit(field: FieldType) -> Option<u32> {
1558 match key::operand_type(field) {
1559 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1560 FieldType::List { max_items, .. } => Some(max_items),
1561 FieldType::Named(link) => match (link.definition)().body {
1562 TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1563 _ => None,
1564 },
1565 _ => None,
1566 }
1567}
1568
1569fn member_type(field: FieldType) -> Option<FieldType> {
1570 match key::operand_type(field) {
1571 FieldType::List { item, .. } => Some(*item),
1572 FieldType::Named(link) => match (link.definition)().body {
1573 TypeBody::Set { item, .. } => Some(item),
1574 _ => None,
1575 },
1576 _ => None,
1577 }
1578}
1579
1580fn contains_member(
1582 span: &[u8],
1583 optional: bool,
1584 item: FieldType,
1585 needle: IndexValue<'_>,
1586) -> Result<bool, Error> {
1587 let mut reader = Decoder::new(span)?;
1588 if optional && !reader.boolean()? {
1589 return Ok(false);
1590 }
1591 for _ in 0..reader.nat32()? {
1592 let value = IndexValue::read(&mut reader, item)?;
1593 if equal_values(value, needle) {
1594 return Ok(true);
1595 }
1596 }
1597
1598 Ok(false)
1599}
1600
1601fn projection_positions(mut mask: u32) -> impl Iterator<Item = usize> {
1604 std::iter::from_fn(move || {
1605 if mask == 0 {
1606 return None;
1607 }
1608 let position = mask.trailing_zeros() as usize;
1609 mask &= mask - 1;
1610 Some(position)
1611 })
1612}
1613
1614fn admit_ordered_fields(entity: &EntitySchema, mask: u32) -> Result<(), Error> {
1615 for i in projection_positions(mask) {
1616 if !key::supports(entity.fields[i].value) {
1617 return Err(Error::InvalidQuery);
1618 }
1619 }
1620
1621 Ok(())
1622}
1623
1624fn comparison_key(
1626 entity: &EntitySchema,
1627 mask: u32,
1628 values: &[IndexValue<'_>],
1629 scratch: &mut Vec<u8>,
1630) -> Result<(), Error> {
1631 build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1632}
1633
1634fn build_comparison_key<'a>(
1635 entity: &EntitySchema,
1636 mask: u32,
1637 key: &mut Vec<u8>,
1638 mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1639) -> Result<(), Error> {
1640 key.clear();
1641 for i in projection_positions(mask) {
1642 let field = &entity.fields[i];
1643 value(i, field)?.append_component(field.optional, key);
1644 if key.len() > MAX_COMPARISON_KEY {
1645 return Err(Error::Limit);
1646 }
1647 }
1648
1649 Ok(())
1650}
1651
1652fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1653 if size > limit {
1654 return Err(Error::RowTooLarge);
1655 }
1656 if size > limit - *used {
1657 return Err(Error::Limit);
1658 }
1659 *used += size;
1660
1661 Ok(())
1662}
1663
1664fn projection_size(spans: &[(u16, u16)], mask: u32) -> usize {
1666 projection_positions(mask)
1667 .map(|i| {
1668 let (start, end) = spans[i];
1669 usize::from(end - start)
1670 })
1671 .sum()
1672}
1673
1674fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u32, size: usize) -> Vec<u8> {
1675 let mut output = Vec::with_capacity(size);
1676 for i in projection_positions(mask) {
1677 let (start, end) = spans[i];
1678 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1679 }
1680
1681 output
1682}
1683#[derive(Clone, Copy)]
1684enum PlanOutput {
1685 Rows,
1686 Aggregate { grouped: bool },
1687}
1688
1689struct Plan<'a> {
1690 primary: usize,
1691 index: Option<&'a IndexSchema>,
1692 prefix: Vec<u8>,
1693 fixed_components: usize,
1694 terms: Vec<Term>,
1695 selected: u32,
1696 span_fields: u32,
1698 binding: [u8; 32],
1699 projection: Option<u32>,
1700 distinct: distinct::Strategy,
1701 sort: Option<Vec<order::SortField>>,
1702 descending: bool,
1703}
1704impl<'a> Plan<'a> {
1705 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1706 self.terms.split_inclusive(|term| !term.or_next)
1707 }
1708
1709 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1710 self.index = Some(path.index);
1711 self.prefix = path.prefix;
1712 self.fixed_components = path.fixed;
1713 self.selected |= entity.key_fields();
1714 }
1715
1716 fn admit(
1717 entity: &'a EntitySchema,
1718 request: &Request<'_>,
1719 schema: [u8; 32],
1720 incarnation: [u8; 16],
1721 projection: Option<Projection<'_>>,
1722 output: PlanOutput,
1723 ) -> Result<Self, Error> {
1724 if !request.within_limits() {
1725 return Err(Error::Limit);
1726 }
1727 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1728 {
1729 return Err(Error::InvalidQuery);
1730 }
1731 for value in request
1733 .predicates
1734 .iter()
1735 .filter_map(|p| match &p.operand {
1736 QueryOperand::Literal(value) => Some(value),
1737 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1738 })
1739 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1740 {
1741 if match value {
1742 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1743 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1744 _ => false,
1745 } {
1746 return Err(Error::Limit);
1747 }
1748 }
1749 let primary = entity
1750 .field_position(entity.primary_key)
1751 .filter(|&i| !entity.fields[i].optional)
1752 .ok_or(Error::InvalidQuery)?;
1753 let mut plan = Self {
1754 primary,
1755 index: None,
1756 prefix: prefix(2, entity.id, &[]),
1757 fixed_components: 0,
1758 terms: Vec::new(),
1759 selected: 1 << primary,
1760 span_fields: 0,
1761 binding: [0; 32],
1762 projection: projection.map(|output| output.mask(entity)).transpose()?,
1763 distinct: distinct::Strategy::Identity,
1764 sort: None,
1765 descending: request.descending ^ request.primary_descending(entity),
1766 };
1767 for predicate in &request.predicates {
1768 let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
1769 let field = &entity.fields[position];
1770 let member = if predicate.comparison == Comparison::Contains {
1771 member_type(field.value)
1772 } else {
1773 None
1774 };
1775 let operand = match (predicate.operand, record_member) {
1776 (QueryOperand::Literal(value), Some(member)) => {
1777 if !predicate.comparison.supports_record_member() {
1778 return Err(Error::InvalidQuery);
1779 }
1780 let leaf = member.field();
1781 predicate.comparison.admit(
1782 leaf.value,
1783 field.optional || leaf.optional,
1784 value,
1785 )?;
1786 let mut literal = Vec::new();
1787 value.append_component(field.optional || leaf.optional, &mut literal);
1788 plan.span_fields |= 1 << position;
1789 TermOperand::Nested {
1790 member,
1791 literal,
1792 absent: value == IndexValue::Absent,
1793 }
1794 }
1795 (QueryOperand::Length(length), member) => {
1796 let selected = member.map_or(field.value, |m| m.field().value);
1797 if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1798 return Err(Error::InvalidQuery);
1799 }
1800 plan.span_fields |= 1 << position;
1801
1802 TermOperand::Length {
1803 member,
1804 threshold: length,
1805 }
1806 }
1807 (QueryOperand::Field(name), left_member) => {
1808 let (right, right_member) = crate::member::resolve_field(entity, name)?;
1809 if (left_member.is_some() || right_member.is_some())
1810 && member.is_none()
1811 && !predicate.comparison.supports_record_member()
1812 {
1813 return Err(Error::InvalidQuery);
1814 }
1815 let right_type =
1816 right_member.map_or(entity.fields[right].value, |m| m.field().value);
1817 let left_type =
1818 left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1819 let compatible = left_type == right_type
1820 || matches!(
1821 (left_type, right_type),
1822 (FieldType::Text { .. }, FieldType::Text { .. })
1823 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1824 );
1825 if !compatible
1826 || !key::supports(left_type)
1827 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1828 {
1829 return Err(Error::InvalidQuery);
1830 }
1831 if right_member.is_some() {
1832 plan.span_fields |= 1 << right;
1833 } else {
1834 plan.selected |= 1 << right;
1835 }
1836
1837 if let Some(item) = member {
1838 plan.span_fields |= 1 << position;
1839
1840 TermOperand::Member {
1841 item,
1842 needle: MemberNeedle::Field(right, right_member),
1843 }
1844 } else {
1845 if left_member.is_some() {
1846 plan.span_fields |= 1 << position;
1847 } else {
1848 plan.selected |= 1 << position;
1849 }
1850 TermOperand::Field {
1851 right,
1852 left_member,
1853 right_member,
1854 }
1855 }
1856 }
1857 (QueryOperand::Literal(value), None) => {
1858 if let Some(item) = member {
1859 if !key::supports(item) {
1860 return Err(Error::InvalidQuery);
1861 }
1862 value.admit(item, false)?;
1863 let mut bytes = Vec::new();
1864 value.append_component(false, &mut bytes);
1865 plan.span_fields |= 1 << position;
1866
1867 TermOperand::Member {
1868 item,
1869 needle: MemberNeedle::Literal(bytes),
1870 }
1871 } else {
1872 let absent = value == IndexValue::Absent;
1873 if key::supports(field.value) {
1874 plan.selected |= 1 << position;
1875 } else if absent
1876 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1877 {
1878 plan.span_fields |= 1 << position;
1879 } else {
1880 return Err(Error::InvalidQuery);
1881 }
1882 predicate
1883 .comparison
1884 .admit(field.value, field.optional, value)?;
1885 let mut bytes = Vec::new();
1886 value.append_component(field.optional, &mut bytes);
1887
1888 TermOperand::Literal { bytes, absent }
1889 }
1890 }
1891 };
1892 plan.terms.push(Term {
1893 tests_presence: predicate.tests_presence(entity, &operand),
1894 position,
1895 comparison: predicate.comparison,
1896 operand,
1897 or_next: predicate.or_next,
1898 });
1899 }
1900 match order::select(entity, request, output)? {
1903 order::Path::Primary => {}
1904 order::Path::Index(path, descending) => {
1905 plan.use_index(entity, path);
1906 plan.descending = request.descending ^ descending;
1907 }
1908 order::Path::Filtered { sort } => {
1909 order::select_filtered_path(entity, request, &mut plan, None)?;
1910 for field in sort.iter().flatten() {
1911 if field.member.is_some() {
1912 plan.span_fields |= 1 << field.position;
1913 } else {
1914 plan.selected |= 1 << field.position;
1915 }
1916 }
1917 plan.sort = sort;
1918 }
1919 }
1920 if request.distinct {
1921 plan.distinct = distinct::admit(entity, request, &plan)?;
1922 match plan.distinct {
1923 distinct::Strategy::FirstMatch => plan.sort = None,
1924 distinct::Strategy::Complete { key_fields } => plan.selected |= key_fields,
1925 _ => {}
1926 }
1927 }
1928 let mut hash = Sha256::new();
1929 hash.update(b"ic-db:query:v1\0");
1930 hash.update(schema);
1931 hash.update(incarnation);
1932 hash.update([u8::from(request.descending)]);
1933 hash.update((plan.prefix.len() as u32).to_le_bytes());
1934 hash.update(&plan.prefix);
1935 for term in &plan.terms {
1936 hash.update([term.position as u8, term.comparison as u8]);
1937
1938 match &term.operand {
1939 TermOperand::Nested {
1940 member,
1941 literal,
1942 absent,
1943 } => {
1944 hash.update((u32::MAX - 2).to_le_bytes());
1945 hash.update([member.position() as u8, u8::from(*absent)]);
1946 let literal = &literal[usize::from(
1948 entity.fields[term.position].optional || member.field().optional,
1949 )..];
1950 hash.update((literal.len() as u32).to_le_bytes());
1951 hash.update(literal);
1952 }
1953 TermOperand::Literal { bytes, .. }
1954 | TermOperand::Member {
1955 needle: MemberNeedle::Literal(bytes),
1956 ..
1957 } => {
1958 hash.update((bytes.len() as u32).to_le_bytes());
1959 hash.update(bytes);
1960 }
1961 TermOperand::Length { member, threshold } => {
1962 if let Some(member) = member {
1963 hash.update((u32::MAX - 3).to_le_bytes());
1964 hash.update([member.position() as u8]);
1965 } else {
1966 hash.update((u32::MAX - 1).to_le_bytes());
1967 }
1968 hash.update(threshold.to_le_bytes());
1969 }
1970 TermOperand::Field {
1971 right,
1972 left_member: None,
1973 right_member: None,
1974 }
1975 | TermOperand::Member {
1976 needle: MemberNeedle::Field(right, None),
1977 ..
1978 } => {
1979 hash.update(u32::MAX.to_le_bytes());
1981 hash.update([*right as u8]);
1982 }
1983 TermOperand::Member {
1984 needle: MemberNeedle::Field(right, Some(member)),
1985 ..
1986 } => {
1987 hash.update((u32::MAX - 4).to_le_bytes());
1988 hash.update([u8::MAX, *right as u8, member.position() as u8]);
1989 }
1990 TermOperand::Field {
1991 right,
1992 left_member,
1993 right_member,
1994 } => {
1995 hash.update((u32::MAX - 4).to_le_bytes());
1996 let slot = |member: &Option<crate::member::RecordMember>| {
1997 member.map_or(u8::MAX, |m| m.position() as u8)
1998 };
1999 hash.update([slot(left_member), *right as u8, slot(right_member)]);
2000 }
2001 }
2002 }
2003 let clauses = plan
2006 .terms
2007 .iter()
2008 .enumerate()
2009 .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
2010 if clauses != 0 {
2011 hash.update(b"or-clauses\0");
2012 hash.update([clauses]);
2013 }
2014 if let Some(order) = &request.order {
2015 hash.update(b"order\0");
2016 hash.update([order.len() as u8]);
2017 for name in order {
2018 if let Some(position) = entity.field_position(name) {
2020 hash.update([position as u8]);
2021 } else {
2022 hash.update([u8::MAX, name.len() as u8]);
2024 hash.update(name.as_bytes());
2025 }
2026 }
2027 }
2028 if request.order_descending != 0 {
2029 hash.update(b"order-directions\0");
2030 hash.update([request.order_descending]);
2031 }
2032 if let Some(mask) = plan.projection {
2035 hash.update(b"projection\0");
2036 hash.update(mask.to_le_bytes());
2037 if let Some(Projection::Columns(columns)) = projection {
2038 hash.update(b"columns\0");
2039 hash.update(columns);
2040 }
2041 }
2042 if request.distinct {
2043 hash.update(b"distinct\0");
2044 }
2045 plan.binding = hash.finalize().into();
2046 if let Some(cursor) = request.cursor {
2047 if cursor.binding != plan.binding {
2048 return Err(Error::InvalidCursor);
2049 }
2050 plan.validate_position(entity, cursor)
2051 .map_err(|_| Error::InvalidCursor)?;
2052 }
2053
2054 Ok(plan)
2055 }
2056
2057 fn validate_position(&self, entity: &EntitySchema, cursor: &QueryCursor) -> Result<(), Error> {
2058 if cursor.resume == Resume::AfterUnemittedClass
2059 && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
2060 {
2061 return Err(Error::InvalidCursor);
2062 }
2063 let bytes = cursor.position.as_slice();
2064 if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
2065 return Err(Error::InvalidCursor);
2066 }
2067 if let Some(index) = self.index {
2068 let mut remaining = bytes
2069 .get(INDEX_PREFIX_BYTES..)
2070 .ok_or(Error::InvalidCursor)?;
2071 for name in index.fields {
2072 consume_index_component(entity, index, name, &mut remaining)?;
2073 }
2074 if !index.unique {
2075 key::consume(&mut remaining, entity.key_type()?)?;
2076 }
2077 if !remaining.is_empty() {
2078 return Err(Error::InvalidCursor);
2079 }
2080 } else {
2081 RowKey::decode(
2082 bytes
2083 .get(ENTITY_PREFIX_BYTES..)
2084 .ok_or(Error::InvalidCursor)?,
2085 entity.key_type()?,
2086 )?;
2087 }
2088
2089 Ok(())
2090 }
2091
2092 fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
2093 QueryCursor {
2094 binding: self.binding,
2095 position: position.to_vec(),
2096 resume,
2097 }
2098 }
2099}
2100
2101fn consume_index_component(
2103 entity: &EntitySchema,
2104 index: &IndexSchema,
2105 name: &str,
2106 remaining: &mut &[u8],
2107) -> Result<(), Error> {
2108 let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
2109
2110 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
2111}
2112
2113#[inline(never)]
2116#[expect(
2117 clippy::needless_pass_by_value,
2118 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
2119)]
2120fn fetch_rows<M: Memory>(
2121 db: &Database<M>,
2122 entity: &EntitySchema,
2123 request: Request<'_>,
2124 projection: Option<Projection<'_>>,
2125) -> Result<QueryPage<Vec<u8>>, Error> {
2126 db.schema.admits(entity)?;
2127 let plan = Plan::admit(
2128 entity,
2129 &request,
2130 db.schema.fingerprint(),
2131 db.incarnation,
2132 projection,
2133 PlanOutput::Rows,
2134 )?;
2135
2136 execute(&db.map, entity, &request, &plan, None)
2137}
2138
2139fn execute<M: Memory>(
2140 map: &Map<M>,
2141 entity: &EntitySchema,
2142 request: &Request<'_>,
2143 plan: &Plan<'_>,
2144 mut aggregate: Option<aggregate::Accumulator<'_>>,
2145) -> Result<QueryPage<Vec<u8>>, Error> {
2146 execute_inner(
2147 map,
2148 entity,
2149 request,
2150 plan,
2151 range::bounds(entity, request, plan)?,
2152 aggregate.as_mut(),
2153 None,
2154 )
2155}
2156
2157const STEP_INPUT_BYTES: usize = 64 * 1024;
2160const fn candidate_byte_limit(row_bytes: usize) -> usize {
2161 row_bytes + 2 * crate::MAX_INDEX_KEY_BYTES
2162}
2163
2164fn execute_inner<M: Memory>(
2165 map: &Map<M>,
2166 entity: &EntitySchema,
2167 request: &Request<'_>,
2168 plan: &Plan<'_>,
2169 bounds: Option<range::Bounds>,
2170 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
2171 mut input_bytes: Option<&mut usize>,
2172) -> Result<QueryPage<Vec<u8>>, Error> {
2173 let mut page = QueryPage {
2174 rows: Vec::new(),
2175 next: None,
2176 examined: 0,
2177 fetched: 0,
2178 output_bytes: 0,
2179 };
2180 let Some(bounds) = bounds else {
2181 return Ok(page);
2182 };
2183 let terminal = range::terminal_key(&bounds, plan.descending);
2184 let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
2185 let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
2186 Some(distinct::Collection::new(
2187 plan.projection.ok_or(Error::InvalidQuery)?,
2188 key_fields,
2189 ))
2190 } else {
2191 None
2192 };
2193 let mut sorted = plan
2194 .sort
2195 .as_ref()
2196 .map(|_| sort::Collection::new(request, plan.distinct));
2197 let mut component = Vec::new();
2198 let mut right_component = Vec::new();
2199 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
2201 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
2202 } else {
2203 None
2204 };
2205 let candidate_bytes = candidate_byte_limit(entity.max_row_bytes);
2206 let primary_type = entity.fields[plan.primary].value;
2207 let needs_spans = plan.index.is_some()
2208 || plan.span_fields != 0
2209 || match &aggregate {
2210 Some(accumulator) => accumulator.needs_spans(),
2211 None => plan.projection.is_some(),
2212 };
2213 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
2215 let mut next_entry = || {
2216 if plan.descending {
2217 entries.next_back()
2218 } else {
2219 entries.next()
2220 }
2221 };
2222 while let Some(entry) = next_entry() {
2223 if page.examined == request.work {
2226 return Err(Error::Limit);
2227 }
2228 page.examined += 1;
2229 let stored_key = entry.key();
2230 let mut read_bytes = stored_key.len();
2231 let (owner, bytes) = if plan.index.is_some() {
2232 let owner_bytes = entry.value();
2233 read_bytes += owner_bytes.len();
2234 read_index_owner(map, entity.id, primary_type, &owner_bytes)?
2235 } else {
2236 (
2237 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
2238 entry.value(),
2239 )
2240 };
2241 if let Some(used) = input_bytes.as_deref_mut() {
2242 read_bytes += bytes.len();
2243 if read_bytes > candidate_bytes {
2244 return Err(Error::Corrupt);
2245 }
2246 *used += read_bytes;
2247 }
2248 page.fetched += 1;
2249 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
2250 entity.inspect_fields(
2251 &bytes,
2252 plan.selected,
2253 &mut values,
2254 needs_spans.then_some(&mut spans),
2255 )?;
2256 if plan.index.is_some() {
2257 validate_index_entry(
2258 entity,
2259 &entity.row_info(&values, &bytes, &spans)?,
2260 owner,
2261 stored_key,
2262 )?;
2263 } else if RowKey::from_index(values[plan.primary])? != owner {
2264 return Err(Error::Corrupt);
2265 }
2266 let read = |position: usize, member: Option<crate::member::RecordMember>| {
2267 if let Some(member) = member {
2268 let (start, end) = spans[position];
2269 member.read(
2270 &bytes[usize::from(start)..usize::from(end)],
2271 entity.fields[position].optional,
2272 )
2273 } else {
2274 Ok(values[position])
2275 }
2276 };
2277 let mut accepts = |term: &Term, supplied: &QueryOperand<'_>| -> Result<bool, Error> {
2278 let mut value = values[term.position];
2279 component.clear();
2280 let (operand, optional) = match &term.operand {
2281 TermOperand::Nested {
2282 member,
2283 literal,
2284 absent,
2285 } => {
2286 value = read(term.position, Some(*member))?;
2287 if *absent {
2288 return Ok(term.comparison.accepts_absent(value == IndexValue::Absent));
2289 }
2290 (
2291 Some(literal.as_slice()),
2292 entity.fields[term.position].optional || member.field().optional,
2293 )
2294 }
2295 TermOperand::Literal { absent: true, .. } => {
2296 let absent = if plan.span_fields & (1 << term.position) != 0 {
2297 bytes[usize::from(spans[term.position].0)] == 0
2298 } else {
2299 value == IndexValue::Absent
2300 };
2301
2302 return Ok(term.comparison.accepts_absent(absent));
2303 }
2304 TermOperand::Member { item, needle } => {
2305 let needle = match (needle, supplied) {
2306 (MemberNeedle::Literal(_), QueryOperand::Literal(value)) => *value,
2307 (MemberNeedle::Field(right, member), QueryOperand::Field(_)) => {
2308 read(*right, *member)?
2309 }
2310 _ => return Err(Error::Corrupt),
2311 };
2312 if needle == IndexValue::Absent {
2313 return Ok(false);
2314 }
2315 let (start, end) = spans[term.position];
2316
2317 return contains_member(
2318 &bytes[usize::from(start)..usize::from(end)],
2319 entity.fields[term.position].optional,
2320 *item,
2321 needle,
2322 );
2323 }
2324 TermOperand::Length { member, threshold } => {
2325 let (start, end) = spans[term.position];
2326 let span = &bytes[usize::from(start)..usize::from(end)];
2327 let optional = entity.fields[term.position].optional;
2328 let actual = if let Some(member) = member {
2329 match member.read(span, optional)? {
2330 IndexValue::Absent => None,
2331 value => Some(scalar_bytes(value).ok_or(Error::Corrupt)?.len() as u32),
2332 }
2333 } else {
2334 crate::codec::validated_length(span, optional)
2335 };
2336
2337 return Ok(term.comparison.accepts_length(actual, *threshold));
2338 }
2339 TermOperand::Literal {
2340 bytes,
2341 absent: false,
2342 } => (
2343 Some(bytes.as_slice()),
2344 entity.fields[term.position].optional,
2345 ),
2346 TermOperand::Field {
2347 right,
2348 left_member,
2349 right_member,
2350 } => {
2351 value = read(term.position, *left_member)?;
2352 let rhs = read(*right, *right_member)?;
2353 if value == IndexValue::Absent || rhs == IndexValue::Absent {
2354 return Ok(term.comparison.accepts_absent(value == rhs));
2355 }
2356 if let Some(matches) = term.comparison.accepts_values(value, rhs) {
2357 return Ok(matches);
2358 }
2359 right_component.clear();
2360 rhs.append_component(false, &mut right_component);
2361
2362 (Some(right_component.as_slice()), false)
2363 }
2364 };
2365 if let QueryOperand::Literal(right) = supplied
2366 && let Some(matches) = term.comparison.accepts_values(value, *right)
2367 {
2368 return Ok(matches);
2369 }
2370 value.append_component(optional, &mut component);
2371
2372 Ok(term.comparison.accepts(
2373 (value != IndexValue::Absent).then_some(component.as_slice()),
2374 operand,
2375 optional,
2376 ))
2377 };
2378 let matches = 'matches: {
2379 let mut clause_matches = false;
2380 for (term, predicate) in plan.terms.iter().zip(&request.predicates) {
2381 clause_matches = clause_matches || accepts(term, &predicate.operand)?;
2382 if !term.or_next {
2383 if !clause_matches {
2384 break 'matches false;
2385 }
2386 clause_matches = false;
2387 }
2388 }
2389
2390 true
2391 };
2392 let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
2393 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2394 if matches && let Some(accumulator) = aggregate.as_mut() {
2395 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2396 if matches!(accumulator, aggregate::Accumulator::Until(remaining) if **remaining == 0) {
2397 return Ok(page);
2399 }
2400 } else if matches && let Some(collection) = collected.as_mut() {
2401 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2402 if request.single_result_probe == Some(SingleResult::First) {
2404 break;
2405 }
2406 } else if matches && let Some(collection) = sorted.as_mut() {
2407 collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2408 request.check_result_count(collection.result_count())?;
2410 } else if matches && !duplicate {
2411 request.check_result_count(page.rows.len() + 1)?;
2412 let size = plan
2413 .projection
2414 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2415 if size > request.bytes {
2416 return Err(Error::RowTooLarge);
2417 }
2418 if size > request.bytes - page.output_bytes {
2419 page.next = Some(plan.cursor(stored_key, Resume::Retry));
2420
2421 return Ok(page);
2422 }
2423 page.output_bytes += size;
2424 if let Some(mask) = plan.projection {
2425 page.rows.push(copy_projection(&bytes, &spans, mask, size));
2426 } else {
2427 page.rows.push(bytes);
2428 }
2429 if request.single_result_probe == Some(SingleResult::First)
2430 || plan.distinct.finishes_on_match(plan.fixed_components)
2431 {
2432 return Ok(page);
2433 }
2434 if let Some(boundary) = boundary {
2435 previous = Some(boundary.to_vec());
2436 }
2437 }
2438 if page.rows.len() == request.rows
2439 || page.examined == request.work
2440 || input_bytes
2441 .as_deref()
2442 .is_some_and(|used| *used > STEP_INPUT_BYTES - candidate_bytes)
2443 {
2444 if terminal == Some(stored_key) {
2445 break;
2446 }
2447 if request.single_result_probe.is_some()
2448 || (aggregate.is_some() && input_bytes.is_none())
2449 || collected.is_some()
2450 || sorted.is_some()
2451 {
2452 continue;
2455 }
2456 if input_bytes.is_some() && next_entry().is_none() {
2460 break;
2461 }
2462 let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
2463 Resume::AfterUnemittedClass
2464 } else {
2465 Resume::After
2466 };
2467 page.next = Some(plan.cursor(stored_key, resume));
2468
2469 return Ok(page);
2470 }
2471 }
2472 if let Some(collection) = collected {
2473 page.output_bytes = collection.output_bytes;
2474 page.rows = collection.rows;
2475 }
2476 if let Some(collection) = sorted {
2477 collection.finish(request.bytes, &mut page)?;
2478 }
2479
2480 Ok(page)
2481}