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