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, Debug, PartialEq, Eq)]
61#[repr(u8)]
62pub enum Comparison {
63 Eq = 0,
65 Ne = 1,
67 Lt = 2,
69 Le = 3,
71 Gt = 4,
73 Ge = 5,
75 StartsWith = 6,
79 EndsWith = 7,
82 Contains = 8,
86}
87
88impl Comparison {
89 fn supports_record_member(self) -> bool {
90 self.is_relational() || matches!(self, Self::StartsWith | Self::EndsWith)
91 }
92
93 fn is_relational(self) -> bool {
94 matches!(
95 self,
96 Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge
97 )
98 }
99
100 fn supports_scalar(self, field: FieldType) -> bool {
101 self.is_relational()
102 || matches!(
103 key::operand_type(field),
104 FieldType::Text { .. } | FieldType::Blob { .. }
105 )
106 }
107
108 fn admit(self, field: FieldType, optional: bool, value: IndexValue<'_>) -> Result<(), Error> {
109 value.admit(field, optional)?;
110 if !self.supports_scalar(field) {
111 return Err(Error::InvalidQuery);
112 }
113 if value == IndexValue::Absent && !matches!(self, Self::Eq | Self::Ne) {
114 return Err(Error::InvalidOperand);
115 }
116
117 Ok(())
118 }
119
120 fn accepts(self, actual: Option<&[u8]>, operand: Option<&[u8]>, optional: bool) -> bool {
121 if actual.is_none() {
122 return self.accepts_absent(operand.is_none());
123 }
124
125 match self {
126 Self::Eq => actual == operand,
127 Self::Ne => actual != operand,
128 Self::StartsWith | Self::EndsWith | Self::Contains => {
129 fn content(key: &[u8], optional: bool) -> Option<&[u8]> {
132 crate::key::bytes_prefix(key.get(usize::from(optional)..)?)
133 }
134
135 actual
136 .and_then(|key| content(key, optional))
137 .zip(operand.and_then(|key| content(key, optional)))
138 .is_some_and(|(actual, operand)| match self {
139 Self::StartsWith => actual.starts_with(operand),
142 Self::EndsWith => actual
146 .strip_suffix(operand)
147 .is_some_and(|prefix| prefix.last() != Some(&0)),
148 _ => contains_component(actual, operand),
149 })
150 }
151 _ if actual.is_none() || operand.is_none() => false,
152 Self::Lt => actual < operand,
153 Self::Le => actual <= operand,
154 Self::Gt => actual > operand,
155 Self::Ge => actual >= operand,
156 }
157 }
158
159 fn accepts_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
161 match self {
162 Self::Eq => Some(equal_values(left, right)),
163 Self::Ne => Some(!equal_values(left, right)),
164 _ => Some(self.accepts_bytes(scalar_bytes(left)?, scalar_bytes(right)?)),
165 }
166 }
167
168 fn accepts_fixed_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
170 if left == IndexValue::Absent || right == IndexValue::Absent {
171 return Some(self.accepts_absent(left == right));
172 }
173 if let Some(result) = self.accepts_values(left, right) {
174 return Some(result);
175 }
176 match self {
177 Comparison::Lt | Comparison::Le | Comparison::Gt | Comparison::Ge => {
178 let mut encoded = Vec::new();
180 left.append_component(false, &mut encoded);
181 let split = encoded.len();
182 right.append_component(false, &mut encoded);
183 let (left, right) = encoded.split_at(split);
184
185 Some(self.accepts(Some(left), Some(right), false))
186 }
187 _ => None,
188 }
189 }
190
191 fn accepts_bytes(self, actual: &[u8], operand: &[u8]) -> bool {
193 match self {
194 Self::StartsWith => actual.starts_with(operand),
195 Self::EndsWith => actual.ends_with(operand),
196 Self::Contains => memchr::memmem::find(actual, operand).is_some(),
197 _ => self.accepts(Some(actual), Some(operand), false),
198 }
199 }
200
201 fn accepts_length(self, actual: Option<u32>, threshold: u32) -> bool {
202 let encoded = actual.map(u32::to_be_bytes);
203
204 self.accepts(
205 encoded.as_ref().map(|v| v.as_slice()),
206 Some(&threshold.to_be_bytes()),
207 false,
208 )
209 }
210
211 fn empty_length_value(self, threshold: u32, field: FieldType) -> Option<IndexValue<'static>> {
213 if !matches!((self, threshold), (Self::Eq | Self::Le, 0) | (Self::Lt, 1)) {
214 return None;
215 }
216 match key::operand_type(field) {
217 FieldType::Text { .. } => Some(IndexValue::Text("")),
218 FieldType::Blob { .. } => Some(IndexValue::Blob(&[])),
219 _ => None,
220 }
221 }
222
223 fn uniform_length_result(self, min: u32, max: u32, n: u32) -> Option<bool> {
225 match self {
226 Self::Eq | Self::Ne if min == max || n < min || n > max => {
227 Some(self.accepts_length(Some(min), n))
228 }
229 Self::Lt | Self::Ge if max < n || min >= n => Some(self.accepts_length(Some(min), n)),
230 Self::Le | Self::Gt if max <= n || min > n => Some(self.accepts_length(Some(min), n)),
231 _ => None,
232 }
233 }
234
235 fn accepts_absent(self, other_absent: bool) -> bool {
238 match self {
239 Self::Eq => other_absent,
240 Self::Ne => !other_absent,
241 _ => false,
242 }
243 }
244}
245
246fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
248 let Some(start) = memchr::memmem::find(actual, needle) else {
249 return false;
250 };
251 if start == 0 || actual[start - 1] != 0 {
252 return true;
253 }
254 fn raw(content: &[u8]) -> Vec<u8> {
258 let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
259 let mut encoded = content.iter();
260 while let Some(&byte) = encoded.next() {
261 bytes.push(byte);
262 if byte == 0 {
263 encoded.next();
264 }
265 }
266
267 bytes
268 }
269
270 memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
271}
272
273#[derive(Debug)]
276pub struct QueryPage<T> {
277 pub rows: Vec<T>,
279 pub next: Option<QueryCursor>,
281 pub examined: usize,
283 pub fetched: usize,
285 pub output_bytes: usize,
287}
288
289impl QueryPage<Vec<u8>> {
290 #[inline(never)]
291 pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
292 Ok(QueryPage {
293 rows: self
294 .rows
295 .iter()
296 .map(|bytes| E::decode(bytes))
297 .collect::<Result<_, _>>()?,
298 next: self.next,
299 examined: self.examined,
300 fetched: self.fetched,
301 output_bytes: self.output_bytes,
302 })
303 }
304
305 #[inline(never)]
306 fn decode_with<R>(
307 self,
308 decode: impl Fn(&mut Decoder<'_>) -> Result<R, Error>,
309 ) -> Result<QueryPage<R>, Error> {
310 Ok(QueryPage {
311 rows: self
312 .rows
313 .iter()
314 .map(|bytes| {
315 let mut reader = Decoder::new(bytes)?;
316 let row = decode(&mut reader)?;
318 reader.finish()?;
319
320 Ok(row)
321 })
322 .collect::<Result<_, Error>>()?,
323 next: self.next,
324 examined: self.examined,
325 fetched: self.fetched,
326 output_bytes: self.output_bytes,
327 })
328 }
329}
330
331#[derive(Clone, Copy, Debug, PartialEq, Eq)]
333pub enum QueryOperand<'a> {
334 Literal(IndexValue<'a>),
336 Length(u32),
338 Field(&'a str),
340}
341
342struct Predicate<'a> {
343 field: &'a str,
344 comparison: Comparison,
345 operand: QueryOperand<'a>,
346 or_next: bool,
348}
349
350impl<'a> Predicate<'a> {
351 fn compared_field(&self, name: &str) -> Option<&'a str> {
353 let QueryOperand::Field(right) = self.operand else {
354 return None;
355 };
356 if self.field == name {
357 Some(right)
358 } else if right == name {
359 Some(self.field)
360 } else {
361 None
362 }
363 }
364
365 fn at_extreme(&self, entity: &EntitySchema, value: IndexValue<'_>, upper: bool) -> bool {
367 use crate::{Date, Duration, Timestamp, Ulid};
368
369 match value {
370 IndexValue::Bool(b) => b == upper,
371 IndexValue::Date(d) => d == if upper { Date::MAX } else { Date::MIN },
372 IndexValue::Timestamp(t) => {
373 t == if upper {
374 Timestamp::MAX
375 } else {
376 Timestamp::MIN
377 }
378 }
379 IndexValue::Duration(d) => d == if upper { Duration::MAX } else { Duration::MIN },
380 IndexValue::Ulid(id) => id == if upper { Ulid::MAX } else { Ulid::MIN },
381 IndexValue::UnitEnum { ordinal, .. } => entity
382 .index_field(self.field)
383 .is_some_and(|field| key::is_fixed_extreme(field.value, &[ordinal], upper)),
384 IndexValue::Text("") | IndexValue::Blob([]) => !upper,
385 _ => value.is_integer_extreme(upper),
386 }
387 }
388
389 fn fixed_equality(&self, entity: &EntitySchema) -> Option<(&'a str, IndexValue<'a>)> {
391 if let QueryOperand::Length(n) = self.operand {
392 let empty = self
393 .comparison
394 .empty_length_value(n, entity.index_field(self.field)?.value)?;
395 return Some((self.field, empty));
396 }
397 let QueryOperand::Literal(value) = self.operand else {
398 return None;
399 };
400 let fixed = match (self.comparison, value) {
402 (Comparison::Eq, _) => value,
403 (Comparison::Ne, IndexValue::Bool(excluded))
404 if entity.field_is_required(self.field) =>
405 {
406 IndexValue::Bool(!excluded)
407 }
408 (cmp @ (Comparison::Ge | Comparison::Le), _)
409 if self.at_extreme(entity, value, cmp == Comparison::Ge) =>
410 {
411 value
412 }
413 (Comparison::Gt, IndexValue::Bool(false)) => IndexValue::Bool(true),
414 (Comparison::Lt, IndexValue::Bool(true)) => IndexValue::Bool(false),
415 _ => return None,
416 };
417 Some((self.field, fixed))
418 }
419
420 fn tests_presence(&self, entity: &EntitySchema, operand: &TermOperand) -> bool {
422 match (self.comparison, self.operand) {
423 (Comparison::Ne, QueryOperand::Literal(IndexValue::Absent)) => true,
424 (cmp @ (Comparison::Le | Comparison::Ge), QueryOperand::Literal(value)) => {
425 self.at_extreme(entity, value, cmp == Comparison::Le)
426 }
427 (_, QueryOperand::Length(_)) => {
428 self.present_length_result(entity) == Some(true)
429 && self.comparison != Comparison::Ne
430 }
431 (
432 Comparison::Le
433 | Comparison::Ge
434 | Comparison::StartsWith
435 | Comparison::EndsWith
436 | Comparison::Contains,
437 QueryOperand::Field(right),
438 ) => right == self.field,
439 (
440 Comparison::StartsWith | Comparison::EndsWith | Comparison::Contains,
441 QueryOperand::Literal(needle),
442 ) => {
443 !matches!(operand, TermOperand::Member { .. })
445 && scalar_bytes(needle).is_some_and(<[u8]>::is_empty)
446 }
447 _ => false,
448 }
449 }
450
451 fn present_length_result(&self, entity: &EntitySchema) -> Option<bool> {
453 let QueryOperand::Length(n) = self.operand else {
454 return None;
455 };
456 let max = length_limit(entity.index_field(self.field)?.value)?;
457 self.comparison.uniform_length_result(0, max, n)
458 }
459
460 fn constant_comparison(&self, entity: &EntitySchema) -> Option<bool> {
461 if let QueryOperand::Literal(value) = self.operand {
462 return match (self.comparison, value) {
464 (cmp @ (Comparison::Lt | Comparison::Gt), value)
465 if self.at_extreme(entity, value, cmp == Comparison::Gt) =>
466 {
467 Some(false)
468 }
469 _ => None,
470 };
471 }
472 if matches!(self.operand, QueryOperand::Length(_)) {
473 let result = self.present_length_result(entity)?;
474 return (result == self.comparison.accepts_absent(false)
475 || entity.field_is_required(self.field))
476 .then_some(result);
477 }
478 if !matches!(self.operand, QueryOperand::Field(right) if right == self.field) {
479 return None;
480 }
481 match self.comparison {
482 Comparison::Eq => Some(true),
483 Comparison::Ne | Comparison::Lt | Comparison::Gt => Some(false),
484 _ => None,
485 }
486 }
487}
488
489#[derive(Clone, Copy, PartialEq, Eq)]
490enum SingleResult {
491 First,
492 Only,
493}
494
495struct Request<'a> {
496 groups: aggregate::GroupRequest<'a>,
497 predicates: Vec<Predicate<'a>>,
498 index: Option<(&'a str, Vec<IndexValue<'a>>)>,
499 order: Option<Vec<&'a str>>,
500 order_descending: u8,
501 descending: bool,
502 distinct: bool,
503 single_result_probe: Option<SingleResult>,
504 rows: usize,
505 work: usize,
506 bytes: usize,
507 cursor: Option<&'a QueryCursor>,
508 over_limit: bool,
509}
510
511impl Default for Request<'_> {
512 fn default() -> Self {
513 Self {
514 groups: aggregate::GroupRequest::default(),
515 predicates: Vec::new(),
516 index: None,
517 order: None,
518 order_descending: 0,
519 descending: false,
520 distinct: false,
521 single_result_probe: None,
522 rows: 32,
523 work: 128,
524 bytes: MAX_OUTPUT,
525 cursor: None,
526 over_limit: false,
527 }
528 }
529}
530
531impl<'a> Request<'a> {
534 fn within_limits(&self) -> bool {
535 !self.over_limit
536 && (1..=32).contains(&self.rows)
537 && (1..=MAX_WORK).contains(&self.work)
538 && (1..=MAX_OUTPUT).contains(&self.bytes)
539 }
540
541 fn check_result_count(&self, count: usize) -> Result<(), Error> {
544 if self.single_result_probe == Some(SingleResult::Only) && count > 1 {
545 return Err(Error::MultipleMatches);
546 }
547 Ok(())
548 }
549
550 fn fixed_equalities<'r>(
552 &'r self,
553 entity: &'r EntitySchema,
554 ) -> impl Iterator<Item = (&'a str, IndexValue<'a>)> + 'r {
555 self.clauses().filter_map(move |clause| {
556 let (predicate, rest) = clause.split_first()?;
557 if !rest.is_empty() {
558 let mut candidate = predicate.fixed_equality(entity)?;
559 for alternative in rest {
560 let other = alternative.fixed_equality(entity)?;
561 if candidate.0 != other.0 {
562 return None;
563 }
564 if equal_values(candidate.1, other.1) {
565 continue;
566 }
567 if self.predicates.len() == clause.len() {
568 return None;
569 }
570 if self.excludes_literal(other.0, other.1) {
571 continue;
572 }
573 if !self.excludes_literal(candidate.0, candidate.1) {
574 return None;
575 }
576 candidate = other;
577 }
578 return Some(candidate);
581 }
582 if let Some(equality) = predicate.fixed_equality(entity) {
583 return Some(equality);
584 }
585 let QueryOperand::Literal(value) = predicate.operand else {
588 return None;
589 };
590 let lower = match predicate.comparison {
591 Comparison::Ge => value,
592 Comparison::Gt if self.predicates.len() > 1 => value.discrete_successor()?,
593 _ => return None,
594 };
595 self.clauses()
596 .any(|clause| {
597 let [upper] = clause else { return false };
598 if upper.field != predicate.field {
599 return false;
600 }
601 match (upper.comparison, upper.operand) {
602 (Comparison::Le, QueryOperand::Literal(value)) => {
603 equal_values(lower, value)
604 }
605 (Comparison::Lt, QueryOperand::Literal(value)) => {
606 consecutive_values(lower, value)
607 }
608 _ => false,
609 }
610 })
611 .then_some((predicate.field, lower))
612 })
613 }
614
615 fn excludes_literal(&self, field: &str, value: IndexValue<'_>) -> bool {
616 self.clauses().any(|clause| {
619 clause.iter().all(|predicate| {
620 if predicate.field != field {
621 return false;
622 }
623 let QueryOperand::Literal(literal) = predicate.operand else {
624 return false;
625 };
626 match predicate.comparison {
627 Comparison::Eq
628 | Comparison::Ne
629 | Comparison::Lt
630 | Comparison::Le
631 | Comparison::Gt
632 | Comparison::Ge => {
633 predicate.comparison.accepts_fixed_values(value, literal) == Some(false)
634 }
635 _ => false,
636 }
637 })
638 })
639 }
640
641 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
642 self.predicates.split_inclusive(|p| !p.or_next)
643 }
644
645 #[inline(never)]
646 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
647 if self.predicates.len() == MAX_TERMS {
648 self.over_limit = true;
649 } else {
650 self.predicates.push(Predicate {
651 field,
652 comparison,
653 operand,
654 or_next: false,
655 });
656 }
657 }
658
659 #[inline(never)]
660 fn or_clause(
661 &mut self,
662 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
663 ) {
664 let count = alternatives.len();
665
666 if count == 0 || count > MAX_TERMS - self.predicates.len() {
667 self.over_limit = true;
668 } else {
669 self.predicates.extend(alternatives.enumerate().map(
670 |(i, (field, comparison, operand))| Predicate {
671 field,
672 comparison,
673 operand,
674 or_next: i + 1 < count,
675 },
676 ));
677 }
678 }
679
680 #[inline(never)]
681 fn filter_not_in(
682 &mut self,
683 field: &'a str,
684 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
685 ) {
686 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
687 self.over_limit = true;
688
689 return;
690 }
691 for value in values {
692 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
693 }
694 }
695
696 #[inline(never)]
697 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
698 if values.len() > 4 {
699 self.over_limit = true;
700 } else {
701 self.index = Some((name, values.to_vec()));
702 }
703 }
704
705 #[inline(never)]
706 fn order_by(&mut self, fields: &[&'a str]) {
707 self.order_descending = 0;
708
709 if fields.len() > 4 {
710 self.over_limit = true;
711 } else {
712 self.order = Some(fields.to_vec());
713 }
714 }
715
716 #[inline(never)]
717 fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
718 if fields.len() > 4 {
719 self.over_limit = true;
720
721 return;
722 }
723 self.order = Some(Vec::with_capacity(fields.len()));
724 self.order_descending = 0;
725 for &(field, direction) in fields {
726 self.append_order(field, direction);
727 }
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 if direction == SortDirection::Descending {
738 self.order_descending |= 1 << fields.len();
739 }
740 fields.push(field);
741 }
742
743 fn primary_descending(&self, entity: &EntitySchema) -> bool {
744 self.order_descending != 0
745 && self.order.as_ref().is_some_and(|fields| {
746 fields.last() == Some(&entity.primary_key)
747 && self.order_descending & (1 << (fields.len() - 1)) != 0
748 })
749 }
750}
751
752pub(super) fn source_page<M: Memory>(
754 map: &Map<M>,
755 entity: &EntitySchema,
756 binding: [u8; 32],
757 incarnation: [u8; 16],
758 cursor: Option<&QueryCursor>,
759 rows: usize,
760 bytes: usize,
761) -> Result<QueryPage<Vec<u8>>, Error> {
762 let request = Request {
763 rows,
764 work: rows,
765 bytes,
766 cursor,
767 ..Request::default()
768 };
769 let plan = Plan::admit(
770 entity,
771 &request,
772 binding,
773 incarnation,
774 None,
775 PlanOutput::Rows,
776 )?;
777
778 execute(map, entity, &request, &plan, None)
779}
780
781enum QuerySource<'a, M: Memory> {
782 Direct(&'a Database<M>),
783 Session(Rc<RefCell<Database<M>>>),
784}
785
786enum QueryRead<'a, M: Memory> {
787 Direct(&'a Database<M>),
788 Session(Ref<'a, Database<M>>),
789}
790
791impl<M: Memory> Deref for QueryRead<'_, M> {
792 type Target = Database<M>;
793
794 fn deref(&self) -> &Self::Target {
795 match self {
796 Self::Direct(db) => db,
797 Self::Session(db) => db,
798 }
799 }
800}
801
802impl<M: Memory> QuerySource<'_, M> {
803 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
804 match self {
805 Self::Direct(db) => Ok(QueryRead::Direct(db)),
806 Self::Session(db) => db
807 .try_borrow()
808 .map(QueryRead::Session)
809 .map_err(|_| Error::BorrowConflict),
810 }
811 }
812}
813
814pub struct Query<'a, E, M: Memory> {
818 db: QuerySource<'a, M>,
819 request: Request<'a>,
820 entity: PhantomData<E>,
821}
822impl<M: Memory> Database<M> {
823 #[must_use]
825 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
826 Query {
827 db: QuerySource::Direct(self),
828 entity: PhantomData,
829 request: Request::default(),
830 }
831 }
832}
833impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
834 pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
835 Self {
836 db: QuerySource::Session(db),
837 request: Request::default(),
838 entity: PhantomData,
839 }
840 }
841
842 #[must_use]
856 pub fn distinct(mut self) -> Self {
857 self.request.distinct = true;
858
859 self
860 }
861
862 #[must_use]
875 pub fn filter(
876 mut self,
877 field: &'a str,
878 comparison: Comparison,
879 value: impl Into<IndexValue<'a>>,
880 ) -> Self {
881 self.request
882 .filter(field, comparison, QueryOperand::Literal(value.into()));
883
884 self
885 }
886
887 #[must_use]
889 pub fn by_id(self, id: impl Into<crate::Id<E>>) -> Self {
890 self.eq(
891 E::SCHEMA.primary_key,
892 id.into().key().into_row_key().index_value(),
893 )
894 }
895
896 #[must_use]
898 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
899 self.filter(field, Comparison::Eq, value)
900 }
901
902 #[must_use]
905 pub fn eq_if_some(self, field: &'a str, value: Option<impl Into<IndexValue<'a>>>) -> Self {
906 match value {
907 Some(value) => self.eq(field, value),
908 None => self,
909 }
910 }
911
912 #[must_use]
914 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
915 self.filter(field, Comparison::Ne, value)
916 }
917
918 #[must_use]
920 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
921 self.filter(field, Comparison::Lt, value)
922 }
923
924 #[must_use]
926 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
927 self.filter(field, Comparison::Le, value)
928 }
929
930 #[must_use]
932 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
933 self.filter(field, Comparison::Gt, value)
934 }
935
936 #[must_use]
938 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
939 self.filter(field, Comparison::Ge, value)
940 }
941
942 #[must_use]
950 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
951 self.request
952 .filter(left, comparison, QueryOperand::Field(right));
953
954 self
955 }
956
957 #[must_use]
962 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
963 self.request
964 .filter(field, comparison, QueryOperand::Length(length));
965
966 self
967 }
968
969 #[must_use]
972 pub fn filter_present(self, field: &'a str) -> Self {
973 self.filter(field, Comparison::Ne, IndexValue::Absent)
974 }
975
976 #[must_use]
979 pub fn filter_absent(self, field: &'a str) -> Self {
980 self.filter(field, Comparison::Eq, IndexValue::Absent)
981 }
982
983 #[must_use]
987 pub fn filter_range<T: Into<IndexValue<'a>>>(
988 self,
989 field: &'a str,
990 range: std::ops::Range<T>,
991 ) -> Self {
992 self.gte(field, range.start).lt(field, range.end)
993 }
994
995 #[must_use]
999 pub fn filter_ulid_time(
1000 self,
1001 field: &'a str,
1002 range: std::ops::Range<crate::Timestamp>,
1003 ) -> Self {
1004 let (first, last) =
1005 crate::Ulid::time_bounds(range).unwrap_or((crate::Ulid::MAX, crate::Ulid::MIN));
1006 self.filter_between(field, first, last)
1007 }
1008
1009 #[must_use]
1016 pub fn filter_between(
1017 self,
1018 field: &'a str,
1019 lower: impl Into<IndexValue<'a>>,
1020 upper: impl Into<IndexValue<'a>>,
1021 ) -> Self {
1022 self.filter(field, Comparison::Ge, lower)
1023 .filter(field, Comparison::Le, upper)
1024 }
1025
1026 #[must_use]
1034 pub fn filter_not_between(
1035 self,
1036 field: &'a str,
1037 lower: impl Into<IndexValue<'a>>,
1038 upper: impl Into<IndexValue<'a>>,
1039 ) -> Self {
1040 self.filter_any(&[
1041 (field, Comparison::Lt, lower.into()),
1042 (field, Comparison::Gt, upper.into()),
1043 ])
1044 }
1045
1046 #[must_use]
1051 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1052 self.filter_fields(field, Comparison::Ge, lower)
1053 .filter_fields(field, Comparison::Le, upper)
1054 }
1055
1056 #[must_use]
1061 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1062 self.filter_any_operands(&[
1063 (field, Comparison::Lt, QueryOperand::Field(lower)),
1064 (field, Comparison::Gt, QueryOperand::Field(upper)),
1065 ])
1066 }
1067
1068 #[must_use]
1076 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
1077 self.request.or_clause(
1078 alternatives
1079 .iter()
1080 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
1081 );
1082
1083 self
1084 }
1085
1086 #[must_use]
1091 pub fn filter_any_operands(
1092 mut self,
1093 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
1094 ) -> Self {
1095 self.request.or_clause(alternatives.iter().copied());
1096
1097 self
1098 }
1099
1100 #[must_use]
1110 pub fn filter_in(
1111 mut self,
1112 field: &'a str,
1113 values: &[impl Copy + Into<IndexValue<'a>>],
1114 ) -> Self {
1115 self.request.or_clause(
1116 values
1117 .iter()
1118 .copied()
1119 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
1120 );
1121
1122 self
1123 }
1124
1125 #[must_use]
1133 pub fn filter_not_in(
1134 mut self,
1135 field: &'a str,
1136 values: &[impl Copy + Into<IndexValue<'a>>],
1137 ) -> Self {
1138 self.request
1139 .filter_not_in(field, values.iter().copied().map(Into::into));
1140
1141 self
1142 }
1143
1144 #[must_use]
1149 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
1150 self.request.using_index(name, values);
1151
1152 self
1153 }
1154
1155 #[must_use]
1158 pub fn order_asc(mut self, field: &'a str) -> Self {
1159 self.request.append_order(field, SortDirection::Ascending);
1160
1161 self
1162 }
1163
1164 #[must_use]
1167 pub fn order_desc(mut self, field: &'a str) -> Self {
1168 self.request.append_order(field, SortDirection::Descending);
1169
1170 self
1171 }
1172
1173 #[must_use]
1184 pub fn order_by(mut self, fields: &[&'a str]) -> Self {
1185 self.request.order_by(fields);
1186
1187 self
1188 }
1189
1190 #[must_use]
1195 pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
1196 self.request.order_by_each(fields);
1197
1198 self
1199 }
1200
1201 #[must_use]
1203 pub fn descending(mut self) -> Self {
1204 self.request.descending = true;
1205
1206 self
1207 }
1208
1209 #[must_use]
1216 pub fn limit(mut self, rows: usize) -> Self {
1217 self.request.rows = rows;
1218
1219 self
1220 }
1221
1222 #[must_use]
1224 pub fn work_limit(mut self, candidates: usize) -> Self {
1225 self.request.work = candidates;
1226
1227 self
1228 }
1229
1230 #[cfg(feature = "test-support")]
1232 #[doc(hidden)]
1233 #[must_use]
1234 pub fn test_output_limit(mut self, bytes: usize) -> Self {
1235 self.request.bytes = bytes;
1236
1237 self
1238 }
1239
1240 #[must_use]
1242 pub fn after(self, cursor: &'a QueryCursor) -> Self {
1243 self.after_optional(Some(cursor))
1244 }
1245
1246 #[must_use]
1248 pub fn after_optional(mut self, cursor: Option<&'a QueryCursor>) -> Self {
1249 self.request.cursor = cursor;
1250
1251 self
1252 }
1253
1254 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
1261 observe!(query, { self.entity_page() })
1262 }
1263
1264 fn entity_page(self) -> Result<QueryPage<E>, Error> {
1265 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
1266 }
1267
1268 pub fn first(self) -> Result<Option<E>, Error> {
1274 self.first_with(Self::entity_page)
1275 }
1276
1277 pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
1281 self.first_with(Self::projected_page::<R>)
1282 }
1283
1284 fn first_with<R>(
1285 self,
1286 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1287 ) -> Result<Option<R>, Error> {
1288 observe!(query, { fetch(self.probe_matches(SingleResult::First)?) })
1289 .map(|mut page| page.rows.pop())
1290 }
1291
1292 pub fn try_one(self) -> Result<Option<E>, Error> {
1299 self.try_one_with(Self::entity_page)
1300 }
1301
1302 pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
1308 self.try_one_with(Self::projected_page::<R>)
1309 }
1310
1311 fn try_one_with<R>(
1312 self,
1313 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1314 ) -> Result<Option<R>, Error> {
1315 observe!(query, {
1316 if self.request.cursor.is_some() {
1317 return Err(Error::InvalidQuery);
1318 }
1319 fetch(self.probe_matches(SingleResult::Only)?)
1320 })
1321 .map(|mut page| page.rows.pop())
1322 }
1323
1324 fn probe_matches(mut self, probe: SingleResult) -> Result<Self, Error> {
1325 if !(1..=32).contains(&self.request.rows) {
1326 return Err(Error::Limit);
1327 }
1328
1329 self.request.single_result_probe = Some(probe);
1330
1331 Ok(self.limit(match probe {
1332 SingleResult::First => 1,
1333 SingleResult::Only => 2,
1334 }))
1335 }
1336
1337 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1347 observe!(query, { self.projected_page() })
1348 }
1349
1350 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1351 let raw = fetch_rows(
1352 &*self.db.read()?,
1353 E::SCHEMA,
1354 self.request,
1355 Some(Projection::Record(R::definition())),
1356 )?;
1357
1358 raw.decode_with(R::decode_from)
1359 }
1360}
1361
1362#[derive(Clone, Copy)]
1363enum Projection<'a> {
1364 Record(&'a TypeSchema),
1365 Columns(&'a [u8]),
1366}
1367
1368impl Projection<'_> {
1369 fn mask(self, entity: &EntitySchema) -> Result<u32, Error> {
1370 match self {
1371 Self::Record(record) => admit_projection(entity, record),
1372 Self::Columns(columns) => {
1373 let mut mask = 0;
1374 for &column in columns {
1375 if usize::from(column) >= entity.fields.len() || mask & (1 << column) != 0 {
1376 return Err(Error::InvalidQuery);
1377 }
1378 mask |= 1 << column;
1379 }
1380 Ok(mask)
1381 }
1382 }
1383 }
1384}
1385
1386fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u32, Error> {
1390 let TypeBody::Record(fields) = &output.body else {
1391 return Err(Error::InvalidQuery);
1392 };
1393 if fields.is_empty()
1394 || fields.len() > crate::schema::MAX_FIELDS
1395 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1396 {
1397 return Err(Error::InvalidQuery);
1398 }
1399 let mut source = TypeGraph::default();
1400 let mut target = TypeGraph::default();
1401 let mut mask = 0;
1402 for field in *fields {
1403 let position = entity
1404 .field_position(field.name)
1405 .ok_or(Error::InvalidQuery)?;
1406 let stored = &entity.fields[position];
1407 if stored.value != field.value || stored.optional != field.optional {
1408 return Err(Error::InvalidQuery);
1409 }
1410 source
1411 .include(stored.value)
1412 .map_err(|_| Error::InvalidQuery)?;
1413 target
1414 .include(field.value)
1415 .map_err(|_| Error::InvalidQuery)?;
1416 mask |= 1 << position;
1417 }
1418 if !source.contains(&target) {
1419 return Err(Error::InvalidQuery);
1420 }
1421
1422 Ok(mask)
1423}
1424
1425struct Term {
1426 tests_presence: bool,
1427 position: usize,
1428 comparison: Comparison,
1429 operand: TermOperand,
1430 or_next: bool,
1431}
1432
1433enum TermOperand {
1434 Literal {
1435 bytes: Vec<u8>,
1436 absent: bool,
1437 },
1438 Member {
1439 item: FieldType,
1440 needle: MemberNeedle,
1441 },
1442 Nested {
1443 member: crate::member::RecordMember,
1444 literal: Vec<u8>,
1445 absent: bool,
1446 },
1447 Field {
1448 right: usize,
1449 left_member: Option<crate::member::RecordMember>,
1450 right_member: Option<crate::member::RecordMember>,
1451 },
1452 Length {
1453 member: Option<crate::member::RecordMember>,
1454 threshold: u32,
1455 },
1456}
1457
1458enum MemberNeedle {
1459 Literal(Vec<u8>),
1460 Field(usize, Option<crate::member::RecordMember>),
1461}
1462
1463fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1466 match value {
1467 IndexValue::Text(text) => Some(text.as_bytes()),
1468 IndexValue::Blob(bytes) => Some(bytes),
1469 _ => None,
1470 }
1471}
1472
1473fn consecutive_values(low: IndexValue<'_>, high: IndexValue<'_>) -> bool {
1474 low.discrete_successor()
1475 .is_some_and(|next| equal_values(next, high))
1476}
1477
1478fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1479 match (left, right) {
1481 (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1482 a == b
1483 }
1484 _ => left == right,
1485 }
1486}
1487
1488fn length_limit(field: FieldType) -> Option<u32> {
1489 match key::operand_type(field) {
1490 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1491 FieldType::List { max_items, .. } => Some(max_items),
1492 FieldType::Named(link) => match (link.definition)().body {
1493 TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1494 _ => None,
1495 },
1496 _ => None,
1497 }
1498}
1499
1500fn member_type(field: FieldType) -> Option<FieldType> {
1501 match key::operand_type(field) {
1502 FieldType::List { item, .. } => Some(*item),
1503 FieldType::Named(link) => match (link.definition)().body {
1504 TypeBody::Set { item, .. } => Some(item),
1505 _ => None,
1506 },
1507 _ => None,
1508 }
1509}
1510
1511fn contains_member(
1513 span: &[u8],
1514 optional: bool,
1515 item: FieldType,
1516 needle: IndexValue<'_>,
1517) -> Result<bool, Error> {
1518 let mut reader = Decoder::new(span)?;
1519 if optional && !reader.boolean()? {
1520 return Ok(false);
1521 }
1522 for _ in 0..reader.nat32()? {
1523 let value = IndexValue::read(&mut reader, item)?;
1524 if equal_values(value, needle) {
1525 return Ok(true);
1526 }
1527 }
1528
1529 Ok(false)
1530}
1531
1532fn projection_positions(mut mask: u32) -> impl Iterator<Item = usize> {
1535 std::iter::from_fn(move || {
1536 if mask == 0 {
1537 return None;
1538 }
1539 let position = mask.trailing_zeros() as usize;
1540 mask &= mask - 1;
1541 Some(position)
1542 })
1543}
1544
1545fn admit_ordered_fields(entity: &EntitySchema, mask: u32) -> Result<(), Error> {
1546 for i in projection_positions(mask) {
1547 if !key::supports(entity.fields[i].value) {
1548 return Err(Error::InvalidQuery);
1549 }
1550 }
1551
1552 Ok(())
1553}
1554
1555fn comparison_key(
1557 entity: &EntitySchema,
1558 mask: u32,
1559 values: &[IndexValue<'_>],
1560 scratch: &mut Vec<u8>,
1561) -> Result<(), Error> {
1562 build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1563}
1564
1565fn build_comparison_key<'a>(
1566 entity: &EntitySchema,
1567 mask: u32,
1568 key: &mut Vec<u8>,
1569 mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1570) -> Result<(), Error> {
1571 key.clear();
1572 for i in projection_positions(mask) {
1573 let field = &entity.fields[i];
1574 value(i, field)?.append_component(field.optional, key);
1575 if key.len() > MAX_COMPARISON_KEY {
1576 return Err(Error::Limit);
1577 }
1578 }
1579
1580 Ok(())
1581}
1582
1583fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1584 if size > limit {
1585 return Err(Error::RowTooLarge);
1586 }
1587 if size > limit - *used {
1588 return Err(Error::Limit);
1589 }
1590 *used += size;
1591
1592 Ok(())
1593}
1594
1595fn projection_size(spans: &[(u16, u16)], mask: u32) -> usize {
1597 projection_positions(mask)
1598 .map(|i| {
1599 let (start, end) = spans[i];
1600 usize::from(end - start)
1601 })
1602 .sum()
1603}
1604
1605fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u32, size: usize) -> Vec<u8> {
1606 let mut output = Vec::with_capacity(size);
1607 for i in projection_positions(mask) {
1608 let (start, end) = spans[i];
1609 output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1610 }
1611
1612 output
1613}
1614#[derive(Clone, Copy)]
1615enum PlanOutput {
1616 Rows,
1617 Aggregate { grouped: bool },
1618 ImmediateCount,
1619}
1620
1621struct Plan<'a> {
1622 primary: usize,
1623 index: Option<&'a IndexSchema>,
1624 prefix: Vec<u8>,
1625 fixed_components: usize,
1626 terms: Vec<Term>,
1627 selected: u32,
1628 span_fields: u32,
1630 binding: [u8; 32],
1631 projection: Option<u32>,
1632 distinct: distinct::Strategy,
1633 sort: Option<Vec<order::SortField>>,
1634 descending: bool,
1635}
1636impl<'a> Plan<'a> {
1637 fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1638 self.terms.split_inclusive(|term| !term.or_next)
1639 }
1640
1641 fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1642 self.index = Some(path.index);
1643 self.prefix = path.prefix;
1644 self.fixed_components = path.fixed;
1645 self.selected |= entity.key_fields();
1646 }
1647
1648 fn admit(
1649 entity: &'a EntitySchema,
1650 request: &Request<'_>,
1651 schema: [u8; 32],
1652 incarnation: [u8; 16],
1653 projection: Option<Projection<'_>>,
1654 output: PlanOutput,
1655 ) -> Result<Self, Error> {
1656 if !request.within_limits() {
1657 return Err(Error::Limit);
1658 }
1659 if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1660 {
1661 return Err(Error::InvalidQuery);
1662 }
1663 for value in request
1665 .predicates
1666 .iter()
1667 .filter_map(|p| match &p.operand {
1668 QueryOperand::Literal(value) => Some(value),
1669 QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1670 })
1671 .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1672 {
1673 if match value {
1674 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1675 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1676 _ => false,
1677 } {
1678 return Err(Error::Limit);
1679 }
1680 }
1681 let primary = entity
1682 .field_position(entity.primary_key)
1683 .filter(|&i| !entity.fields[i].optional)
1684 .ok_or(Error::InvalidQuery)?;
1685 let mut plan = Self {
1686 primary,
1687 index: None,
1688 prefix: prefix(2, entity.id, &[]),
1689 fixed_components: 0,
1690 terms: Vec::new(),
1691 selected: 1 << primary,
1692 span_fields: 0,
1693 binding: [0; 32],
1694 projection: projection.map(|output| output.mask(entity)).transpose()?,
1695 distinct: distinct::Strategy::Identity,
1696 sort: None,
1697 descending: request.descending ^ request.primary_descending(entity),
1698 };
1699 for predicate in &request.predicates {
1700 let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
1701 let field = &entity.fields[position];
1702 let member = if predicate.comparison == Comparison::Contains {
1703 member_type(field.value)
1704 } else {
1705 None
1706 };
1707 let operand = match (predicate.operand, record_member) {
1708 (QueryOperand::Literal(value), Some(member)) => {
1709 if !predicate.comparison.supports_record_member() {
1710 return Err(Error::InvalidQuery);
1711 }
1712 let leaf = member.field();
1713 predicate.comparison.admit(
1714 leaf.value,
1715 field.optional || leaf.optional,
1716 value,
1717 )?;
1718 let mut literal = Vec::new();
1719 value.append_component(field.optional || leaf.optional, &mut literal);
1720 plan.span_fields |= 1 << position;
1721 TermOperand::Nested {
1722 member,
1723 literal,
1724 absent: value == IndexValue::Absent,
1725 }
1726 }
1727 (QueryOperand::Length(length), member) => {
1728 let selected = member.map_or(field.value, |m| m.field().value);
1729 if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1730 return Err(Error::InvalidQuery);
1731 }
1732 plan.span_fields |= 1 << position;
1733
1734 TermOperand::Length {
1735 member,
1736 threshold: length,
1737 }
1738 }
1739 (QueryOperand::Field(name), left_member) => {
1740 let (right, right_member) = crate::member::resolve_field(entity, name)?;
1741 if (left_member.is_some() || right_member.is_some())
1742 && member.is_none()
1743 && !predicate.comparison.supports_record_member()
1744 {
1745 return Err(Error::InvalidQuery);
1746 }
1747 let right_type =
1748 right_member.map_or(entity.fields[right].value, |m| m.field().value);
1749 let left_type =
1750 left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1751 let compatible = left_type == right_type
1752 || matches!(
1753 (left_type, right_type),
1754 (FieldType::Text { .. }, FieldType::Text { .. })
1755 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1756 );
1757 if !compatible
1758 || !key::supports(left_type)
1759 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1760 {
1761 return Err(Error::InvalidQuery);
1762 }
1763 if right_member.is_some() {
1764 plan.span_fields |= 1 << right;
1765 } else {
1766 plan.selected |= 1 << right;
1767 }
1768
1769 if let Some(item) = member {
1770 plan.span_fields |= 1 << position;
1771
1772 TermOperand::Member {
1773 item,
1774 needle: MemberNeedle::Field(right, right_member),
1775 }
1776 } else {
1777 if left_member.is_some() {
1778 plan.span_fields |= 1 << position;
1779 } else {
1780 plan.selected |= 1 << position;
1781 }
1782 TermOperand::Field {
1783 right,
1784 left_member,
1785 right_member,
1786 }
1787 }
1788 }
1789 (QueryOperand::Literal(value), None) => {
1790 if let Some(item) = member {
1791 if !key::supports(item) {
1792 return Err(Error::InvalidQuery);
1793 }
1794 value.admit(item, false)?;
1795 let mut bytes = Vec::new();
1796 value.append_component(false, &mut bytes);
1797 plan.span_fields |= 1 << position;
1798
1799 TermOperand::Member {
1800 item,
1801 needle: MemberNeedle::Literal(bytes),
1802 }
1803 } else {
1804 let absent = value == IndexValue::Absent;
1805 if key::supports(field.value) {
1806 plan.selected |= 1 << position;
1807 } else if absent
1808 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1809 {
1810 plan.span_fields |= 1 << position;
1811 } else {
1812 return Err(Error::InvalidQuery);
1813 }
1814 predicate
1815 .comparison
1816 .admit(field.value, field.optional, value)?;
1817 let mut bytes = Vec::new();
1818 value.append_component(field.optional, &mut bytes);
1819
1820 TermOperand::Literal { bytes, absent }
1821 }
1822 }
1823 };
1824 plan.terms.push(Term {
1825 tests_presence: predicate.tests_presence(entity, &operand),
1826 position,
1827 comparison: predicate.comparison,
1828 operand,
1829 or_next: predicate.or_next,
1830 });
1831 }
1832 match order::select(entity, request, output)? {
1835 order::Path::Primary => {}
1836 order::Path::Index(path, descending) => {
1837 plan.use_index(entity, path);
1838 plan.descending = request.descending ^ descending;
1839 }
1840 order::Path::Filtered { sort } => {
1841 order::select_filtered_path(entity, request, &mut plan, None)?;
1842 for field in sort.iter().flatten() {
1843 if field.member.is_some() {
1844 plan.span_fields |= 1 << field.position;
1845 } else {
1846 plan.selected |= 1 << field.position;
1847 }
1848 }
1849 plan.sort = sort;
1850 }
1851 }
1852 if request.distinct {
1853 plan.distinct = distinct::admit(entity, request, &plan)?;
1854 match plan.distinct {
1855 distinct::Strategy::FirstMatch => plan.sort = None,
1856 distinct::Strategy::Complete { key_fields } => plan.selected |= key_fields,
1857 _ => {}
1858 }
1859 }
1860 if matches!(output, PlanOutput::ImmediateCount)
1862 || (request.single_result_probe.is_some() && request.cursor.is_none())
1863 {
1864 return Ok(plan);
1865 }
1866 plan.bind_cursor(entity, request, schema, incarnation, projection)?;
1867
1868 Ok(plan)
1869 }
1870}
1871
1872fn consume_index_component(
1874 entity: &EntitySchema,
1875 index: &IndexSchema,
1876 name: &str,
1877 remaining: &mut &[u8],
1878) -> Result<(), Error> {
1879 let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
1880
1881 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
1882}
1883
1884#[inline(never)]
1887#[expect(
1888 clippy::needless_pass_by_value,
1889 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1890)]
1891fn fetch_rows<M: Memory>(
1892 db: &Database<M>,
1893 entity: &EntitySchema,
1894 request: Request<'_>,
1895 projection: Option<Projection<'_>>,
1896) -> Result<QueryPage<Vec<u8>>, Error> {
1897 db.schema.admits(entity)?;
1898 let plan = Plan::admit(
1899 entity,
1900 &request,
1901 db.schema.fingerprint(),
1902 db.incarnation,
1903 projection,
1904 PlanOutput::Rows,
1905 )?;
1906
1907 execute(&db.map, entity, &request, &plan, None)
1908}
1909
1910fn execute<M: Memory>(
1911 map: &Map<M>,
1912 entity: &EntitySchema,
1913 request: &Request<'_>,
1914 plan: &Plan<'_>,
1915 mut aggregate: Option<aggregate::Accumulator<'_>>,
1916) -> Result<QueryPage<Vec<u8>>, Error> {
1917 execute_inner(
1918 map,
1919 entity,
1920 request,
1921 plan,
1922 range::bounds(entity, request, plan)?,
1923 aggregate.as_mut(),
1924 None,
1925 )
1926}
1927
1928const STEP_INPUT_BYTES: usize = 64 * 1024;
1931const fn candidate_byte_limit(row_bytes: usize) -> usize {
1932 row_bytes + 2 * crate::MAX_INDEX_KEY_BYTES
1933}
1934
1935fn execute_inner<M: Memory>(
1936 map: &Map<M>,
1937 entity: &EntitySchema,
1938 request: &Request<'_>,
1939 plan: &Plan<'_>,
1940 bounds: Option<range::Bounds>,
1941 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1942 mut input_bytes: Option<&mut usize>,
1943) -> Result<QueryPage<Vec<u8>>, Error> {
1944 let mut page = QueryPage {
1945 rows: Vec::new(),
1946 next: None,
1947 examined: 0,
1948 fetched: 0,
1949 output_bytes: 0,
1950 };
1951 let Some(bounds) = bounds else {
1952 return Ok(page);
1953 };
1954 let terminal = range::terminal_key(&bounds, plan.descending);
1955 let mut next_entry = range::entries(map, &bounds, plan.descending);
1956 let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
1957 Some(distinct::Collection::new(
1958 plan.projection.ok_or(Error::InvalidQuery)?,
1959 key_fields,
1960 ))
1961 } else {
1962 None
1963 };
1964 let mut sorted = plan
1965 .sort
1966 .as_ref()
1967 .map(|_| sort::Collection::new(request, plan.distinct));
1968 let mut component = Vec::new();
1969 let mut right_component = Vec::new();
1970 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
1972 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1973 } else {
1974 None
1975 };
1976 let candidate_bytes = candidate_byte_limit(entity.max_row_bytes);
1977 let primary_type = entity.fields[plan.primary].value;
1978 let needs_spans = plan.index.is_some()
1979 || plan.span_fields != 0
1980 || match &aggregate {
1981 Some(accumulator) => accumulator.needs_spans(),
1982 None => plan.projection.is_some(),
1983 };
1984 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1986 let mut index_info = None;
1987 while let Some((stored_key, stored_value)) = next_entry() {
1988 if page.examined == request.work {
1991 return Err(Error::Limit);
1992 }
1993 page.examined += 1;
1994 let mut read_bytes = stored_key.len();
1995 let (owner, bytes) = if plan.index.is_some() {
1996 read_bytes += stored_value.len();
1997 read_index_owner(map, entity.id, primary_type, &stored_value)?
1998 } else {
1999 (
2000 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
2001 stored_value,
2002 )
2003 };
2004 if let Some(used) = input_bytes.as_deref_mut() {
2005 read_bytes += bytes.len();
2006 if read_bytes > candidate_bytes {
2007 return Err(Error::Corrupt);
2008 }
2009 *used += read_bytes;
2010 }
2011 page.fetched += 1;
2012 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
2013 entity.inspect_fields(
2014 &bytes,
2015 plan.selected,
2016 &mut values,
2017 needs_spans.then_some(&mut spans),
2018 )?;
2019 let row_key = RowKey::from_index(values[plan.primary])?;
2020 if plan.index.is_some() {
2021 let info = index_info.get_or_insert_with(|| crate::__private::RowInfo::new(row_key));
2022 info.key = row_key;
2023 entity.fill_index_info(&values, &bytes, &spans, info)?;
2024 validate_index_entry(entity, info, owner, &stored_key)?;
2025 } else if row_key != owner {
2026 return Err(Error::Corrupt);
2027 }
2028 let matches = predicate::PredicateRow {
2029 entity,
2030 bytes: &bytes,
2031 values: &values,
2032 spans: &spans,
2033 span_fields: plan.span_fields,
2034 }
2035 .matches(
2036 &plan.terms,
2037 &request.predicates,
2038 &mut component,
2039 &mut right_component,
2040 )?;
2041 let boundary = distinct::boundary(entity, plan.index, plan.distinct, &stored_key)?;
2042 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2043 if matches && let Some(accumulator) = aggregate.as_mut() {
2044 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2045 if matches!(accumulator, aggregate::Accumulator::Until(remaining) if **remaining == 0) {
2046 return Ok(page);
2048 }
2049 } else if matches && let Some(collection) = collected.as_mut() {
2050 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2051 if request.single_result_probe == Some(SingleResult::First) {
2053 break;
2054 }
2055 } else if matches && let Some(collection) = sorted.as_mut() {
2056 collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2057 request.check_result_count(collection.result_count())?;
2059 } else if matches && !duplicate {
2060 request.check_result_count(page.rows.len() + 1)?;
2061 let size = plan
2062 .projection
2063 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2064 if size > request.bytes {
2065 return Err(Error::RowTooLarge);
2066 }
2067 if size > request.bytes - page.output_bytes {
2068 page.next = Some(plan.cursor(&stored_key, Resume::Retry));
2069
2070 return Ok(page);
2071 }
2072 page.output_bytes += size;
2073 if let Some(mask) = plan.projection {
2074 page.rows.push(copy_projection(&bytes, &spans, mask, size));
2075 } else {
2076 page.rows.push(bytes);
2077 }
2078 if request.single_result_probe == Some(SingleResult::First)
2079 || plan.distinct.finishes_on_match(plan.fixed_components)
2080 {
2081 return Ok(page);
2082 }
2083 if let Some(boundary) = boundary {
2084 previous = Some(boundary.to_vec());
2085 }
2086 }
2087 if page.rows.len() == request.rows
2088 || page.examined == request.work
2089 || input_bytes
2090 .as_deref()
2091 .is_some_and(|used| *used > STEP_INPUT_BYTES - candidate_bytes)
2092 {
2093 if terminal == Some(&stored_key) {
2094 break;
2095 }
2096 if request.single_result_probe.is_some()
2097 || (aggregate.is_some() && input_bytes.is_none())
2098 || collected.is_some()
2099 || sorted.is_some()
2100 {
2101 continue;
2104 }
2105 if input_bytes.is_some() && next_entry().is_none() {
2109 break;
2110 }
2111 let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
2112 Resume::AfterUnemittedClass
2113 } else {
2114 Resume::After
2115 };
2116 page.next = Some(plan.cursor(&stored_key, resume));
2117
2118 return Ok(page);
2119 }
2120 }
2121 if let Some(collection) = collected {
2122 page.output_bytes = collection.output_bytes;
2123 page.rows = collection.rows;
2124 }
2125 if let Some(collection) = sorted {
2126 collection.finish(request.bytes, &mut page)?;
2127 }
2128
2129 Ok(page)
2130}