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_rows<R>(
323 self,
324 decode: impl Fn(&[u8]) -> Result<R, Error>,
325 ) -> Result<QueryPage<R>, Error> {
326 Ok(QueryPage {
327 rows: self
328 .rows
329 .iter()
330 .map(|bytes| decode(bytes))
331 .collect::<Result<_, _>>()?,
332 next: self.next,
333 examined: self.examined,
334 fetched: self.fetched,
335 output_bytes: self.output_bytes,
336 })
337 }
338}
339
340fn decode_exact<R>(
341 bytes: &[u8],
342 decode: impl FnOnce(&mut Decoder<'_>) -> Result<R, Error>,
343) -> Result<R, Error> {
344 let mut reader = Decoder::new(bytes)?;
345 let value = decode(&mut reader)?;
346 reader.finish()?;
347 Ok(value)
348}
349
350fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
351 decode_exact(bytes, R::decode_from)
352}
353
354#[derive(Clone, Copy, Debug, PartialEq, Eq)]
356pub enum QueryOperand<'a> {
357 Literal(IndexValue<'a>),
359 Length(u32),
361 Field(&'a str),
363}
364
365impl<'a, T: Into<IndexValue<'a>>> From<T> for QueryOperand<'a> {
366 fn from(value: T) -> Self {
367 Self::Literal(value.into())
368 }
369}
370
371struct Predicate<'a> {
372 field: &'a str,
373 comparison: Comparison,
374 operand: QueryOperand<'a>,
375 or_next: bool,
377}
378
379impl<'a> Predicate<'a> {
380 fn compared_field(&self, name: &str) -> Option<&'a str> {
382 let QueryOperand::Field(right) = self.operand else {
383 return None;
384 };
385 if self.field == name {
386 Some(right)
387 } else if right == name {
388 Some(self.field)
389 } else {
390 None
391 }
392 }
393
394 fn at_extreme(&self, entity: &EntitySchema, value: IndexValue<'_>, upper: bool) -> bool {
396 use crate::{Date, Duration, Timestamp, Ulid};
397
398 match value {
399 IndexValue::Bool(b) => b == upper,
400 IndexValue::Date(d) => d == if upper { Date::MAX } else { Date::MIN },
401 IndexValue::Timestamp(t) => {
402 t == if upper {
403 Timestamp::MAX
404 } else {
405 Timestamp::MIN
406 }
407 }
408 IndexValue::Duration(d) => d == if upper { Duration::MAX } else { Duration::MIN },
409 IndexValue::Ulid(id) => id == if upper { Ulid::MAX } else { Ulid::MIN },
410 IndexValue::UnitEnum { ordinal, .. } => entity
411 .index_field(self.field)
412 .is_some_and(|field| key::is_fixed_extreme(field.value, &[ordinal], upper)),
413 IndexValue::Text("") | IndexValue::Blob([]) => !upper,
414 _ => value.is_integer_extreme(upper),
415 }
416 }
417
418 fn fixed_equality(&self, entity: &EntitySchema) -> Option<(&'a str, IndexValue<'a>)> {
420 if let QueryOperand::Length(n) = self.operand {
421 let empty = self
422 .comparison
423 .empty_length_value(n, entity.index_field(self.field)?.value)?;
424 return Some((self.field, empty));
425 }
426 let QueryOperand::Literal(value) = self.operand else {
427 return None;
428 };
429 let fixed = match (self.comparison, value) {
431 (Comparison::Eq, _) => value,
432 (Comparison::Ne, IndexValue::Bool(excluded))
433 if entity.field_is_required(self.field) =>
434 {
435 IndexValue::Bool(!excluded)
436 }
437 (cmp @ (Comparison::Ge | Comparison::Le), _)
438 if self.at_extreme(entity, value, cmp == Comparison::Ge) =>
439 {
440 value
441 }
442 (Comparison::Gt, IndexValue::Bool(false)) => IndexValue::Bool(true),
443 (Comparison::Lt, IndexValue::Bool(true)) => IndexValue::Bool(false),
444 _ => return None,
445 };
446 Some((self.field, fixed))
447 }
448
449 fn tests_presence(&self, entity: &EntitySchema, operand: &TermOperand) -> bool {
451 match (self.comparison, self.operand) {
452 (Comparison::Ne, QueryOperand::Literal(IndexValue::Absent)) => true,
453 (cmp @ (Comparison::Le | Comparison::Ge), QueryOperand::Literal(value)) => {
454 self.at_extreme(entity, value, cmp == Comparison::Le)
455 }
456 (_, QueryOperand::Length(_)) => {
457 self.present_length_result(entity) == Some(true)
458 && self.comparison != Comparison::Ne
459 }
460 (
461 Comparison::Le
462 | Comparison::Ge
463 | Comparison::StartsWith
464 | Comparison::EndsWith
465 | Comparison::Contains,
466 QueryOperand::Field(right),
467 ) => right == self.field,
468 (
469 Comparison::StartsWith | Comparison::EndsWith | Comparison::Contains,
470 QueryOperand::Literal(needle),
471 ) => {
472 !matches!(operand, TermOperand::Member { .. })
474 && scalar_bytes(needle).is_some_and(<[u8]>::is_empty)
475 }
476 _ => false,
477 }
478 }
479
480 fn present_length_result(&self, entity: &EntitySchema) -> Option<bool> {
482 let QueryOperand::Length(n) = self.operand else {
483 return None;
484 };
485 let max = length_limit(entity.index_field(self.field)?.value)?;
486 self.comparison.uniform_length_result(0, max, n)
487 }
488
489 fn constant_comparison(&self, entity: &EntitySchema) -> Option<bool> {
490 if let QueryOperand::Literal(value) = self.operand {
491 return match (self.comparison, value) {
493 (cmp @ (Comparison::Lt | Comparison::Gt), value)
494 if self.at_extreme(entity, value, cmp == Comparison::Gt) =>
495 {
496 Some(false)
497 }
498 _ => None,
499 };
500 }
501 if matches!(self.operand, QueryOperand::Length(_)) {
502 let result = self.present_length_result(entity)?;
503 return (result == self.comparison.accepts_absent(false)
504 || entity.field_is_required(self.field))
505 .then_some(result);
506 }
507 if !matches!(self.operand, QueryOperand::Field(right) if right == self.field) {
508 return None;
509 }
510 match self.comparison {
511 Comparison::Eq => Some(true),
512 Comparison::Ne | Comparison::Lt | Comparison::Gt => Some(false),
513 _ => None,
514 }
515 }
516}
517
518#[derive(Clone, Copy, PartialEq, Eq)]
519enum SingleResult {
520 First,
521 Only,
522}
523
524struct Request<'a> {
525 groups: aggregate::GroupRequest<'a>,
526 predicates: Vec<Predicate<'a>>,
527 index: Option<(&'a str, Vec<IndexValue<'a>>)>,
528 order: Option<Vec<OrderTerm<'a>>>,
529 descending: bool,
530 distinct: bool,
531 single_result_probe: Option<SingleResult>,
532 rows: usize,
533 work: usize,
534 bytes: usize,
535 cursor: Option<&'a QueryCursor>,
536 over_limit: bool,
537}
538
539impl Default for Request<'_> {
540 fn default() -> Self {
541 Self {
542 groups: aggregate::GroupRequest::default(),
543 predicates: Vec::new(),
544 index: None,
545 order: None,
546 descending: false,
547 distinct: false,
548 single_result_probe: None,
549 rows: 32,
550 work: 128,
551 bytes: MAX_OUTPUT,
552 cursor: None,
553 over_limit: false,
554 }
555 }
556}
557
558impl<'a> Request<'a> {
561 fn within_limits(&self) -> bool {
562 !self.over_limit
563 && (1..=32).contains(&self.rows)
564 && (1..=MAX_WORK).contains(&self.work)
565 && (1..=MAX_OUTPUT).contains(&self.bytes)
566 }
567
568 fn check_result_count(&self, count: usize) -> Result<(), Error> {
571 if self.single_result_probe == Some(SingleResult::Only) && count > 1 {
572 return Err(Error::MultipleMatches);
573 }
574 Ok(())
575 }
576
577 fn fixed_equalities<'r>(
579 &'r self,
580 entity: &'r EntitySchema,
581 ) -> impl Iterator<Item = (&'a str, IndexValue<'a>)> + 'r {
582 self.clauses().filter_map(move |clause| {
583 let (predicate, rest) = clause.split_first()?;
584 if !rest.is_empty() {
585 let mut candidate = predicate.fixed_equality(entity)?;
586 for alternative in rest {
587 let other = alternative.fixed_equality(entity)?;
588 if candidate.0 != other.0 {
589 return None;
590 }
591 if equal_values(candidate.1, other.1) {
592 continue;
593 }
594 if self.predicates.len() == clause.len() {
595 return None;
596 }
597 if self.excludes_literal(other.0, other.1) {
598 continue;
599 }
600 if !self.excludes_literal(candidate.0, candidate.1) {
601 return None;
602 }
603 candidate = other;
604 }
605 return Some(candidate);
608 }
609 if let Some(equality) = predicate.fixed_equality(entity) {
610 return Some(equality);
611 }
612 let QueryOperand::Literal(value) = predicate.operand else {
615 return None;
616 };
617 let lower = match predicate.comparison {
618 Comparison::Ge => value,
619 Comparison::Gt if self.predicates.len() > 1 => value.discrete_successor()?,
620 _ => return None,
621 };
622 self.clauses()
623 .any(|clause| {
624 let [upper] = clause else { return false };
625 if upper.field != predicate.field {
626 return false;
627 }
628 match (upper.comparison, upper.operand) {
629 (Comparison::Le, QueryOperand::Literal(value)) => {
630 equal_values(lower, value)
631 }
632 (Comparison::Lt, QueryOperand::Literal(value)) => {
633 consecutive_values(lower, value)
634 }
635 _ => false,
636 }
637 })
638 .then_some((predicate.field, lower))
639 })
640 }
641
642 fn excludes_literal(&self, field: &str, value: IndexValue<'_>) -> bool {
643 self.clauses().any(|clause| {
646 clause.iter().all(|predicate| {
647 if predicate.field != field {
648 return false;
649 }
650 let QueryOperand::Literal(literal) = predicate.operand else {
651 return false;
652 };
653 predicate.comparison.is_relational()
654 && predicate.comparison.accepts_fixed_values(value, literal) == Some(false)
655 })
656 })
657 }
658
659 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
660 self.predicates.split_inclusive(|p| !p.or_next)
661 }
662
663 #[inline(never)]
664 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
665 if self.predicates.len() == MAX_TERMS {
666 self.over_limit = true;
667 } else {
668 self.predicates.push(Predicate {
669 field,
670 comparison,
671 operand,
672 or_next: false,
673 });
674 }
675 }
676
677 #[inline(never)]
678 fn or_clause(
679 &mut self,
680 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
681 ) {
682 append_clause(
683 &mut self.predicates,
684 &mut self.over_limit,
685 alternatives,
686 |(field, comparison, operand), or_next| Predicate {
687 field,
688 comparison,
689 operand,
690 or_next,
691 },
692 );
693 }
694
695 #[inline(never)]
696 fn filter_not_in(
697 &mut self,
698 field: &'a str,
699 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
700 ) {
701 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
702 self.over_limit = true;
703
704 return;
705 }
706 for value in values {
707 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
708 }
709 }
710
711 #[inline(never)]
712 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
713 if values.len() > 4 {
714 self.over_limit = true;
715 } else {
716 self.index = Some((name, values.to_vec()));
717 }
718 }
719
720 #[inline(never)]
721 fn order_by<T: Copy + Into<OrderTerm<'a>>>(&mut self, fields: &[T]) {
722 if fields.len() > 4 {
723 self.over_limit = true;
724
725 return;
726 }
727 self.order = Some(fields.iter().copied().map(Into::into).collect());
728 }
729
730 fn append_order(&mut self, field: &'a str, direction: SortDirection) {
731 let fields = self.order.get_or_insert_with(Vec::new);
732 if fields.len() == 4 {
733 self.over_limit = true;
734
735 return;
736 }
737 fields.push(OrderTerm { field, direction });
738 }
739
740 fn primary_descending(&self, entity: &EntitySchema) -> bool {
741 self.order
742 .as_deref()
743 .and_then(|order| order.last())
744 .is_some_and(|term| {
745 term.field == entity.primary_key && term.direction == SortDirection::Descending
746 })
747 }
748}
749
750fn append_clause<I, T>(
751 predicates: &mut Vec<T>,
752 over_limit: &mut bool,
753 terms: impl ExactSizeIterator<Item = I>,
754 predicate: impl Fn(I, bool) -> T,
755) {
756 let count = terms.len();
757 if count == 0 || count > MAX_TERMS - predicates.len() {
758 *over_limit = true;
759 return;
760 }
761 predicates.extend(
762 terms
763 .enumerate()
764 .map(|(i, term)| predicate(term, i + 1 < count)),
765 );
766}
767
768pub(super) fn source_page<M: Memory>(
770 map: &Map<M>,
771 entity: &EntitySchema,
772 binding: [u8; 32],
773 incarnation: [u8; 16],
774 cursor: Option<&QueryCursor>,
775 rows: usize,
776 bytes: usize,
777) -> Result<QueryPage<Vec<u8>>, Error> {
778 let request = Request {
779 rows,
780 work: rows,
781 bytes,
782 cursor,
783 ..Request::default()
784 };
785 let plan = Plan::admit(
786 entity,
787 &request,
788 binding,
789 incarnation,
790 None,
791 PlanOutput::Rows,
792 )?;
793
794 execute(map, entity, &request, &plan, None)
795}
796
797enum QuerySource<'a, M: Memory> {
798 Direct(&'a Database<M>),
799 Session(Rc<RefCell<Database<M>>>),
800}
801
802enum QueryRead<'a, M: Memory> {
803 Direct(&'a Database<M>),
804 Session(Ref<'a, Database<M>>),
805}
806
807impl<M: Memory> Deref for QueryRead<'_, M> {
808 type Target = Database<M>;
809
810 fn deref(&self) -> &Self::Target {
811 match self {
812 Self::Direct(db) => db,
813 Self::Session(db) => db,
814 }
815 }
816}
817
818impl<M: Memory> QuerySource<'_, M> {
819 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
820 match self {
821 Self::Direct(db) => Ok(QueryRead::Direct(db)),
822 Self::Session(db) => db
823 .try_borrow()
824 .map(QueryRead::Session)
825 .map_err(|_| Error::BorrowConflict),
826 }
827 }
828}
829
830pub struct Query<'a, E, M: Memory> {
834 db: QuerySource<'a, M>,
835 request: Request<'a>,
836 entity: PhantomData<E>,
837}
838impl<M: Memory> Database<M> {
839 #[must_use]
841 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
842 Query::new(QuerySource::Direct(self))
843 }
844}
845impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
846 pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
847 Self::new(QuerySource::Session(db))
848 }
849
850 fn new(db: QuerySource<'a, M>) -> Self {
851 Self {
852 db,
853 request: Request::default(),
854 entity: PhantomData,
855 }
856 }
857
858 #[must_use]
872 pub fn distinct(mut self) -> Self {
873 self.request.distinct = true;
874
875 self
876 }
877
878 #[must_use]
891 pub fn filter(
892 mut self,
893 field: &'a str,
894 comparison: Comparison,
895 value: impl Into<IndexValue<'a>>,
896 ) -> Self {
897 self.request
898 .filter(field, comparison, QueryOperand::Literal(value.into()));
899
900 self
901 }
902
903 #[must_use]
905 pub fn by_id(self, id: impl Into<crate::Id<E>>) -> Self {
906 self.eq(
907 E::SCHEMA.primary_key,
908 id.into().key().into_row_key().index_value(),
909 )
910 }
911
912 #[must_use]
914 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
915 self.filter(field, Comparison::Eq, value)
916 }
917
918 #[must_use]
921 pub fn eq_if_some(self, field: &'a str, value: Option<impl Into<IndexValue<'a>>>) -> Self {
922 match value {
923 Some(value) => self.eq(field, value),
924 None => self,
925 }
926 }
927
928 #[must_use]
930 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
931 self.filter(field, Comparison::Ne, value)
932 }
933
934 #[must_use]
936 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
937 self.filter(field, Comparison::Lt, value)
938 }
939
940 #[must_use]
942 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
943 self.filter(field, Comparison::Le, value)
944 }
945
946 #[must_use]
948 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
949 self.filter(field, Comparison::Gt, value)
950 }
951
952 #[must_use]
954 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
955 self.filter(field, Comparison::Ge, value)
956 }
957
958 #[must_use]
966 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
967 self.request
968 .filter(left, comparison, QueryOperand::Field(right));
969
970 self
971 }
972
973 #[must_use]
978 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
979 self.request
980 .filter(field, comparison, QueryOperand::Length(length));
981
982 self
983 }
984
985 #[must_use]
988 pub fn filter_present(self, field: &'a str) -> Self {
989 self.filter(field, Comparison::Ne, IndexValue::Absent)
990 }
991
992 #[must_use]
995 pub fn filter_absent(self, field: &'a str) -> Self {
996 self.filter(field, Comparison::Eq, IndexValue::Absent)
997 }
998
999 #[must_use]
1003 pub fn filter_range<T: Into<IndexValue<'a>>>(
1004 self,
1005 field: &'a str,
1006 range: std::ops::Range<T>,
1007 ) -> Self {
1008 self.gte(field, range.start).lt(field, range.end)
1009 }
1010
1011 #[must_use]
1015 pub fn filter_ulid_time(
1016 self,
1017 field: &'a str,
1018 range: std::ops::Range<crate::Timestamp>,
1019 ) -> Self {
1020 let (first, last) =
1021 crate::Ulid::time_bounds(range).unwrap_or((crate::Ulid::MAX, crate::Ulid::MIN));
1022 self.filter_between(field, first, last)
1023 }
1024
1025 #[must_use]
1032 pub fn filter_between(
1033 self,
1034 field: &'a str,
1035 lower: impl Into<IndexValue<'a>>,
1036 upper: impl Into<IndexValue<'a>>,
1037 ) -> Self {
1038 self.filter(field, Comparison::Ge, lower)
1039 .filter(field, Comparison::Le, upper)
1040 }
1041
1042 #[must_use]
1050 pub fn filter_not_between(
1051 self,
1052 field: &'a str,
1053 lower: impl Into<IndexValue<'a>>,
1054 upper: impl Into<IndexValue<'a>>,
1055 ) -> Self {
1056 self.filter_any(&[
1057 (field, Comparison::Lt, lower.into()),
1058 (field, Comparison::Gt, upper.into()),
1059 ])
1060 }
1061
1062 #[must_use]
1071 pub fn filter_any<T: Copy + Into<QueryOperand<'a>>>(
1072 mut self,
1073 alternatives: &[(&'a str, Comparison, T)],
1074 ) -> Self {
1075 self.request.or_clause(
1076 alternatives
1077 .iter()
1078 .map(|&(field, op, value)| (field, op, value.into())),
1079 );
1080 self
1081 }
1082
1083 #[must_use]
1093 pub fn filter_in(
1094 mut self,
1095 field: &'a str,
1096 values: &[impl Copy + Into<IndexValue<'a>>],
1097 ) -> Self {
1098 self.request.or_clause(
1099 values
1100 .iter()
1101 .copied()
1102 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
1103 );
1104
1105 self
1106 }
1107
1108 #[must_use]
1116 pub fn filter_not_in(
1117 mut self,
1118 field: &'a str,
1119 values: &[impl Copy + Into<IndexValue<'a>>],
1120 ) -> Self {
1121 self.request
1122 .filter_not_in(field, values.iter().copied().map(Into::into));
1123
1124 self
1125 }
1126
1127 #[must_use]
1132 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
1133 self.request.using_index(name, values);
1134
1135 self
1136 }
1137
1138 #[must_use]
1141 pub fn order_asc(mut self, field: &'a str) -> Self {
1142 self.request.append_order(field, SortDirection::Ascending);
1143
1144 self
1145 }
1146
1147 #[must_use]
1150 pub fn order_desc(mut self, field: &'a str) -> Self {
1151 self.request.append_order(field, SortDirection::Descending);
1152
1153 self
1154 }
1155
1156 #[must_use]
1168 pub fn order_by(mut self, fields: &[impl Copy + Into<OrderTerm<'a>>]) -> Self {
1169 self.request.order_by(fields);
1170
1171 self
1172 }
1173
1174 #[must_use]
1176 pub fn descending(mut self) -> Self {
1177 self.request.descending = true;
1178
1179 self
1180 }
1181
1182 #[must_use]
1189 pub fn limit(mut self, rows: usize) -> Self {
1190 self.request.rows = rows;
1191
1192 self
1193 }
1194
1195 #[must_use]
1197 pub fn work_limit(mut self, candidates: usize) -> Self {
1198 self.request.work = candidates;
1199
1200 self
1201 }
1202
1203 #[cfg(feature = "test-support")]
1205 #[doc(hidden)]
1206 #[must_use]
1207 pub fn test_output_limit(mut self, bytes: usize) -> Self {
1208 self.request.bytes = bytes;
1209
1210 self
1211 }
1212
1213 #[must_use]
1216 pub fn after(mut self, cursor: impl Into<Option<&'a QueryCursor>>) -> Self {
1217 self.request.cursor = cursor.into();
1218
1219 self
1220 }
1221
1222 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
1229 observe!(query, { self.entity_page() })
1230 }
1231
1232 fn entity_page(self) -> Result<QueryPage<E>, Error> {
1233 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_rows(E::decode)
1234 }
1235
1236 pub fn first(self) -> Result<Option<E>, Error> {
1242 self.single_with(SingleResult::First, Self::entity_page)
1243 }
1244
1245 pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
1249 self.single_with(SingleResult::First, Self::projected_page::<R>)
1250 }
1251
1252 pub fn try_one(self) -> Result<Option<E>, Error> {
1259 self.single_with(SingleResult::Only, Self::entity_page)
1260 }
1261
1262 pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
1268 self.single_with(SingleResult::Only, Self::projected_page::<R>)
1269 }
1270
1271 fn single_with<R>(
1272 mut self,
1273 probe: SingleResult,
1274 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1275 ) -> Result<Option<R>, Error> {
1276 observe!(query, {
1277 if probe == SingleResult::Only && self.request.cursor.is_some() {
1278 return Err(Error::InvalidQuery);
1279 }
1280 if !(1..=32).contains(&self.request.rows) {
1281 return Err(Error::Limit);
1282 }
1283 self.request.single_result_probe = Some(probe);
1284 fetch(self.limit(match probe {
1285 SingleResult::First => 1,
1286 SingleResult::Only => 2,
1287 }))
1288 })
1289 .map(|mut page| page.rows.pop())
1290 }
1291
1292 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1302 observe!(query, { self.projected_page() })
1303 }
1304
1305 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1306 let raw = fetch_rows(
1307 &*self.db.read()?,
1308 E::SCHEMA,
1309 self.request,
1310 Some(Projection::Record(R::definition())),
1311 )?;
1312
1313 raw.decode_rows(decode_record)
1314 }
1315}
1316
1317#[derive(Clone, Copy)]
1318enum Projection<'a> {
1319 Record(&'a TypeSchema),
1320 Columns(&'a [u8]),
1321}
1322
1323impl Projection<'_> {
1324 fn mask(self, entity: &EntitySchema) -> Result<u32, Error> {
1325 match self {
1326 Self::Record(record) => admit_projection(entity, record),
1327 Self::Columns(columns) => {
1328 let mut mask = 0;
1329 for &column in columns {
1330 if usize::from(column) >= entity.fields.len() || mask & (1 << column) != 0 {
1331 return Err(Error::InvalidQuery);
1332 }
1333 mask |= 1 << column;
1334 }
1335 Ok(mask)
1336 }
1337 }
1338 }
1339}
1340
1341fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u32, Error> {
1345 let TypeBody::Record(fields) = &output.body else {
1346 return Err(Error::InvalidQuery);
1347 };
1348 if fields.is_empty()
1349 || fields.len() > crate::schema::MAX_FIELDS
1350 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1351 {
1352 return Err(Error::InvalidQuery);
1353 }
1354 let mut source = TypeGraph::default();
1355 let mut target = TypeGraph::default();
1356 let mut mask = 0;
1357 for field in *fields {
1358 let position = entity
1359 .field_position(field.name)
1360 .ok_or(Error::InvalidQuery)?;
1361 let stored = &entity.fields[position];
1362 if stored.value != field.value || stored.optional != field.optional {
1363 return Err(Error::InvalidQuery);
1364 }
1365 source
1366 .include(stored.value)
1367 .map_err(|_| Error::InvalidQuery)?;
1368 target
1369 .include(field.value)
1370 .map_err(|_| Error::InvalidQuery)?;
1371 mask |= 1 << position;
1372 }
1373 if !source.contains(&target) {
1374 return Err(Error::InvalidQuery);
1375 }
1376
1377 Ok(mask)
1378}
1379
1380struct Term {
1381 tests_presence: bool,
1382 position: usize,
1383 comparison: Comparison,
1384 operand: TermOperand,
1385 or_next: bool,
1386}
1387
1388enum TermOperand {
1389 Literal {
1390 bytes: Vec<u8>,
1391 absent: bool,
1392 },
1393 Member {
1394 item: FieldType,
1395 needle: MemberNeedle,
1396 },
1397 Nested {
1398 member: crate::member::RecordMember,
1399 literal: Vec<u8>,
1400 absent: bool,
1401 },
1402 Field {
1403 right: usize,
1404 left_member: Option<crate::member::RecordMember>,
1405 right_member: Option<crate::member::RecordMember>,
1406 },
1407 Length {
1408 member: Option<crate::member::RecordMember>,
1409 threshold: u32,
1410 },
1411}
1412
1413enum MemberNeedle {
1414 Literal(Vec<u8>),
1415 Field(usize, Option<crate::member::RecordMember>),
1416}
1417
1418fn admit_literal_size(value: &IndexValue<'_>) -> Result<(), Error> {
1421 let size = match value {
1422 IndexValue::Text(text) => text.len(),
1423 IndexValue::Blob(bytes) => bytes.len(),
1424 _ => return Ok(()),
1425 };
1426 if size > crate::codec::MAX_ROW_BYTES {
1427 return Err(Error::Limit);
1428 }
1429 Ok(())
1430}
1431
1432fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1433 match value {
1434 IndexValue::Text(text) => Some(text.as_bytes()),
1435 IndexValue::Blob(bytes) => Some(bytes),
1436 _ => None,
1437 }
1438}
1439
1440fn consecutive_values(low: IndexValue<'_>, high: IndexValue<'_>) -> bool {
1441 low.discrete_successor()
1442 .is_some_and(|next| equal_values(next, high))
1443}
1444
1445fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1446 match (left, right) {
1448 (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1449 a == b
1450 }
1451 _ => left == right,
1452 }
1453}
1454
1455fn length_limit(field: FieldType) -> Option<u32> {
1456 match key::operand_type(field) {
1457 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1458 FieldType::List { max_items, .. } => Some(max_items),
1459 FieldType::Named(link) => match (link.definition)().body {
1460 TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1461 _ => None,
1462 },
1463 _ => None,
1464 }
1465}
1466
1467fn member_type(field: FieldType) -> Option<FieldType> {
1468 match key::operand_type(field) {
1469 FieldType::List { item, .. } => Some(*item),
1470 FieldType::Named(link) => match (link.definition)().body {
1471 TypeBody::Set { item, .. } => Some(item),
1472 _ => None,
1473 },
1474 _ => None,
1475 }
1476}
1477
1478fn contains_member(
1480 span: &[u8],
1481 optional: bool,
1482 item: FieldType,
1483 needle: IndexValue<'_>,
1484) -> Result<bool, Error> {
1485 let mut reader = Decoder::new(span)?;
1486 if optional && !reader.boolean()? {
1487 return Ok(false);
1488 }
1489 for _ in 0..reader.nat32()? {
1490 let value = IndexValue::read(&mut reader, item)?;
1491 if equal_values(value, needle) {
1492 return Ok(true);
1493 }
1494 }
1495
1496 Ok(false)
1497}
1498
1499pub(super) fn set_bit_positions(mut mask: u32) -> impl Iterator<Item = usize> {
1501 std::iter::from_fn(move || {
1502 if mask == 0 {
1503 return None;
1504 }
1505 let position = mask.trailing_zeros() as usize;
1506 mask &= mask - 1;
1507 Some(position)
1508 })
1509}
1510
1511fn admit_ordered_fields(entity: &EntitySchema, mask: u32) -> Result<(), Error> {
1512 for i in set_bit_positions(mask) {
1513 if !key::supports(entity.fields[i].value) {
1514 return Err(Error::InvalidQuery);
1515 }
1516 }
1517
1518 Ok(())
1519}
1520
1521fn comparison_key(
1523 entity: &EntitySchema,
1524 mask: u32,
1525 values: &[IndexValue<'_>],
1526 scratch: &mut Vec<u8>,
1527) -> Result<(), Error> {
1528 build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1529}
1530
1531fn build_comparison_key<'a>(
1532 entity: &EntitySchema,
1533 mask: u32,
1534 key: &mut Vec<u8>,
1535 mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1536) -> Result<(), Error> {
1537 key.clear();
1538 for i in set_bit_positions(mask) {
1539 let field = &entity.fields[i];
1540 value(i, field)?.append_component(field.optional, key);
1541 if key.len() > MAX_COMPARISON_KEY {
1542 return Err(Error::Limit);
1543 }
1544 }
1545
1546 Ok(())
1547}
1548
1549fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1550 if size > limit {
1551 return Err(Error::RowTooLarge);
1552 }
1553 if size > limit - *used {
1554 return Err(Error::Limit);
1555 }
1556 *used += size;
1557
1558 Ok(())
1559}
1560
1561fn projection_size(spans: &[(u16, u16)], mask: u32) -> usize {
1563 set_bit_positions(mask)
1564 .map(|i| {
1565 let (start, end) = spans[i];
1566 usize::from(end - start)
1567 })
1568 .sum()
1569}
1570
1571fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u32, size: usize) -> Vec<u8> {
1572 let mut output = Vec::with_capacity(size);
1573 for i in set_bit_positions(mask) {
1574 let (start, end) = spans[i];
1575 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1576 }
1577
1578 output
1579}
1580#[derive(Clone, Copy)]
1581enum PlanOutput {
1582 Rows,
1583 Aggregate { grouped: bool },
1584 ImmediateCount,
1585}
1586
1587struct Plan<'a> {
1588 primary: usize,
1589 index: Option<&'a IndexSchema>,
1590 prefix: Vec<u8>,
1591 cursor_prefix_len: usize,
1593 fixed_components: usize,
1594 terms: Vec<Term>,
1595 selected: u32,
1596 span_fields: u32,
1598 binding: [u8; 32],
1599 projection: Option<u32>,
1600 distinct: distinct::Strategy,
1601 sort: Option<Vec<order::SortField>>,
1602 descending: bool,
1603}
1604impl<'a> Plan<'a> {
1605 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1606 self.terms.split_inclusive(|term| !term.or_next)
1607 }
1608
1609 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1610 self.index = Some(path.index);
1611 self.cursor_prefix_len = path.prefix.len();
1612 self.prefix = path.prefix;
1613 self.fixed_components = path.fixed;
1614 self.selected |= entity.key_fields();
1615 }
1616
1617 fn admit(
1618 entity: &'a EntitySchema,
1619 request: &Request<'_>,
1620 schema: [u8; 32],
1621 incarnation: [u8; 16],
1622 projection: Option<Projection<'_>>,
1623 output: PlanOutput,
1624 ) -> Result<Self, Error> {
1625 if !request.within_limits() {
1626 return Err(Error::Limit);
1627 }
1628 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1629 {
1630 return Err(Error::InvalidQuery);
1631 }
1632 for value in request
1634 .predicates
1635 .iter()
1636 .filter_map(|p| match &p.operand {
1637 QueryOperand::Literal(value) => Some(value),
1638 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1639 })
1640 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1641 {
1642 admit_literal_size(value)?;
1643 }
1644 let primary = entity
1645 .field_position(entity.primary_key)
1646 .filter(|&i| !entity.fields[i].optional)
1647 .ok_or(Error::InvalidQuery)?;
1648 let mut plan = Self {
1649 primary,
1650 index: None,
1651 prefix: prefix(2, entity.id, &[]),
1652 cursor_prefix_len: ENTITY_PREFIX_BYTES,
1653 fixed_components: 0,
1654 terms: Vec::new(),
1655 selected: 1 << primary,
1656 span_fields: 0,
1657 binding: [0; 32],
1658 projection: projection.map(|output| output.mask(entity)).transpose()?,
1659 distinct: distinct::Strategy::Identity,
1660 sort: None,
1661 descending: request.descending ^ request.primary_descending(entity),
1662 };
1663 for predicate in &request.predicates {
1664 let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
1665 let field = &entity.fields[position];
1666 let member = if predicate.comparison == Comparison::Contains {
1667 member_type(field.value)
1668 } else {
1669 None
1670 };
1671 let operand = match (predicate.operand, record_member) {
1672 (QueryOperand::Literal(value), Some(member)) => {
1673 if !predicate.comparison.supports_record_member() {
1674 return Err(Error::InvalidQuery);
1675 }
1676 let leaf = member.field();
1677 predicate.comparison.admit(
1678 leaf.value,
1679 field.optional || leaf.optional,
1680 value,
1681 )?;
1682 let literal = value.component(field.optional || leaf.optional);
1683 plan.span_fields |= 1 << position;
1684 TermOperand::Nested {
1685 member,
1686 literal,
1687 absent: value == IndexValue::Absent,
1688 }
1689 }
1690 (QueryOperand::Length(length), member) => {
1691 let selected = member.map_or(field.value, |m| m.field().value);
1692 if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1693 return Err(Error::InvalidQuery);
1694 }
1695 plan.span_fields |= 1 << position;
1696
1697 TermOperand::Length {
1698 member,
1699 threshold: length,
1700 }
1701 }
1702 (QueryOperand::Field(name), left_member) => {
1703 let (right, right_member) = crate::member::resolve_field(entity, name)?;
1704 if (left_member.is_some() || right_member.is_some())
1705 && member.is_none()
1706 && !predicate.comparison.supports_record_member()
1707 {
1708 return Err(Error::InvalidQuery);
1709 }
1710 let right_type =
1711 right_member.map_or(entity.fields[right].value, |m| m.field().value);
1712 let left_type =
1713 left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1714 let compatible = left_type == right_type
1715 || matches!(
1716 (left_type, right_type),
1717 (FieldType::Text { .. }, FieldType::Text { .. })
1718 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1719 );
1720 if !compatible
1721 || !key::supports(left_type)
1722 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1723 {
1724 return Err(Error::InvalidQuery);
1725 }
1726 if right_member.is_some() {
1727 plan.span_fields |= 1 << right;
1728 } else {
1729 plan.selected |= 1 << right;
1730 }
1731
1732 if let Some(item) = member {
1733 plan.span_fields |= 1 << position;
1734
1735 TermOperand::Member {
1736 item,
1737 needle: MemberNeedle::Field(right, right_member),
1738 }
1739 } else {
1740 if left_member.is_some() {
1741 plan.span_fields |= 1 << position;
1742 } else {
1743 plan.selected |= 1 << position;
1744 }
1745 TermOperand::Field {
1746 right,
1747 left_member,
1748 right_member,
1749 }
1750 }
1751 }
1752 (QueryOperand::Literal(value), None) => {
1753 if let Some(item) = member {
1754 if !key::supports(item) {
1755 return Err(Error::InvalidQuery);
1756 }
1757 value.admit(item, false)?;
1758 let bytes = value.component(false);
1759 plan.span_fields |= 1 << position;
1760
1761 TermOperand::Member {
1762 item,
1763 needle: MemberNeedle::Literal(bytes),
1764 }
1765 } else {
1766 let absent = value == IndexValue::Absent;
1767 if key::supports(field.value) {
1768 plan.selected |= 1 << position;
1769 } else if absent
1770 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1771 {
1772 plan.span_fields |= 1 << position;
1773 } else {
1774 return Err(Error::InvalidQuery);
1775 }
1776 predicate
1777 .comparison
1778 .admit(field.value, field.optional, value)?;
1779 let bytes = value.component(field.optional);
1780
1781 TermOperand::Literal { bytes, absent }
1782 }
1783 }
1784 };
1785 plan.terms.push(Term {
1786 tests_presence: predicate.tests_presence(entity, &operand),
1787 position,
1788 comparison: predicate.comparison,
1789 operand,
1790 or_next: predicate.or_next,
1791 });
1792 }
1793 match order::select(entity, request, output)? {
1796 order::Path::Primary => {}
1797 order::Path::Index(path, descending) => {
1798 plan.use_index(entity, path);
1799 plan.descending = request.descending ^ descending;
1800 }
1801 order::Path::Filtered { sort } => {
1802 order::select_filtered_path(entity, request, &mut plan, None)?;
1803 for field in sort.iter().flatten() {
1804 if field.member.is_some() {
1805 plan.span_fields |= 1 << field.position;
1806 } else {
1807 plan.selected |= 1 << field.position;
1808 }
1809 }
1810 plan.sort = sort;
1811 }
1812 }
1813 if request.distinct {
1814 plan.distinct = distinct::admit(entity, request, &plan)?;
1815 match plan.distinct {
1816 distinct::Strategy::FirstMatch => plan.sort = None,
1817 distinct::Strategy::Complete { key_fields } => plan.selected |= key_fields,
1818 _ => {}
1819 }
1820 }
1821 if request.index.is_some()
1824 && !request.predicates.is_empty()
1825 && let Some(index) = plan.index
1826 {
1827 for field in &index.fields[plan.fixed_components..] {
1828 let Some(value) = order::equality(entity, request, field) else {
1829 break;
1830 };
1831 let schema = entity.index_field(field).ok_or(Error::InvalidSchema)?;
1832 let len = plan.prefix.len();
1833 value.append_component(schema.optional, &mut plan.prefix);
1834 if plan.prefix.len() > crate::MAX_INDEX_KEY_BYTES {
1835 plan.prefix.truncate(len);
1836 break;
1837 }
1838 plan.fixed_components += 1;
1839 }
1840 }
1841 if matches!(output, PlanOutput::ImmediateCount)
1843 || (request.single_result_probe.is_some() && request.cursor.is_none())
1844 {
1845 return Ok(plan);
1846 }
1847 plan.bind_cursor(entity, request, schema, incarnation, projection)?;
1848
1849 Ok(plan)
1850 }
1851}
1852
1853fn consume_index_component(
1855 entity: &EntitySchema,
1856 index: &IndexSchema,
1857 name: &str,
1858 remaining: &mut &[u8],
1859) -> Result<(), Error> {
1860 let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
1861
1862 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
1863}
1864
1865#[inline(never)]
1868#[expect(
1869 clippy::needless_pass_by_value,
1870 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1871)]
1872fn fetch_rows<M: Memory>(
1873 db: &Database<M>,
1874 entity: &EntitySchema,
1875 request: Request<'_>,
1876 projection: Option<Projection<'_>>,
1877) -> Result<QueryPage<Vec<u8>>, Error> {
1878 db.schema.admits(entity)?;
1879 let plan = Plan::admit(
1880 entity,
1881 &request,
1882 db.schema.fingerprint(),
1883 db.incarnation,
1884 projection,
1885 PlanOutput::Rows,
1886 )?;
1887
1888 execute(&db.map, entity, &request, &plan, None)
1889}
1890
1891fn execute<M: Memory>(
1892 map: &Map<M>,
1893 entity: &EntitySchema,
1894 request: &Request<'_>,
1895 plan: &Plan<'_>,
1896 mut aggregate: Option<aggregate::Accumulator<'_>>,
1897) -> Result<QueryPage<Vec<u8>>, Error> {
1898 execute_inner(
1899 map,
1900 entity,
1901 request,
1902 plan,
1903 range::bounds(entity, request, plan)?,
1904 aggregate.as_mut(),
1905 None,
1906 )
1907}
1908
1909const STEP_INPUT_BYTES: usize = 64 * 1024;
1912const fn candidate_byte_limit(row_bytes: usize) -> usize {
1913 row_bytes + 2 * crate::MAX_INDEX_KEY_BYTES
1914}
1915
1916fn execute_inner<M: Memory>(
1917 map: &Map<M>,
1918 entity: &EntitySchema,
1919 request: &Request<'_>,
1920 plan: &Plan<'_>,
1921 bounds: Option<range::Bounds>,
1922 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1923 mut input_bytes: Option<&mut usize>,
1924) -> Result<QueryPage<Vec<u8>>, Error> {
1925 let mut page = QueryPage {
1926 rows: Vec::new(),
1927 next: None,
1928 examined: 0,
1929 fetched: 0,
1930 output_bytes: 0,
1931 };
1932 let Some(bounds) = bounds else {
1933 return Ok(page);
1934 };
1935 let terminal = range::terminal_key(&bounds, plan.descending);
1936 let mut next_entry = range::entries(map, &bounds, plan.descending);
1937 let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
1938 Some(distinct::Collection::new(
1939 plan.projection.ok_or(Error::InvalidQuery)?,
1940 key_fields,
1941 ))
1942 } else {
1943 None
1944 };
1945 let mut sorted = plan
1946 .sort
1947 .as_ref()
1948 .map(|_| sort::Collection::new(request, plan.distinct));
1949 let mut component = Vec::new();
1950 let mut right_component = Vec::new();
1951 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
1953 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1954 } else {
1955 None
1956 };
1957 let candidate_bytes = candidate_byte_limit(entity.max_row_bytes);
1958 let primary_type = entity.fields[plan.primary].value;
1959 let needs_spans = plan.index.is_some()
1960 || plan.span_fields != 0
1961 || match &aggregate {
1962 Some(accumulator) => accumulator.needs_spans(),
1963 None => plan.projection.is_some(),
1964 };
1965 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1967 let mut index_info = None;
1968 while let Some((stored_key, stored_value)) = next_entry() {
1969 if page.examined == request.work {
1972 return Err(Error::Limit);
1973 }
1974 page.examined += 1;
1975 let mut read_bytes = stored_key.len();
1976 let (owner, bytes) = if plan.index.is_some() {
1977 read_bytes += stored_value.len();
1978 read_index_owner(map, entity.id, primary_type, &stored_value)?
1979 } else {
1980 (
1981 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
1982 stored_value,
1983 )
1984 };
1985 if let Some(used) = input_bytes.as_deref_mut() {
1986 read_bytes += bytes.len();
1987 if read_bytes > candidate_bytes {
1988 return Err(Error::Corrupt);
1989 }
1990 *used += read_bytes;
1991 }
1992 page.fetched += 1;
1993 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
1994 entity.inspect_fields(
1995 &bytes,
1996 plan.selected,
1997 &mut values,
1998 needs_spans.then_some(&mut spans),
1999 )?;
2000 let row_key = RowKey::from_index(values[plan.primary])?;
2001 if plan.index.is_some() {
2002 let info = index_info.get_or_insert_with(|| crate::__private::RowInfo::new(row_key));
2003 info.key = row_key;
2004 entity.fill_index_info(&values, &bytes, &spans, info)?;
2005 validate_index_entry(entity, info, owner, &stored_key)?;
2006 } else if row_key != owner {
2007 return Err(Error::Corrupt);
2008 }
2009 let matches = predicate::PredicateRow {
2010 entity,
2011 bytes: &bytes,
2012 values: &values,
2013 spans: &spans,
2014 span_fields: plan.span_fields,
2015 }
2016 .matches(
2017 &plan.terms,
2018 &request.predicates,
2019 &mut component,
2020 &mut right_component,
2021 )?;
2022 let boundary = distinct::boundary(entity, plan.index, plan.distinct, &stored_key)?;
2023 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2024 if matches && let Some(accumulator) = aggregate.as_mut() {
2025 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2026 if matches!(accumulator, aggregate::Accumulator::Until(remaining) if **remaining == 0) {
2027 return Ok(page);
2029 }
2030 } else if matches && let Some(collection) = collected.as_mut() {
2031 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2032 if request.single_result_probe == Some(SingleResult::First) {
2034 break;
2035 }
2036 } else if matches && let Some(collection) = sorted.as_mut() {
2037 collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2038 request.check_result_count(collection.result_count())?;
2040 } else if matches && !duplicate {
2041 request.check_result_count(page.rows.len() + 1)?;
2042 let size = plan
2043 .projection
2044 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2045 if size > request.bytes {
2046 return Err(Error::RowTooLarge);
2047 }
2048 if size > request.bytes - page.output_bytes {
2049 page.next = Some(plan.cursor(&stored_key, Resume::Retry));
2050
2051 return Ok(page);
2052 }
2053 page.output_bytes += size;
2054 if let Some(mask) = plan.projection {
2055 page.rows.push(copy_projection(&bytes, &spans, mask, size));
2056 } else {
2057 page.rows.push(bytes);
2058 }
2059 if request.single_result_probe == Some(SingleResult::First)
2060 || plan.distinct.finishes_on_match(plan.fixed_components)
2061 {
2062 return Ok(page);
2063 }
2064 if let Some(boundary) = boundary {
2065 previous = Some(boundary.to_vec());
2066 }
2067 }
2068 if page.rows.len() == request.rows
2069 || page.examined == request.work
2070 || input_bytes
2071 .as_deref()
2072 .is_some_and(|used| *used > STEP_INPUT_BYTES - candidate_bytes)
2073 {
2074 if terminal == Some(&stored_key) {
2075 break;
2076 }
2077 if request.single_result_probe.is_some()
2078 || (aggregate.is_some() && input_bytes.is_none())
2079 || collected.is_some()
2080 || sorted.is_some()
2081 {
2082 continue;
2085 }
2086 if input_bytes.is_some() && next_entry().is_none() {
2090 break;
2091 }
2092 let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
2093 Resume::AfterUnemittedClass
2094 } else {
2095 Resume::After
2096 };
2097 page.next = Some(plan.cursor(&stored_key, resume));
2098
2099 return Ok(page);
2100 }
2101 }
2102 if let Some(collection) = collected {
2103 page.output_bytes = collection.output_bytes;
2104 page.rows = collection.rows;
2105 }
2106 if let Some(collection) = sorted {
2107 collection.finish(request.bytes, &mut page)?;
2108 }
2109
2110 Ok(page)
2111}