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