1mod aggregate;
4mod cursor;
5pub use cursor::QueryCursor;
6use cursor::Resume;
7mod distinct;
8mod get_many;
9pub use get_many::{GetMany, SelectedGetMany};
10mod order;
11mod predicate;
12mod probe;
13mod range;
14mod select;
15mod sort;
16use crate::member::ResolvedField;
17pub use select::{Column, SelectColumns, SelectedQuery, Selection};
18
19pub use aggregate::{
20 Aggregate, GroupCount, GroupOrder, GroupSummaries, GroupSummary, GroupSummaryPage, GroupValue,
21 SummaryMeasure,
22 jobs::{AggregateJobs, GroupCursor, GroupPage, JobHandle, JobOutcome, JobStep},
23};
24
25use super::{
26 Database, ENTITY_PREFIX_BYTES, INDEX_PREFIX_BYTES, Map, prefix, read_index_owner,
27 validate_index_entry,
28};
29use crate::{
30 Entity, EntitySchema, Error, FieldType, IndexSchema, IndexValue, TypeBody, TypeSchema, Value,
31 codec::Decoder,
32 key,
33 named_schema::TypeGraph,
34 primary::{PrimaryKey, RowKey},
35};
36use ic_storage::Memory;
37use std::{
38 cell::{Ref, RefCell},
39 marker::PhantomData,
40 ops::Deref,
41 rc::Rc,
42};
43
44const MAX_TERMS: usize = 8;
45const MAX_WORK: usize = 512;
46const MAX_OUTPUT: usize = 128 * 1024;
47const MAX_COMPARISON_KEY: usize = 4096;
48const MAX_DISTINCT_VALUES: usize = 32;
49const MAX_STATE_BYTES: usize = 128 * 1024;
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub enum SortDirection {
54 Ascending,
56 Descending,
58}
59
60#[derive(Clone, Copy)]
62pub struct OrderTerm<'a> {
63 field: &'a str,
64 direction: SortDirection,
65}
66
67impl<'a, T: AsRef<str> + ?Sized> From<&'a T> for OrderTerm<'a> {
68 fn from(field: &'a T) -> Self {
69 Self {
70 field: field.as_ref(),
71 direction: SortDirection::Ascending,
72 }
73 }
74}
75
76impl<'a, T: AsRef<str> + ?Sized> From<(&'a T, SortDirection)> for OrderTerm<'a> {
77 fn from((field, direction): (&'a T, SortDirection)) -> Self {
78 Self {
79 field: field.as_ref(),
80 direction,
81 }
82 }
83}
84
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87#[repr(u8)]
88pub enum Comparison {
89 Eq = 0,
91 Ne = 1,
93 Lt = 2,
95 Le = 3,
97 Gt = 4,
99 Ge = 5,
101 StartsWith = 6,
105 EndsWith = 7,
108 Contains = 8,
112}
113
114impl Comparison {
115 fn supports_record_member(self) -> bool {
116 self.is_relational() || matches!(self, Self::StartsWith | Self::EndsWith)
117 }
118
119 fn is_relational(self) -> bool {
120 matches!(
121 self,
122 Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge
123 )
124 }
125
126 fn supports_scalar(self, field: FieldType) -> bool {
127 self.is_relational()
128 || matches!(
129 key::operand_type(field),
130 FieldType::Text { .. } | FieldType::Blob { .. }
131 )
132 }
133
134 fn admit(self, field: FieldType, optional: bool, value: IndexValue<'_>) -> Result<(), Error> {
135 value.admit(field, optional)?;
136 if !self.supports_scalar(field) {
137 return Err(Error::InvalidQuery);
138 }
139 if value == IndexValue::Absent && !matches!(self, Self::Eq | Self::Ne) {
140 return Err(Error::InvalidOperand);
141 }
142
143 Ok(())
144 }
145
146 fn accepts(self, actual: Option<&[u8]>, operand: Option<&[u8]>, optional: bool) -> bool {
147 if actual.is_none() {
148 return self.accepts_absent(operand.is_none());
149 }
150
151 match self {
152 Self::Eq => actual == operand,
153 Self::Ne => actual != operand,
154 Self::StartsWith | Self::EndsWith | Self::Contains => {
155 fn content(key: &[u8], optional: bool) -> Option<&[u8]> {
158 crate::key::bytes_prefix(key.get(usize::from(optional)..)?)
159 }
160
161 actual
162 .and_then(|key| content(key, optional))
163 .zip(operand.and_then(|key| content(key, optional)))
164 .is_some_and(|(actual, operand)| match self {
165 Self::StartsWith => actual.starts_with(operand),
168 Self::EndsWith => actual
172 .strip_suffix(operand)
173 .is_some_and(|prefix| prefix.last() != Some(&0)),
174 _ => contains_component(actual, operand),
175 })
176 }
177 _ if actual.is_none() || operand.is_none() => false,
178 Self::Lt => actual < operand,
179 Self::Le => actual <= operand,
180 Self::Gt => actual > operand,
181 Self::Ge => actual >= operand,
182 }
183 }
184
185 fn accepts_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
187 match self {
188 Self::Eq => Some(equal_values(left, right)),
189 Self::Ne => Some(!equal_values(left, right)),
190 _ => match left.integer_cmp(&right) {
191 Some(order) => self.accepts_order(order),
192 None => Some(self.accepts_bytes(scalar_bytes(left)?, scalar_bytes(right)?)),
193 },
194 }
195 }
196
197 fn accepts_fixed_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
199 if left == IndexValue::Absent || right == IndexValue::Absent {
200 return Some(self.accepts_absent(left == right));
201 }
202 if let Some(result) = self.accepts_values(left, right) {
203 return Some(result);
204 }
205 if !self.is_relational() {
206 return None;
207 }
208 let mut encoded = Vec::new();
210 left.append_component(false, &mut encoded);
211 let split = encoded.len();
212 right.append_component(false, &mut encoded);
213 let (left, right) = encoded.split_at(split);
214 Some(self.accepts(Some(left), Some(right), false))
215 }
216
217 fn accepts_bytes(self, actual: &[u8], operand: &[u8]) -> bool {
219 match self {
220 Self::StartsWith => actual.starts_with(operand),
221 Self::EndsWith => actual.ends_with(operand),
222 Self::Contains => memchr::memmem::find(actual, operand).is_some(),
223 _ => self.accepts(Some(actual), Some(operand), false),
224 }
225 }
226
227 fn accepts_order(self, order: std::cmp::Ordering) -> Option<bool> {
228 Some(match self {
229 Self::Eq => order.is_eq(),
230 Self::Ne => !order.is_eq(),
231 Self::Lt => order.is_lt(),
232 Self::Le => order.is_le(),
233 Self::Gt => order.is_gt(),
234 Self::Ge => order.is_ge(),
235 _ => return None,
236 })
237 }
238
239 fn accepts_length(self, actual: Option<u32>, threshold: u32) -> bool {
240 actual.map_or_else(
241 || self.accepts_absent(false),
242 |n| self.accepts_order(n.cmp(&threshold)) == Some(true),
243 )
244 }
245
246 fn empty_length_value(self, threshold: u32, field: FieldType) -> Option<IndexValue<'static>> {
248 if !matches!((self, threshold), (Self::Eq | Self::Le, 0) | (Self::Lt, 1)) {
249 return None;
250 }
251 match key::operand_type(field) {
252 FieldType::Text { .. } => Some(IndexValue::Text("")),
253 FieldType::Blob { .. } => Some(IndexValue::Blob(&[])),
254 _ => None,
255 }
256 }
257
258 fn uniform_length_result(self, min: u32, max: u32, n: u32) -> Option<bool> {
260 match self {
261 Self::Eq | Self::Ne if min == max || n < min || n > max => {
262 Some(self.accepts_length(Some(min), n))
263 }
264 Self::Lt | Self::Ge if max < n || min >= n => Some(self.accepts_length(Some(min), n)),
265 Self::Le | Self::Gt if max <= n || min > n => Some(self.accepts_length(Some(min), n)),
266 _ => None,
267 }
268 }
269
270 fn accepts_absent(self, other_absent: bool) -> bool {
273 match self {
274 Self::Eq => other_absent,
275 Self::Ne => !other_absent,
276 _ => false,
277 }
278 }
279}
280
281fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
283 let Some(start) = memchr::memmem::find(actual, needle) else {
284 return false;
285 };
286 if start == 0 || actual[start - 1] != 0 {
287 return true;
288 }
289 fn raw(content: &[u8]) -> Vec<u8> {
293 let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
294 let mut encoded = content.iter();
295 while let Some(&byte) = encoded.next() {
296 bytes.push(byte);
297 if byte == 0 {
298 encoded.next();
299 }
300 }
301
302 bytes
303 }
304
305 memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
306}
307
308#[derive(Debug)]
311pub struct QueryPage<T> {
312 pub rows: Vec<T>,
314 pub next: Option<QueryCursor>,
316 pub examined: usize,
318 pub fetched: usize,
320 pub output_bytes: usize,
322}
323
324impl QueryPage<Vec<u8>> {
325 #[inline(never)]
326 pub(super) fn decode_rows<R>(
327 self,
328 decode: impl Fn(&[u8]) -> Result<R, Error>,
329 ) -> Result<QueryPage<R>, Error> {
330 Ok(QueryPage {
331 rows: self
332 .rows
333 .iter()
334 .map(|bytes| decode(bytes))
335 .collect::<Result<_, _>>()?,
336 next: self.next,
337 examined: self.examined,
338 fetched: self.fetched,
339 output_bytes: self.output_bytes,
340 })
341 }
342}
343
344fn decode_exact<R>(
345 bytes: &[u8],
346 decode: impl FnOnce(&mut Decoder<'_>) -> Result<R, Error>,
347) -> Result<R, Error> {
348 let mut reader = Decoder::new(bytes)?;
349 let value = decode(&mut reader)?;
350 reader.finish()?;
351 Ok(value)
352}
353
354fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
355 decode_exact(bytes, R::decode_from)
356}
357
358#[derive(Clone, Copy, Debug, PartialEq, Eq)]
360pub enum QueryOperand<'a> {
361 Literal(IndexValue<'a>),
363 Length(u32),
365 Field(&'a str),
367}
368
369impl<'a, T: Into<IndexValue<'a>>> From<T> for QueryOperand<'a> {
370 fn from(value: T) -> Self {
371 Self::Literal(value.into())
372 }
373}
374
375struct Predicate<'a> {
376 field: &'a str,
377 comparison: Comparison,
378 operand: QueryOperand<'a>,
379 or_next: bool,
381}
382
383impl<'a> Predicate<'a> {
384 fn compared_field(&self, name: &str) -> Option<&'a str> {
386 let QueryOperand::Field(right) = self.operand else {
387 return None;
388 };
389 if self.field == name {
390 Some(right)
391 } else if right == name {
392 Some(self.field)
393 } else {
394 None
395 }
396 }
397
398 fn at_extreme(&self, entity: &EntitySchema, value: IndexValue<'_>, upper: bool) -> bool {
400 use crate::{Date, Duration, Timestamp, Ulid};
401
402 match value {
403 IndexValue::Bool(b) => b == upper,
404 IndexValue::Date(d) => d == if upper { Date::MAX } else { Date::MIN },
405 IndexValue::Timestamp(t) => {
406 t == if upper {
407 Timestamp::MAX
408 } else {
409 Timestamp::MIN
410 }
411 }
412 IndexValue::Duration(d) => d == if upper { Duration::MAX } else { Duration::MIN },
413 IndexValue::Ulid(id) => id == if upper { Ulid::MAX } else { Ulid::MIN },
414 IndexValue::UnitEnum { ordinal, .. } => entity
415 .index_field(self.field)
416 .is_some_and(|field| key::is_fixed_extreme(field.value, &[ordinal], upper)),
417 IndexValue::Text("") | IndexValue::Blob([]) => !upper,
418 _ => value.is_integer_extreme(upper),
419 }
420 }
421
422 fn fixed_equality(&self, entity: &EntitySchema) -> Option<(&'a str, IndexValue<'a>)> {
424 if let QueryOperand::Length(n) = self.operand {
425 let empty = self
426 .comparison
427 .empty_length_value(n, entity.index_field(self.field)?.value)?;
428 return Some((self.field, empty));
429 }
430 let QueryOperand::Literal(value) = self.operand else {
431 return None;
432 };
433 let fixed = match (self.comparison, value) {
435 (Comparison::Eq, _) => value,
436 (Comparison::Ne, IndexValue::Bool(excluded))
437 if entity.field_is_required(self.field) =>
438 {
439 IndexValue::Bool(!excluded)
440 }
441 (cmp @ (Comparison::Ge | Comparison::Le), _)
442 if self.at_extreme(entity, value, cmp == Comparison::Ge) =>
443 {
444 value
445 }
446 (Comparison::Gt, IndexValue::Bool(false)) => IndexValue::Bool(true),
447 (Comparison::Lt, IndexValue::Bool(true)) => IndexValue::Bool(false),
448 _ => return None,
449 };
450 Some((self.field, fixed))
451 }
452
453 fn tests_presence(&self, entity: &EntitySchema, operand: &TermOperand) -> bool {
455 match (self.comparison, self.operand) {
456 (Comparison::Ne, QueryOperand::Literal(IndexValue::Absent)) => true,
457 (cmp @ (Comparison::Le | Comparison::Ge), QueryOperand::Literal(value)) => {
458 self.at_extreme(entity, value, cmp == Comparison::Le)
459 }
460 (_, QueryOperand::Length(_)) => {
461 self.present_length_result(entity) == Some(true)
462 && self.comparison != Comparison::Ne
463 }
464 (
465 Comparison::Le
466 | Comparison::Ge
467 | Comparison::StartsWith
468 | Comparison::EndsWith
469 | Comparison::Contains,
470 QueryOperand::Field(right),
471 ) => right == self.field,
472 (
473 Comparison::StartsWith | Comparison::EndsWith | Comparison::Contains,
474 QueryOperand::Literal(needle),
475 ) => {
476 !matches!(operand, TermOperand::Member { .. })
478 && scalar_bytes(needle).is_some_and(<[u8]>::is_empty)
479 }
480 _ => false,
481 }
482 }
483
484 fn present_length_result(&self, entity: &EntitySchema) -> Option<bool> {
486 let QueryOperand::Length(n) = self.operand else {
487 return None;
488 };
489 let max = length_limit(entity.index_field(self.field)?.value)?;
490 self.comparison.uniform_length_result(0, max, n)
491 }
492
493 fn constant_comparison(&self, entity: &EntitySchema) -> Option<bool> {
494 if let QueryOperand::Literal(value) = self.operand {
495 return match (self.comparison, value) {
497 (cmp @ (Comparison::Lt | Comparison::Gt), value)
498 if self.at_extreme(entity, value, cmp == Comparison::Gt) =>
499 {
500 Some(false)
501 }
502 _ => None,
503 };
504 }
505 if matches!(self.operand, QueryOperand::Length(_)) {
506 let result = self.present_length_result(entity)?;
507 return (result == self.comparison.accepts_absent(false)
508 || entity.field_is_required(self.field))
509 .then_some(result);
510 }
511 if !matches!(self.operand, QueryOperand::Field(right) if right == self.field) {
512 return None;
513 }
514 match self.comparison {
515 Comparison::Eq => Some(true),
516 Comparison::Ne | Comparison::Lt | Comparison::Gt => Some(false),
517 _ => None,
518 }
519 }
520}
521
522#[derive(Clone, Copy, PartialEq, Eq)]
523enum SingleResult {
524 First,
525 Only,
526}
527
528struct Request<'a> {
529 groups: aggregate::GroupRequest<'a>,
530 predicates: Vec<Predicate<'a>>,
531 index: Option<(&'a str, Vec<IndexValue<'a>>)>,
532 order: Option<Vec<OrderTerm<'a>>>,
533 descending: bool,
534 distinct: bool,
535 single_result_probe: Option<SingleResult>,
536 rows: usize,
537 work: usize,
538 bytes: usize,
539 cursor: Option<&'a QueryCursor>,
540 over_limit: bool,
541}
542
543impl Default for Request<'_> {
544 fn default() -> Self {
545 Self {
546 groups: aggregate::GroupRequest::default(),
547 predicates: Vec::new(),
548 index: None,
549 order: None,
550 descending: false,
551 distinct: false,
552 single_result_probe: None,
553 rows: 32,
554 work: 128,
555 bytes: MAX_OUTPUT,
556 cursor: None,
557 over_limit: false,
558 }
559 }
560}
561
562impl<'a> Request<'a> {
565 fn within_limits(&self) -> bool {
566 !self.over_limit
567 && (1..=32).contains(&self.rows)
568 && (1..=MAX_WORK).contains(&self.work)
569 && (1..=MAX_OUTPUT).contains(&self.bytes)
570 }
571
572 fn check_result_count(&self, count: usize) -> Result<(), Error> {
575 if self.single_result_probe == Some(SingleResult::Only) && count > 1 {
576 return Err(Error::MultipleMatches);
577 }
578 Ok(())
579 }
580
581 fn fixed_equalities<'r>(
583 &'r self,
584 entity: &'r EntitySchema,
585 ) -> impl Iterator<Item = (&'a str, IndexValue<'a>)> + 'r {
586 self.clauses().filter_map(move |clause| {
587 let (predicate, rest) = clause.split_first()?;
588 if !rest.is_empty() {
589 let mut candidate = predicate.fixed_equality(entity)?;
590 for alternative in rest {
591 let other = alternative.fixed_equality(entity)?;
592 if candidate.0 != other.0 {
593 return None;
594 }
595 if equal_values(candidate.1, other.1) {
596 continue;
597 }
598 if self.predicates.len() == clause.len() {
599 return None;
600 }
601 if self.excludes_literal(other.0, other.1) {
602 continue;
603 }
604 if !self.excludes_literal(candidate.0, candidate.1) {
605 return None;
606 }
607 candidate = other;
608 }
609 return Some(candidate);
612 }
613 if let Some(equality) = predicate.fixed_equality(entity) {
614 return Some(equality);
615 }
616 let QueryOperand::Literal(value) = predicate.operand else {
619 return None;
620 };
621 let lower = match predicate.comparison {
622 Comparison::Ge => value,
623 Comparison::Gt if self.predicates.len() > 1 => value.discrete_successor()?,
624 _ => return None,
625 };
626 self.clauses()
627 .any(|clause| {
628 let [upper] = clause else { return false };
629 if upper.field != predicate.field {
630 return false;
631 }
632 match (upper.comparison, upper.operand) {
633 (Comparison::Le, QueryOperand::Literal(value)) => {
634 equal_values(lower, value)
635 }
636 (Comparison::Lt, QueryOperand::Literal(value)) => {
637 consecutive_values(lower, value)
638 }
639 _ => false,
640 }
641 })
642 .then_some((predicate.field, lower))
643 })
644 }
645
646 fn excludes_literal(&self, field: &str, value: IndexValue<'_>) -> bool {
647 self.clauses().any(|clause| {
650 clause.iter().all(|predicate| {
651 if predicate.field != field {
652 return false;
653 }
654 let QueryOperand::Literal(literal) = predicate.operand else {
655 return false;
656 };
657 predicate.comparison.is_relational()
658 && predicate.comparison.accepts_fixed_values(value, literal) == Some(false)
659 })
660 })
661 }
662
663 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
664 self.predicates.split_inclusive(|p| !p.or_next)
665 }
666
667 #[inline(never)]
668 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
669 if self.predicates.len() == MAX_TERMS {
670 self.over_limit = true;
671 } else {
672 self.predicates.push(Predicate {
673 field,
674 comparison,
675 operand,
676 or_next: false,
677 });
678 }
679 }
680
681 #[inline(never)]
682 fn or_clause(
683 &mut self,
684 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
685 ) {
686 append_clause(
687 &mut self.predicates,
688 &mut self.over_limit,
689 alternatives,
690 |(field, comparison, operand), or_next| Predicate {
691 field,
692 comparison,
693 operand,
694 or_next,
695 },
696 );
697 }
698
699 #[inline(never)]
700 fn filter_not_in(
701 &mut self,
702 field: &'a str,
703 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
704 ) {
705 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
706 self.over_limit = true;
707
708 return;
709 }
710 for value in values {
711 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
712 }
713 }
714
715 #[inline(never)]
716 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
717 if values.len() > 4 {
718 self.over_limit = true;
719 } else {
720 self.index = Some((name, values.to_vec()));
721 }
722 }
723
724 #[inline(never)]
725 fn order_by<T: Copy + Into<OrderTerm<'a>>>(&mut self, fields: &[T]) {
726 if fields.len() > 4 {
727 self.over_limit = true;
728
729 return;
730 }
731 self.order = Some(fields.iter().copied().map(Into::into).collect());
732 }
733
734 fn append_order(&mut self, field: &'a str, direction: SortDirection) {
735 let fields = self.order.get_or_insert_with(Vec::new);
736 if fields.len() == 4 {
737 self.over_limit = true;
738
739 return;
740 }
741 fields.push(OrderTerm { field, direction });
742 }
743
744 fn primary_descending(&self, entity: &EntitySchema) -> bool {
745 self.order
746 .as_deref()
747 .and_then(|order| order.last())
748 .is_some_and(|term| {
749 term.field == entity.primary_key && term.direction == SortDirection::Descending
750 })
751 }
752}
753
754fn append_clause<I, T>(
755 predicates: &mut Vec<T>,
756 over_limit: &mut bool,
757 terms: impl ExactSizeIterator<Item = I>,
758 predicate: impl Fn(I, bool) -> T,
759) {
760 let count = terms.len();
761 if count == 0 || count > MAX_TERMS - predicates.len() {
762 *over_limit = true;
763 return;
764 }
765 predicates.extend(
766 terms
767 .enumerate()
768 .map(|(i, term)| predicate(term, i + 1 < count)),
769 );
770}
771
772pub(super) fn source_page<M: Memory>(
774 map: &Map<M>,
775 entity: &EntitySchema,
776 binding: [u8; 32],
777 incarnation: [u8; 16],
778 cursor: Option<&QueryCursor>,
779 rows: usize,
780 bytes: usize,
781) -> Result<QueryPage<Vec<u8>>, Error> {
782 let request = Request {
783 rows,
784 work: rows,
785 bytes,
786 cursor,
787 ..Request::default()
788 };
789 let plan = Plan::admit(
790 entity,
791 &request,
792 binding,
793 incarnation,
794 None,
795 PlanOutput::Rows,
796 )?;
797
798 execute(map, entity, &request, &plan, None)
799}
800
801pub(crate) enum QuerySource<'a, M: Memory> {
802 Direct(&'a Database<M>),
803 Session(Rc<RefCell<Database<M>>>),
804}
805
806enum QueryRead<'a, M: Memory> {
807 Direct(&'a Database<M>),
808 Session(Ref<'a, Database<M>>),
809}
810
811impl<M: Memory> Deref for QueryRead<'_, M> {
812 type Target = Database<M>;
813
814 fn deref(&self) -> &Self::Target {
815 match self {
816 Self::Direct(db) => db,
817 Self::Session(db) => db,
818 }
819 }
820}
821
822impl<M: Memory> QuerySource<'_, M> {
823 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
824 match self {
825 Self::Direct(db) => Ok(QueryRead::Direct(db)),
826 Self::Session(db) => db
827 .try_borrow()
828 .map(QueryRead::Session)
829 .map_err(|_| Error::BorrowConflict),
830 }
831 }
832}
833
834pub struct Query<'a, E, M: Memory> {
838 db: QuerySource<'a, M>,
839 request: Request<'a>,
840 entity: PhantomData<E>,
841}
842impl<M: Memory> Database<M> {
843 #[must_use]
845 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
846 Query::new(QuerySource::Direct(self))
847 }
848}
849impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
850 #[inline(never)]
853 pub(crate) fn new(db: QuerySource<'a, M>) -> Self {
854 Self {
855 db,
856 request: Request::default(),
857 entity: PhantomData,
858 }
859 }
860
861 #[must_use]
875 pub fn distinct(mut self) -> Self {
876 self.request.distinct = true;
877
878 self
879 }
880
881 #[must_use]
894 #[inline(never)]
895 pub fn filter(
896 mut self,
897 field: &'a str,
898 comparison: Comparison,
899 value: impl Into<IndexValue<'a>>,
900 ) -> Self {
901 self.request
902 .filter(field, comparison, QueryOperand::Literal(value.into()));
903
904 self
905 }
906
907 #[must_use]
909 pub fn by_id(self, id: impl Into<crate::Id<E>>) -> Self {
910 self.eq(
911 E::SCHEMA.primary_key,
912 id.into().key().into_row_key().index_value(),
913 )
914 }
915
916 #[must_use]
918 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
919 self.filter(field, Comparison::Eq, value)
920 }
921
922 #[must_use]
925 pub fn eq_if_some(self, field: &'a str, value: Option<impl Into<IndexValue<'a>>>) -> Self {
926 match value {
927 Some(value) => self.eq(field, value),
928 None => self,
929 }
930 }
931
932 #[must_use]
934 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
935 self.filter(field, Comparison::Ne, value)
936 }
937
938 #[must_use]
940 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
941 self.filter(field, Comparison::Lt, value)
942 }
943
944 #[must_use]
946 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
947 self.filter(field, Comparison::Le, value)
948 }
949
950 #[must_use]
952 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
953 self.filter(field, Comparison::Gt, value)
954 }
955
956 #[must_use]
958 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
959 self.filter(field, Comparison::Ge, value)
960 }
961
962 #[must_use]
970 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
971 self.request
972 .filter(left, comparison, QueryOperand::Field(right));
973
974 self
975 }
976
977 #[must_use]
982 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
983 self.request
984 .filter(field, comparison, QueryOperand::Length(length));
985
986 self
987 }
988
989 #[must_use]
992 pub fn filter_present(self, field: &'a str) -> Self {
993 self.filter(field, Comparison::Ne, IndexValue::Absent)
994 }
995
996 #[must_use]
999 pub fn filter_absent(self, field: &'a str) -> Self {
1000 self.filter(field, Comparison::Eq, IndexValue::Absent)
1001 }
1002
1003 #[must_use]
1007 pub fn filter_range<T: Into<IndexValue<'a>>>(
1008 self,
1009 field: &'a str,
1010 range: std::ops::Range<T>,
1011 ) -> Self {
1012 self.gte(field, range.start).lt(field, range.end)
1013 }
1014
1015 #[must_use]
1019 pub fn filter_ulid_time(
1020 self,
1021 field: &'a str,
1022 range: std::ops::Range<crate::Timestamp>,
1023 ) -> Self {
1024 let (first, last) =
1025 crate::Ulid::time_bounds(range).unwrap_or((crate::Ulid::MAX, crate::Ulid::MIN));
1026 self.filter_between(field, first, last)
1027 }
1028
1029 #[must_use]
1036 pub fn filter_between(
1037 self,
1038 field: &'a str,
1039 lower: impl Into<IndexValue<'a>>,
1040 upper: impl Into<IndexValue<'a>>,
1041 ) -> Self {
1042 self.filter(field, Comparison::Ge, lower)
1043 .filter(field, Comparison::Le, upper)
1044 }
1045
1046 #[must_use]
1054 pub fn filter_not_between(
1055 self,
1056 field: &'a str,
1057 lower: impl Into<IndexValue<'a>>,
1058 upper: impl Into<IndexValue<'a>>,
1059 ) -> Self {
1060 self.filter_any(&[
1061 (field, Comparison::Lt, lower.into()),
1062 (field, Comparison::Gt, upper.into()),
1063 ])
1064 }
1065
1066 #[must_use]
1075 pub fn filter_any<T: Copy + Into<QueryOperand<'a>>>(
1076 mut self,
1077 alternatives: &[(&'a str, Comparison, T)],
1078 ) -> Self {
1079 self.request.or_clause(
1080 alternatives
1081 .iter()
1082 .map(|&(field, op, value)| (field, op, value.into())),
1083 );
1084 self
1085 }
1086
1087 #[must_use]
1097 pub fn filter_in(
1098 mut self,
1099 field: &'a str,
1100 values: &[impl Copy + Into<IndexValue<'a>>],
1101 ) -> Self {
1102 self.request.or_clause(
1103 values
1104 .iter()
1105 .copied()
1106 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
1107 );
1108
1109 self
1110 }
1111
1112 #[must_use]
1120 pub fn filter_not_in(
1121 mut self,
1122 field: &'a str,
1123 values: &[impl Copy + Into<IndexValue<'a>>],
1124 ) -> Self {
1125 self.request
1126 .filter_not_in(field, values.iter().copied().map(Into::into));
1127
1128 self
1129 }
1130
1131 #[must_use]
1136 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
1137 self.request.using_index(name, values);
1138
1139 self
1140 }
1141
1142 #[must_use]
1145 pub fn order_asc(mut self, field: &'a str) -> Self {
1146 self.request.append_order(field, SortDirection::Ascending);
1147
1148 self
1149 }
1150
1151 #[must_use]
1154 pub fn order_desc(mut self, field: &'a str) -> Self {
1155 self.request.append_order(field, SortDirection::Descending);
1156
1157 self
1158 }
1159
1160 #[must_use]
1172 #[inline(never)]
1173 pub fn order_by(mut self, fields: &[impl Copy + Into<OrderTerm<'a>>]) -> Self {
1174 self.request.order_by(fields);
1175
1176 self
1177 }
1178
1179 #[must_use]
1181 pub fn descending(mut self) -> Self {
1182 self.request.descending = true;
1183
1184 self
1185 }
1186
1187 #[must_use]
1194 pub fn limit(mut self, rows: usize) -> Self {
1195 self.request.rows = rows;
1196
1197 self
1198 }
1199
1200 #[must_use]
1202 pub fn work_limit(mut self, candidates: usize) -> Self {
1203 self.request.work = candidates;
1204
1205 self
1206 }
1207
1208 #[cfg(feature = "test-support")]
1210 #[doc(hidden)]
1211 #[must_use]
1212 pub fn test_output_limit(mut self, bytes: usize) -> Self {
1213 self.request.bytes = bytes;
1214
1215 self
1216 }
1217
1218 #[must_use]
1221 pub fn after(mut self, cursor: impl Into<Option<&'a QueryCursor>>) -> Self {
1222 self.request.cursor = cursor.into();
1223
1224 self
1225 }
1226
1227 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
1234 observe!(query, { self.entity_page() })
1235 }
1236
1237 fn entity_page(self) -> Result<QueryPage<E>, Error> {
1238 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_rows(E::decode)
1239 }
1240
1241 pub fn first(self) -> Result<Option<E>, Error> {
1247 self.single_with(SingleResult::First, Self::entity_page)
1248 }
1249
1250 pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
1254 self.single_with(SingleResult::First, Self::projected_page::<R>)
1255 }
1256
1257 pub fn try_one(self) -> Result<Option<E>, Error> {
1264 self.single_with(SingleResult::Only, Self::entity_page)
1265 }
1266
1267 pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
1273 self.single_with(SingleResult::Only, Self::projected_page::<R>)
1274 }
1275
1276 fn single_with<R>(
1277 mut self,
1278 probe: SingleResult,
1279 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1280 ) -> Result<Option<R>, Error> {
1281 observe!(query, {
1282 if probe == SingleResult::Only && self.request.cursor.is_some() {
1283 return Err(Error::InvalidQuery);
1284 }
1285 if !(1..=32).contains(&self.request.rows) {
1286 return Err(Error::Limit);
1287 }
1288 self.request.single_result_probe = Some(probe);
1289 fetch(self.limit(match probe {
1290 SingleResult::First => 1,
1291 SingleResult::Only => 2,
1292 }))
1293 })
1294 .map(|mut page| page.rows.pop())
1295 }
1296
1297 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1307 observe!(query, { self.projected_page() })
1308 }
1309
1310 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1311 let raw = fetch_rows(
1312 &*self.db.read()?,
1313 E::SCHEMA,
1314 self.request,
1315 Some(Projection::Record(R::definition())),
1316 )?;
1317
1318 raw.decode_rows(decode_record)
1319 }
1320}
1321
1322#[derive(Clone, Copy)]
1323enum Projection<'a> {
1324 Record(&'a TypeSchema),
1325 Columns(&'a [u8]),
1326}
1327
1328impl Projection<'_> {
1329 fn mask(self, entity: &EntitySchema) -> Result<u32, Error> {
1330 match self {
1331 Self::Record(record) => admit_projection(entity, record),
1332 Self::Columns(columns) => {
1333 let mut mask = 0;
1334 for &column in columns {
1335 if usize::from(column) >= entity.fields.len() || mask & (1 << column) != 0 {
1336 return Err(Error::InvalidQuery);
1337 }
1338 mask |= 1 << column;
1339 }
1340 Ok(mask)
1341 }
1342 }
1343 }
1344}
1345
1346fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u32, Error> {
1350 let TypeBody::Record(fields) = &output.body else {
1351 return Err(Error::InvalidQuery);
1352 };
1353 if fields.is_empty()
1354 || fields.len() > crate::schema::MAX_FIELDS
1355 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1356 {
1357 return Err(Error::InvalidQuery);
1358 }
1359 let mut source = TypeGraph::default();
1360 let mut target = TypeGraph::default();
1361 let mut mask = 0;
1362 for field in *fields {
1363 let position = entity
1364 .field_position(field.name)
1365 .ok_or(Error::InvalidQuery)?;
1366 let stored = &entity.fields[position];
1367 if stored.value != field.value || stored.optional != field.optional {
1368 return Err(Error::InvalidQuery);
1369 }
1370 source
1371 .include(stored.value)
1372 .map_err(|_| Error::InvalidQuery)?;
1373 target
1374 .include(field.value)
1375 .map_err(|_| Error::InvalidQuery)?;
1376 mask |= 1 << position;
1377 }
1378 if !source.contains(&target) {
1379 return Err(Error::InvalidQuery);
1380 }
1381
1382 Ok(mask)
1383}
1384
1385struct Term<'a> {
1386 tests_presence: bool,
1387 field: ResolvedField,
1388 comparison: Comparison,
1389 operand: TermOperand<'a>,
1390 or_next: bool,
1391}
1392
1393enum TermOperand<'a> {
1394 Literal {
1395 bytes: Vec<u8>,
1396 value: IndexValue<'a>,
1397 },
1398 Member {
1399 item: FieldType,
1400 needle: MemberNeedle<'a>,
1401 },
1402 Field(ResolvedField),
1403 Length(u32),
1404}
1405
1406enum MemberNeedle<'a> {
1407 Literal(IndexValue<'a>),
1408 Field(ResolvedField),
1409}
1410
1411impl<'a> Term<'a> {
1412 fn admit(entity: &EntitySchema, predicate: &Predicate<'a>) -> Result<AdmittedTerm<'a>, Error> {
1413 let left = ResolvedField::resolve(entity, predicate.field)?;
1414 let (mut selected, mut spans) = (0, 0);
1415 let position = left.position;
1416 let field = &entity.fields[position];
1417 let member = if predicate.comparison == Comparison::Contains {
1418 member_type(field.value)
1419 } else {
1420 None
1421 };
1422 let operand = match (predicate.operand, left.member) {
1423 (QueryOperand::Literal(value), Some(member)) => {
1424 if !predicate.comparison.supports_record_member() {
1425 return Err(Error::InvalidQuery);
1426 }
1427 let leaf = member.field();
1428 predicate
1429 .comparison
1430 .admit(leaf.value, left.optional(entity), value)?;
1431 let literal = value.component(left.optional(entity));
1432 spans |= 1 << position;
1433 TermOperand::Literal {
1434 bytes: literal,
1435 value,
1436 }
1437 }
1438 (QueryOperand::Length(length), member) => {
1439 let selected = member.map_or(field.value, |m| m.field().value);
1440 if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1441 return Err(Error::InvalidQuery);
1442 }
1443 spans |= 1 << position;
1444
1445 TermOperand::Length(length)
1446 }
1447 (QueryOperand::Field(name), left_member) => {
1448 let right = ResolvedField::resolve(entity, name)?;
1449 let right_member = right.member;
1450 if (left_member.is_some() || right_member.is_some())
1451 && member.is_none()
1452 && !predicate.comparison.supports_record_member()
1453 {
1454 return Err(Error::InvalidQuery);
1455 }
1456 let right_type =
1457 right_member.map_or(entity.fields[right.position].value, |m| m.field().value);
1458 let left_type =
1459 left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1460 let compatible = left_type == right_type
1461 || matches!(
1462 (left_type, right_type),
1463 (FieldType::Text { .. }, FieldType::Text { .. })
1464 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1465 );
1466 if !compatible
1467 || !key::supports(left_type)
1468 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1469 {
1470 return Err(Error::InvalidQuery);
1471 }
1472 if right_member.is_some() {
1473 spans |= 1 << right.position;
1474 } else {
1475 selected |= 1 << right.position;
1476 }
1477
1478 if let Some(item) = member {
1479 spans |= 1 << position;
1480
1481 TermOperand::Member {
1482 item,
1483 needle: MemberNeedle::Field(right),
1484 }
1485 } else {
1486 if left_member.is_some() {
1487 spans |= 1 << position;
1488 } else {
1489 selected |= 1 << position;
1490 }
1491 TermOperand::Field(right)
1492 }
1493 }
1494 (QueryOperand::Literal(value), None) => {
1495 if let Some(item) = member {
1496 if !key::supports(item) {
1497 return Err(Error::InvalidQuery);
1498 }
1499 value.admit(item, false)?;
1500
1501 spans |= 1 << position;
1502
1503 TermOperand::Member {
1504 item,
1505 needle: MemberNeedle::Literal(value),
1506 }
1507 } else {
1508 let absent = value == IndexValue::Absent;
1509 if key::supports(field.value) {
1510 selected |= 1 << position;
1511 } else if absent
1512 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1513 {
1514 spans |= 1 << position;
1515 } else {
1516 return Err(Error::InvalidQuery);
1517 }
1518 predicate
1519 .comparison
1520 .admit(field.value, field.optional, value)?;
1521 let bytes = value.component(field.optional);
1522
1523 TermOperand::Literal { bytes, value }
1524 }
1525 }
1526 };
1527 Ok(AdmittedTerm {
1528 selected,
1529 spans,
1530 term: Term {
1531 tests_presence: predicate.tests_presence(entity, &operand),
1532 field: left,
1533 comparison: predicate.comparison,
1534 operand,
1535 or_next: predicate.or_next,
1536 },
1537 })
1538 }
1539}
1540struct AdmittedTerm<'a> {
1541 term: Term<'a>,
1542 selected: u32,
1543 spans: u32,
1544}
1545
1546fn admit_literal_size(value: &IndexValue<'_>) -> Result<(), Error> {
1549 let size = match value {
1550 IndexValue::Text(text) => text.len(),
1551 IndexValue::Blob(bytes) => bytes.len(),
1552 _ => return Ok(()),
1553 };
1554 if size > crate::codec::MAX_ROW_BYTES {
1555 return Err(Error::Limit);
1556 }
1557 Ok(())
1558}
1559
1560fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1561 match value {
1562 IndexValue::Text(text) => Some(text.as_bytes()),
1563 IndexValue::Blob(bytes) => Some(bytes),
1564 _ => None,
1565 }
1566}
1567
1568fn consecutive_values(low: IndexValue<'_>, high: IndexValue<'_>) -> bool {
1569 low.discrete_successor()
1570 .is_some_and(|next| equal_values(next, high))
1571}
1572
1573fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1574 match (left, right) {
1576 (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1577 a == b
1578 }
1579 _ => left == right,
1580 }
1581}
1582
1583fn length_limit(field: FieldType) -> Option<u32> {
1584 match key::operand_type(field) {
1585 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1586 FieldType::List { max_items, .. } => Some(max_items),
1587 FieldType::Named(link) => match (link.definition)().body {
1588 TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1589 _ => None,
1590 },
1591 _ => None,
1592 }
1593}
1594
1595fn member_type(field: FieldType) -> Option<FieldType> {
1596 match key::operand_type(field) {
1597 FieldType::List { item, .. } => Some(*item),
1598 FieldType::Named(link) => match (link.definition)().body {
1599 TypeBody::Set { item, .. } => Some(item),
1600 _ => None,
1601 },
1602 _ => None,
1603 }
1604}
1605
1606fn contains_member(
1608 span: &[u8],
1609 optional: bool,
1610 item: FieldType,
1611 needle: IndexValue<'_>,
1612) -> Result<bool, Error> {
1613 let mut reader = Decoder::new(span)?;
1614 if optional && !reader.boolean()? {
1615 return Ok(false);
1616 }
1617 for _ in 0..reader.nat32()? {
1618 let value = IndexValue::read(&mut reader, item)?;
1619 if equal_values(value, needle) {
1620 return Ok(true);
1621 }
1622 }
1623
1624 Ok(false)
1625}
1626
1627pub(super) fn set_bit_positions(mut mask: u32) -> impl Iterator<Item = usize> {
1629 std::iter::from_fn(move || {
1630 if mask == 0 {
1631 return None;
1632 }
1633 let position = mask.trailing_zeros() as usize;
1634 mask &= mask - 1;
1635 Some(position)
1636 })
1637}
1638
1639fn admit_ordered_fields(entity: &EntitySchema, mask: u32) -> Result<(), Error> {
1640 for i in set_bit_positions(mask) {
1641 if !key::supports(entity.fields[i].value) {
1642 return Err(Error::InvalidQuery);
1643 }
1644 }
1645
1646 Ok(())
1647}
1648
1649fn comparison_key(
1651 entity: &EntitySchema,
1652 mask: u32,
1653 values: &[IndexValue<'_>],
1654 scratch: &mut Vec<u8>,
1655) -> Result<(), Error> {
1656 build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1657}
1658
1659fn build_comparison_key<'a>(
1660 entity: &EntitySchema,
1661 mask: u32,
1662 key: &mut Vec<u8>,
1663 mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1664) -> Result<(), Error> {
1665 key.clear();
1666 for i in set_bit_positions(mask) {
1667 let field = &entity.fields[i];
1668 value(i, field)?.append_component(field.optional, key);
1669 if key.len() > MAX_COMPARISON_KEY {
1670 return Err(Error::Limit);
1671 }
1672 }
1673
1674 Ok(())
1675}
1676
1677fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1678 if size > limit {
1679 return Err(Error::RowTooLarge);
1680 }
1681 if size > limit - *used {
1682 return Err(Error::Limit);
1683 }
1684 *used += size;
1685
1686 Ok(())
1687}
1688
1689fn projection_size(spans: &[(u16, u16)], mask: u32) -> usize {
1691 set_bit_positions(mask)
1692 .map(|i| {
1693 let (start, end) = spans[i];
1694 usize::from(end - start)
1695 })
1696 .sum()
1697}
1698
1699fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u32, size: usize) -> Vec<u8> {
1700 let mut output = Vec::with_capacity(size);
1701 for i in set_bit_positions(mask) {
1702 let (start, end) = spans[i];
1703 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1704 }
1705
1706 output
1707}
1708#[derive(Clone, Copy)]
1709enum PlanOutput {
1710 Rows,
1711 Aggregate { grouped: bool },
1712 ImmediateCount,
1713}
1714
1715struct Plan<'a> {
1716 primary: usize,
1717 index: Option<&'a IndexSchema>,
1718 prefix: Vec<u8>,
1719 cursor_prefix_len: usize,
1721 fixed_components: usize,
1722 terms: Vec<Term<'a>>,
1723 selected: u32,
1724 span_fields: u32,
1726 binding: [u8; 32],
1727 projection: Option<u32>,
1728 distinct: distinct::Strategy,
1729 sort: Option<Vec<order::SortField>>,
1730 descending: bool,
1731}
1732impl<'a> Plan<'a> {
1733 fn clauses(&self) -> impl Iterator<Item = &[Term<'a>]> {
1734 self.terms.split_inclusive(|term| !term.or_next)
1735 }
1736
1737 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1738 self.index = Some(path.index);
1739 self.cursor_prefix_len = path.prefix.len();
1740 self.prefix = path.prefix;
1741 self.fixed_components = path.fixed;
1742 self.selected |= entity.key_fields();
1743 }
1744
1745 fn admit(
1746 entity: &'a EntitySchema,
1747 request: &Request<'a>,
1748 schema: [u8; 32],
1749 incarnation: [u8; 16],
1750 projection: Option<Projection<'_>>,
1751 output: PlanOutput,
1752 ) -> Result<Self, Error> {
1753 if !request.within_limits() {
1754 return Err(Error::Limit);
1755 }
1756 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1757 {
1758 return Err(Error::InvalidQuery);
1759 }
1760 for value in request
1762 .predicates
1763 .iter()
1764 .filter_map(|p| match &p.operand {
1765 QueryOperand::Literal(value) => Some(value),
1766 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1767 })
1768 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1769 {
1770 admit_literal_size(value)?;
1771 }
1772 let primary = entity
1773 .primary_position()
1774 .filter(|&i| !entity.fields[i].optional)
1775 .ok_or(Error::InvalidQuery)?;
1776 let mut plan = Self {
1777 primary,
1778 index: None,
1779 prefix: prefix(2, entity.id, &[]),
1780 cursor_prefix_len: ENTITY_PREFIX_BYTES,
1781 fixed_components: 0,
1782 terms: Vec::new(),
1783 selected: 1 << primary,
1784 span_fields: 0,
1785 binding: [0; 32],
1786 projection: projection.map(|output| output.mask(entity)).transpose()?,
1787 distinct: distinct::Strategy::Identity,
1788 sort: None,
1789 descending: request.descending ^ request.primary_descending(entity),
1790 };
1791 for predicate in &request.predicates {
1792 let admitted = Term::admit(entity, predicate)?;
1793 plan.selected |= admitted.selected;
1794 plan.span_fields |= admitted.spans;
1795 plan.terms.push(admitted.term);
1796 }
1797 match order::select(entity, request, output)? {
1800 order::Path::Primary => {}
1801 order::Path::Index(path, descending) => {
1802 plan.use_index(entity, path);
1803 plan.descending = request.descending ^ descending;
1804 }
1805 order::Path::Filtered { sort } => {
1806 order::select_filtered_path(entity, request, &mut plan, None)?;
1807 for term in sort.iter().flatten() {
1808 if term.field.member.is_some() {
1809 plan.span_fields |= 1 << term.field.position;
1810 } else {
1811 plan.selected |= 1 << term.field.position;
1812 }
1813 }
1814 plan.sort = sort;
1815 }
1816 }
1817 if request.distinct {
1818 plan.distinct = distinct::admit(entity, request, &plan)?;
1819 match plan.distinct {
1820 distinct::Strategy::FirstMatch => plan.sort = None,
1821 distinct::Strategy::Complete { key_fields } => plan.selected |= key_fields,
1822 _ => {}
1823 }
1824 }
1825 if request.index.is_some()
1828 && !request.predicates.is_empty()
1829 && let Some(index) = plan.index
1830 {
1831 for field in &index.fields[plan.fixed_components..] {
1832 let Some(value) = order::equality(entity, request, field) else {
1833 break;
1834 };
1835 let schema = entity.index_field(field).ok_or(Error::InvalidSchema)?;
1836 let len = plan.prefix.len();
1837 value.append_component(schema.optional, &mut plan.prefix);
1838 if plan.prefix.len() > crate::MAX_INDEX_KEY_BYTES {
1839 plan.prefix.truncate(len);
1840 break;
1841 }
1842 plan.fixed_components += 1;
1843 }
1844 }
1845 if matches!(output, PlanOutput::ImmediateCount)
1847 || (request.single_result_probe.is_some() && request.cursor.is_none())
1848 {
1849 return Ok(plan);
1850 }
1851 plan.bind_cursor(entity, request, schema, incarnation, projection)?;
1852
1853 Ok(plan)
1854 }
1855}
1856
1857fn consume_index_component(
1859 entity: &EntitySchema,
1860 index: &IndexSchema,
1861 name: &str,
1862 remaining: &mut &[u8],
1863) -> Result<(), Error> {
1864 let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
1865
1866 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
1867}
1868
1869#[inline(never)]
1872#[expect(
1873 clippy::needless_pass_by_value,
1874 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1875)]
1876fn fetch_rows<M: Memory>(
1877 db: &Database<M>,
1878 entity: &EntitySchema,
1879 request: Request<'_>,
1880 projection: Option<Projection<'_>>,
1881) -> Result<QueryPage<Vec<u8>>, Error> {
1882 db.schema.admits(entity)?;
1883 let plan = Plan::admit(
1884 entity,
1885 &request,
1886 db.schema.fingerprint(),
1887 db.incarnation,
1888 projection,
1889 PlanOutput::Rows,
1890 )?;
1891
1892 execute(&db.map, entity, &request, &plan, None)
1893}
1894
1895fn execute<M: Memory>(
1896 map: &Map<M>,
1897 entity: &EntitySchema,
1898 request: &Request<'_>,
1899 plan: &Plan<'_>,
1900 mut aggregate: Option<aggregate::Accumulator<'_>>,
1901) -> Result<QueryPage<Vec<u8>>, Error> {
1902 execute_inner(
1903 map,
1904 entity,
1905 request,
1906 plan,
1907 range::bounds(entity, request, plan)?,
1908 aggregate.as_mut(),
1909 None,
1910 )
1911}
1912
1913const STEP_INPUT_BYTES: usize = 64 * 1024;
1916const fn candidate_byte_limit(row_bytes: usize) -> usize {
1917 row_bytes + 2 * crate::MAX_INDEX_KEY_BYTES
1918}
1919
1920fn execute_inner<M: Memory>(
1921 map: &Map<M>,
1922 entity: &EntitySchema,
1923 request: &Request<'_>,
1924 plan: &Plan<'_>,
1925 bounds: Option<range::Bounds>,
1926 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1927 mut input_bytes: Option<&mut usize>,
1928) -> Result<QueryPage<Vec<u8>>, Error> {
1929 let mut page = QueryPage {
1930 rows: Vec::new(),
1931 next: None,
1932 examined: 0,
1933 fetched: 0,
1934 output_bytes: 0,
1935 };
1936 let Some(bounds) = bounds else {
1937 return Ok(page);
1938 };
1939 let terminal = range::terminal_key(&bounds, plan.descending);
1940 let mut next_entry = range::entries(map, &bounds, plan.descending);
1941 let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
1942 Some(distinct::Collection::new(
1943 plan.projection.ok_or(Error::InvalidQuery)?,
1944 key_fields,
1945 ))
1946 } else {
1947 None
1948 };
1949 let mut sorted = plan
1950 .sort
1951 .as_ref()
1952 .map(|_| sort::Collection::new(request, plan.distinct));
1953 let mut component = Vec::new();
1954 let mut right_component = Vec::new();
1955 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
1957 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1958 } else {
1959 None
1960 };
1961 let candidate_bytes = candidate_byte_limit(entity.max_row_bytes);
1962 let primary_type = entity.fields[plan.primary].value;
1963 let needs_spans = plan.index.is_some()
1964 || plan.span_fields != 0
1965 || match &aggregate {
1966 Some(accumulator) => accumulator.needs_spans(),
1967 None => plan.projection.is_some(),
1968 };
1969 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1971 let mut index_info = None;
1972 while let Some((stored_key, stored_value)) = next_entry() {
1973 if page.examined == request.work {
1976 return Err(Error::Limit);
1977 }
1978 page.examined += 1;
1979 let mut read_bytes = stored_key.len();
1980 let (owner, bytes) = if plan.index.is_some() {
1981 read_bytes += stored_value.len();
1982 read_index_owner(map, entity.id, primary_type, &stored_value)?
1983 } else {
1984 (
1985 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
1986 stored_value,
1987 )
1988 };
1989 if let Some(used) = input_bytes.as_deref_mut() {
1990 read_bytes += bytes.len();
1991 if read_bytes > candidate_bytes {
1992 return Err(Error::Corrupt);
1993 }
1994 *used += read_bytes;
1995 }
1996 page.fetched += 1;
1997 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
1998 entity.inspect_fields(
1999 &bytes,
2000 plan.selected,
2001 &mut values,
2002 needs_spans.then_some(&mut spans),
2003 )?;
2004 let row_key = RowKey::from_index(values[plan.primary])?;
2005 if plan.index.is_some() {
2006 let info = index_info.get_or_insert_with(|| crate::__private::RowInfo::new(row_key));
2007 info.key = row_key;
2008 entity.fill_index_info(&values, &bytes, &spans, info)?;
2009 validate_index_entry(entity, info, owner, &stored_key)?;
2010 } else if row_key != owner {
2011 return Err(Error::Corrupt);
2012 }
2013 let matches = predicate::PredicateRow {
2014 entity,
2015 bytes: &bytes,
2016 values: &values,
2017 spans: &spans,
2018 span_fields: plan.span_fields,
2019 }
2020 .matches(&plan.terms, &mut component, &mut right_component)?;
2021 let boundary = distinct::boundary(entity, plan.index, plan.distinct, &stored_key)?;
2022 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2023 if matches && let Some(accumulator) = aggregate.as_mut() {
2024 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2025 if matches!(accumulator, aggregate::Accumulator::Until(remaining) if **remaining == 0) {
2026 return Ok(page);
2028 }
2029 } else if matches && let Some(collection) = collected.as_mut() {
2030 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2031 if request.single_result_probe == Some(SingleResult::First) {
2033 break;
2034 }
2035 } else if matches && let Some(collection) = sorted.as_mut() {
2036 collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2037 request.check_result_count(collection.result_count())?;
2039 } else if matches && !duplicate {
2040 request.check_result_count(page.rows.len() + 1)?;
2041 let size = plan
2042 .projection
2043 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2044 if size > request.bytes {
2045 return Err(Error::RowTooLarge);
2046 }
2047 if size > request.bytes - page.output_bytes {
2048 page.next = Some(plan.cursor(&stored_key, Resume::Retry));
2049
2050 return Ok(page);
2051 }
2052 page.output_bytes += size;
2053 if let Some(mask) = plan.projection {
2054 page.rows.push(copy_projection(&bytes, &spans, mask, size));
2055 } else {
2056 page.rows.push(bytes);
2057 }
2058 if request.single_result_probe == Some(SingleResult::First)
2059 || plan.distinct.finishes_on_match(plan.fixed_components)
2060 {
2061 return Ok(page);
2062 }
2063 if let Some(boundary) = boundary {
2064 previous = Some(boundary.to_vec());
2065 }
2066 }
2067 if page.rows.len() == request.rows
2068 || page.examined == request.work
2069 || input_bytes
2070 .as_deref()
2071 .is_some_and(|used| *used > STEP_INPUT_BYTES - candidate_bytes)
2072 {
2073 if terminal == Some(&stored_key) {
2074 break;
2075 }
2076 if request.single_result_probe.is_some()
2077 || (aggregate.is_some() && input_bytes.is_none())
2078 || collected.is_some()
2079 || sorted.is_some()
2080 {
2081 continue;
2084 }
2085 if input_bytes.is_some() && next_entry().is_none() {
2089 break;
2090 }
2091 let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
2092 Resume::AfterUnemittedClass
2093 } else {
2094 Resume::After
2095 };
2096 page.next = Some(plan.cursor(&stored_key, resume));
2097
2098 return Ok(page);
2099 }
2100 }
2101 if let Some(collection) = collected {
2102 page.output_bytes = collection.output_bytes;
2103 page.rows = collection.rows;
2104 }
2105 if let Some(collection) = sorted {
2106 collection.finish(request.bytes, &mut page)?;
2107 }
2108
2109 Ok(page)
2110}