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 match self {
193 Comparison::Lt | Comparison::Le | Comparison::Gt | Comparison::Ge => {
194 let mut encoded = Vec::new();
196 left.append_component(false, &mut encoded);
197 let split = encoded.len();
198 right.append_component(false, &mut encoded);
199 let (left, right) = encoded.split_at(split);
200
201 Some(self.accepts(Some(left), Some(right), false))
202 }
203 _ => None,
204 }
205 }
206
207 fn accepts_bytes(self, actual: &[u8], operand: &[u8]) -> bool {
209 match self {
210 Self::StartsWith => actual.starts_with(operand),
211 Self::EndsWith => actual.ends_with(operand),
212 Self::Contains => memchr::memmem::find(actual, operand).is_some(),
213 _ => self.accepts(Some(actual), Some(operand), false),
214 }
215 }
216
217 fn accepts_length(self, actual: Option<u32>, threshold: u32) -> bool {
218 let encoded = actual.map(u32::to_be_bytes);
219
220 self.accepts(
221 encoded.as_ref().map(|v| v.as_slice()),
222 Some(&threshold.to_be_bytes()),
223 false,
224 )
225 }
226
227 fn empty_length_value(self, threshold: u32, field: FieldType) -> Option<IndexValue<'static>> {
229 if !matches!((self, threshold), (Self::Eq | Self::Le, 0) | (Self::Lt, 1)) {
230 return None;
231 }
232 match key::operand_type(field) {
233 FieldType::Text { .. } => Some(IndexValue::Text("")),
234 FieldType::Blob { .. } => Some(IndexValue::Blob(&[])),
235 _ => None,
236 }
237 }
238
239 fn uniform_length_result(self, min: u32, max: u32, n: u32) -> Option<bool> {
241 match self {
242 Self::Eq | Self::Ne if min == max || n < min || n > max => {
243 Some(self.accepts_length(Some(min), n))
244 }
245 Self::Lt | Self::Ge if max < n || min >= n => Some(self.accepts_length(Some(min), n)),
246 Self::Le | Self::Gt if max <= n || min > n => Some(self.accepts_length(Some(min), n)),
247 _ => None,
248 }
249 }
250
251 fn accepts_absent(self, other_absent: bool) -> bool {
254 match self {
255 Self::Eq => other_absent,
256 Self::Ne => !other_absent,
257 _ => false,
258 }
259 }
260}
261
262fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
264 let Some(start) = memchr::memmem::find(actual, needle) else {
265 return false;
266 };
267 if start == 0 || actual[start - 1] != 0 {
268 return true;
269 }
270 fn raw(content: &[u8]) -> Vec<u8> {
274 let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
275 let mut encoded = content.iter();
276 while let Some(&byte) = encoded.next() {
277 bytes.push(byte);
278 if byte == 0 {
279 encoded.next();
280 }
281 }
282
283 bytes
284 }
285
286 memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
287}
288
289#[derive(Debug)]
292pub struct QueryPage<T> {
293 pub rows: Vec<T>,
295 pub next: Option<QueryCursor>,
297 pub examined: usize,
299 pub fetched: usize,
301 pub output_bytes: usize,
303}
304
305impl QueryPage<Vec<u8>> {
306 #[inline(never)]
307 pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
308 Ok(QueryPage {
309 rows: self
310 .rows
311 .iter()
312 .map(|bytes| E::decode(bytes))
313 .collect::<Result<_, _>>()?,
314 next: self.next,
315 examined: self.examined,
316 fetched: self.fetched,
317 output_bytes: self.output_bytes,
318 })
319 }
320
321 #[inline(never)]
322 fn decode_with<R>(
323 self,
324 decode: impl Fn(&mut Decoder<'_>) -> Result<R, Error>,
325 ) -> Result<QueryPage<R>, Error> {
326 Ok(QueryPage {
327 rows: self
328 .rows
329 .iter()
330 .map(|bytes| {
331 let mut reader = Decoder::new(bytes)?;
332 let row = decode(&mut reader)?;
334 reader.finish()?;
335
336 Ok(row)
337 })
338 .collect::<Result<_, Error>>()?,
339 next: self.next,
340 examined: self.examined,
341 fetched: self.fetched,
342 output_bytes: self.output_bytes,
343 })
344 }
345}
346
347#[derive(Clone, Copy, Debug, PartialEq, Eq)]
349pub enum QueryOperand<'a> {
350 Literal(IndexValue<'a>),
352 Length(u32),
354 Field(&'a str),
356}
357
358struct Predicate<'a> {
359 field: &'a str,
360 comparison: Comparison,
361 operand: QueryOperand<'a>,
362 or_next: bool,
364}
365
366impl<'a> Predicate<'a> {
367 fn compared_field(&self, name: &str) -> Option<&'a str> {
369 let QueryOperand::Field(right) = self.operand else {
370 return None;
371 };
372 if self.field == name {
373 Some(right)
374 } else if right == name {
375 Some(self.field)
376 } else {
377 None
378 }
379 }
380
381 fn at_extreme(&self, entity: &EntitySchema, value: IndexValue<'_>, upper: bool) -> bool {
383 use crate::{Date, Duration, Timestamp, Ulid};
384
385 match value {
386 IndexValue::Bool(b) => b == upper,
387 IndexValue::Date(d) => d == if upper { Date::MAX } else { Date::MIN },
388 IndexValue::Timestamp(t) => {
389 t == if upper {
390 Timestamp::MAX
391 } else {
392 Timestamp::MIN
393 }
394 }
395 IndexValue::Duration(d) => d == if upper { Duration::MAX } else { Duration::MIN },
396 IndexValue::Ulid(id) => id == if upper { Ulid::MAX } else { Ulid::MIN },
397 IndexValue::UnitEnum { ordinal, .. } => entity
398 .index_field(self.field)
399 .is_some_and(|field| key::is_fixed_extreme(field.value, &[ordinal], upper)),
400 IndexValue::Text("") | IndexValue::Blob([]) => !upper,
401 _ => value.is_integer_extreme(upper),
402 }
403 }
404
405 fn fixed_equality(&self, entity: &EntitySchema) -> Option<(&'a str, IndexValue<'a>)> {
407 if let QueryOperand::Length(n) = self.operand {
408 let empty = self
409 .comparison
410 .empty_length_value(n, entity.index_field(self.field)?.value)?;
411 return Some((self.field, empty));
412 }
413 let QueryOperand::Literal(value) = self.operand else {
414 return None;
415 };
416 let fixed = match (self.comparison, value) {
418 (Comparison::Eq, _) => value,
419 (Comparison::Ne, IndexValue::Bool(excluded))
420 if entity.field_is_required(self.field) =>
421 {
422 IndexValue::Bool(!excluded)
423 }
424 (cmp @ (Comparison::Ge | Comparison::Le), _)
425 if self.at_extreme(entity, value, cmp == Comparison::Ge) =>
426 {
427 value
428 }
429 (Comparison::Gt, IndexValue::Bool(false)) => IndexValue::Bool(true),
430 (Comparison::Lt, IndexValue::Bool(true)) => IndexValue::Bool(false),
431 _ => return None,
432 };
433 Some((self.field, fixed))
434 }
435
436 fn tests_presence(&self, entity: &EntitySchema, operand: &TermOperand) -> bool {
438 match (self.comparison, self.operand) {
439 (Comparison::Ne, QueryOperand::Literal(IndexValue::Absent)) => true,
440 (cmp @ (Comparison::Le | Comparison::Ge), QueryOperand::Literal(value)) => {
441 self.at_extreme(entity, value, cmp == Comparison::Le)
442 }
443 (_, QueryOperand::Length(_)) => {
444 self.present_length_result(entity) == Some(true)
445 && self.comparison != Comparison::Ne
446 }
447 (
448 Comparison::Le
449 | Comparison::Ge
450 | Comparison::StartsWith
451 | Comparison::EndsWith
452 | Comparison::Contains,
453 QueryOperand::Field(right),
454 ) => right == self.field,
455 (
456 Comparison::StartsWith | Comparison::EndsWith | Comparison::Contains,
457 QueryOperand::Literal(needle),
458 ) => {
459 !matches!(operand, TermOperand::Member { .. })
461 && scalar_bytes(needle).is_some_and(<[u8]>::is_empty)
462 }
463 _ => false,
464 }
465 }
466
467 fn present_length_result(&self, entity: &EntitySchema) -> Option<bool> {
469 let QueryOperand::Length(n) = self.operand else {
470 return None;
471 };
472 let max = length_limit(entity.index_field(self.field)?.value)?;
473 self.comparison.uniform_length_result(0, max, n)
474 }
475
476 fn constant_comparison(&self, entity: &EntitySchema) -> Option<bool> {
477 if let QueryOperand::Literal(value) = self.operand {
478 return match (self.comparison, value) {
480 (cmp @ (Comparison::Lt | Comparison::Gt), value)
481 if self.at_extreme(entity, value, cmp == Comparison::Gt) =>
482 {
483 Some(false)
484 }
485 _ => None,
486 };
487 }
488 if matches!(self.operand, QueryOperand::Length(_)) {
489 let result = self.present_length_result(entity)?;
490 return (result == self.comparison.accepts_absent(false)
491 || entity.field_is_required(self.field))
492 .then_some(result);
493 }
494 if !matches!(self.operand, QueryOperand::Field(right) if right == self.field) {
495 return None;
496 }
497 match self.comparison {
498 Comparison::Eq => Some(true),
499 Comparison::Ne | Comparison::Lt | Comparison::Gt => Some(false),
500 _ => None,
501 }
502 }
503}
504
505#[derive(Clone, Copy, PartialEq, Eq)]
506enum SingleResult {
507 First,
508 Only,
509}
510
511struct Request<'a> {
512 groups: aggregate::GroupRequest<'a>,
513 predicates: Vec<Predicate<'a>>,
514 index: Option<(&'a str, Vec<IndexValue<'a>>)>,
515 order: Option<Vec<&'a str>>,
516 order_descending: u8,
517 descending: bool,
518 distinct: bool,
519 single_result_probe: Option<SingleResult>,
520 rows: usize,
521 work: usize,
522 bytes: usize,
523 cursor: Option<&'a QueryCursor>,
524 over_limit: bool,
525}
526
527impl Default for Request<'_> {
528 fn default() -> Self {
529 Self {
530 groups: aggregate::GroupRequest::default(),
531 predicates: Vec::new(),
532 index: None,
533 order: None,
534 order_descending: 0,
535 descending: false,
536 distinct: false,
537 single_result_probe: None,
538 rows: 32,
539 work: 128,
540 bytes: MAX_OUTPUT,
541 cursor: None,
542 over_limit: false,
543 }
544 }
545}
546
547impl<'a> Request<'a> {
550 fn within_limits(&self) -> bool {
551 !self.over_limit
552 && (1..=32).contains(&self.rows)
553 && (1..=MAX_WORK).contains(&self.work)
554 && (1..=MAX_OUTPUT).contains(&self.bytes)
555 }
556
557 fn check_result_count(&self, count: usize) -> Result<(), Error> {
560 if self.single_result_probe == Some(SingleResult::Only) && count > 1 {
561 return Err(Error::MultipleMatches);
562 }
563 Ok(())
564 }
565
566 fn fixed_equalities<'r>(
568 &'r self,
569 entity: &'r EntitySchema,
570 ) -> impl Iterator<Item = (&'a str, IndexValue<'a>)> + 'r {
571 self.clauses().filter_map(move |clause| {
572 let (predicate, rest) = clause.split_first()?;
573 if !rest.is_empty() {
574 let mut candidate = predicate.fixed_equality(entity)?;
575 for alternative in rest {
576 let other = alternative.fixed_equality(entity)?;
577 if candidate.0 != other.0 {
578 return None;
579 }
580 if equal_values(candidate.1, other.1) {
581 continue;
582 }
583 if self.predicates.len() == clause.len() {
584 return None;
585 }
586 if self.excludes_literal(other.0, other.1) {
587 continue;
588 }
589 if !self.excludes_literal(candidate.0, candidate.1) {
590 return None;
591 }
592 candidate = other;
593 }
594 return Some(candidate);
597 }
598 if let Some(equality) = predicate.fixed_equality(entity) {
599 return Some(equality);
600 }
601 let QueryOperand::Literal(value) = predicate.operand else {
604 return None;
605 };
606 let lower = match predicate.comparison {
607 Comparison::Ge => value,
608 Comparison::Gt if self.predicates.len() > 1 => value.discrete_successor()?,
609 _ => return None,
610 };
611 self.clauses()
612 .any(|clause| {
613 let [upper] = clause else { return false };
614 if upper.field != predicate.field {
615 return false;
616 }
617 match (upper.comparison, upper.operand) {
618 (Comparison::Le, QueryOperand::Literal(value)) => {
619 equal_values(lower, value)
620 }
621 (Comparison::Lt, QueryOperand::Literal(value)) => {
622 consecutive_values(lower, value)
623 }
624 _ => false,
625 }
626 })
627 .then_some((predicate.field, lower))
628 })
629 }
630
631 fn excludes_literal(&self, field: &str, value: IndexValue<'_>) -> bool {
632 self.clauses().any(|clause| {
635 clause.iter().all(|predicate| {
636 if predicate.field != field {
637 return false;
638 }
639 let QueryOperand::Literal(literal) = predicate.operand else {
640 return false;
641 };
642 match predicate.comparison {
643 Comparison::Eq
644 | Comparison::Ne
645 | Comparison::Lt
646 | Comparison::Le
647 | Comparison::Gt
648 | Comparison::Ge => {
649 predicate.comparison.accepts_fixed_values(value, literal) == Some(false)
650 }
651 _ => false,
652 }
653 })
654 })
655 }
656
657 fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
658 self.predicates.split_inclusive(|p| !p.or_next)
659 }
660
661 #[inline(never)]
662 fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
663 if self.predicates.len() == MAX_TERMS {
664 self.over_limit = true;
665 } else {
666 self.predicates.push(Predicate {
667 field,
668 comparison,
669 operand,
670 or_next: false,
671 });
672 }
673 }
674
675 #[inline(never)]
676 fn or_clause(
677 &mut self,
678 alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
679 ) {
680 let count = alternatives.len();
681
682 if count == 0 || count > MAX_TERMS - self.predicates.len() {
683 self.over_limit = true;
684 } else {
685 self.predicates.extend(alternatives.enumerate().map(
686 |(i, (field, comparison, operand))| Predicate {
687 field,
688 comparison,
689 operand,
690 or_next: i + 1 < count,
691 },
692 ));
693 }
694 }
695
696 #[inline(never)]
697 fn filter_not_in(
698 &mut self,
699 field: &'a str,
700 values: impl ExactSizeIterator<Item = IndexValue<'a>>,
701 ) {
702 if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
703 self.over_limit = true;
704
705 return;
706 }
707 for value in values {
708 self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
709 }
710 }
711
712 #[inline(never)]
713 fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
714 if values.len() > 4 {
715 self.over_limit = true;
716 } else {
717 self.index = Some((name, values.to_vec()));
718 }
719 }
720
721 #[inline(never)]
722 fn order_by<T: Copy + Into<OrderTerm<'a>>>(&mut self, fields: &[T]) {
723 if fields.len() > 4 {
724 self.over_limit = true;
725
726 return;
727 }
728 self.order = Some(Vec::with_capacity(fields.len()));
729 self.order_descending = 0;
730 for &term in fields {
731 let OrderTerm(field, direction) = term.into();
732 self.append_order(field, direction);
733 }
734 }
735
736 fn append_order(&mut self, field: &'a str, direction: SortDirection) {
737 let fields = self.order.get_or_insert_with(Vec::new);
738 if fields.len() == 4 {
739 self.over_limit = true;
740
741 return;
742 }
743 if direction == SortDirection::Descending {
744 self.order_descending |= 1 << fields.len();
745 }
746 fields.push(field);
747 }
748
749 fn primary_descending(&self, entity: &EntitySchema) -> bool {
750 self.order_descending != 0
751 && self.order.as_ref().is_some_and(|fields| {
752 fields.last() == Some(&entity.primary_key)
753 && self.order_descending & (1 << (fields.len() - 1)) != 0
754 })
755 }
756}
757
758pub(super) fn source_page<M: Memory>(
760 map: &Map<M>,
761 entity: &EntitySchema,
762 binding: [u8; 32],
763 incarnation: [u8; 16],
764 cursor: Option<&QueryCursor>,
765 rows: usize,
766 bytes: usize,
767) -> Result<QueryPage<Vec<u8>>, Error> {
768 let request = Request {
769 rows,
770 work: rows,
771 bytes,
772 cursor,
773 ..Request::default()
774 };
775 let plan = Plan::admit(
776 entity,
777 &request,
778 binding,
779 incarnation,
780 None,
781 PlanOutput::Rows,
782 )?;
783
784 execute(map, entity, &request, &plan, None)
785}
786
787enum QuerySource<'a, M: Memory> {
788 Direct(&'a Database<M>),
789 Session(Rc<RefCell<Database<M>>>),
790}
791
792enum QueryRead<'a, M: Memory> {
793 Direct(&'a Database<M>),
794 Session(Ref<'a, Database<M>>),
795}
796
797impl<M: Memory> Deref for QueryRead<'_, M> {
798 type Target = Database<M>;
799
800 fn deref(&self) -> &Self::Target {
801 match self {
802 Self::Direct(db) => db,
803 Self::Session(db) => db,
804 }
805 }
806}
807
808impl<M: Memory> QuerySource<'_, M> {
809 fn read(&self) -> Result<QueryRead<'_, M>, Error> {
810 match self {
811 Self::Direct(db) => Ok(QueryRead::Direct(db)),
812 Self::Session(db) => db
813 .try_borrow()
814 .map(QueryRead::Session)
815 .map_err(|_| Error::BorrowConflict),
816 }
817 }
818}
819
820pub struct Query<'a, E, M: Memory> {
824 db: QuerySource<'a, M>,
825 request: Request<'a>,
826 entity: PhantomData<E>,
827}
828impl<M: Memory> Database<M> {
829 #[must_use]
831 pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
832 Query {
833 db: QuerySource::Direct(self),
834 entity: PhantomData,
835 request: Request::default(),
836 }
837 }
838}
839impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
840 pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
841 Self {
842 db: QuerySource::Session(db),
843 request: Request::default(),
844 entity: PhantomData,
845 }
846 }
847
848 #[must_use]
862 pub fn distinct(mut self) -> Self {
863 self.request.distinct = true;
864
865 self
866 }
867
868 #[must_use]
881 pub fn filter(
882 mut self,
883 field: &'a str,
884 comparison: Comparison,
885 value: impl Into<IndexValue<'a>>,
886 ) -> Self {
887 self.request
888 .filter(field, comparison, QueryOperand::Literal(value.into()));
889
890 self
891 }
892
893 #[must_use]
895 pub fn by_id(self, id: impl Into<crate::Id<E>>) -> Self {
896 self.eq(
897 E::SCHEMA.primary_key,
898 id.into().key().into_row_key().index_value(),
899 )
900 }
901
902 #[must_use]
904 pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
905 self.filter(field, Comparison::Eq, value)
906 }
907
908 #[must_use]
911 pub fn eq_if_some(self, field: &'a str, value: Option<impl Into<IndexValue<'a>>>) -> Self {
912 match value {
913 Some(value) => self.eq(field, value),
914 None => self,
915 }
916 }
917
918 #[must_use]
920 pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
921 self.filter(field, Comparison::Ne, value)
922 }
923
924 #[must_use]
926 pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
927 self.filter(field, Comparison::Lt, value)
928 }
929
930 #[must_use]
932 pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
933 self.filter(field, Comparison::Le, value)
934 }
935
936 #[must_use]
938 pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
939 self.filter(field, Comparison::Gt, value)
940 }
941
942 #[must_use]
944 pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
945 self.filter(field, Comparison::Ge, value)
946 }
947
948 #[must_use]
956 pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
957 self.request
958 .filter(left, comparison, QueryOperand::Field(right));
959
960 self
961 }
962
963 #[must_use]
968 pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
969 self.request
970 .filter(field, comparison, QueryOperand::Length(length));
971
972 self
973 }
974
975 #[must_use]
978 pub fn filter_present(self, field: &'a str) -> Self {
979 self.filter(field, Comparison::Ne, IndexValue::Absent)
980 }
981
982 #[must_use]
985 pub fn filter_absent(self, field: &'a str) -> Self {
986 self.filter(field, Comparison::Eq, IndexValue::Absent)
987 }
988
989 #[must_use]
993 pub fn filter_range<T: Into<IndexValue<'a>>>(
994 self,
995 field: &'a str,
996 range: std::ops::Range<T>,
997 ) -> Self {
998 self.gte(field, range.start).lt(field, range.end)
999 }
1000
1001 #[must_use]
1005 pub fn filter_ulid_time(
1006 self,
1007 field: &'a str,
1008 range: std::ops::Range<crate::Timestamp>,
1009 ) -> Self {
1010 let (first, last) =
1011 crate::Ulid::time_bounds(range).unwrap_or((crate::Ulid::MAX, crate::Ulid::MIN));
1012 self.filter_between(field, first, last)
1013 }
1014
1015 #[must_use]
1022 pub fn filter_between(
1023 self,
1024 field: &'a str,
1025 lower: impl Into<IndexValue<'a>>,
1026 upper: impl Into<IndexValue<'a>>,
1027 ) -> Self {
1028 self.filter(field, Comparison::Ge, lower)
1029 .filter(field, Comparison::Le, upper)
1030 }
1031
1032 #[must_use]
1040 pub fn filter_not_between(
1041 self,
1042 field: &'a str,
1043 lower: impl Into<IndexValue<'a>>,
1044 upper: impl Into<IndexValue<'a>>,
1045 ) -> Self {
1046 self.filter_any(&[
1047 (field, Comparison::Lt, lower.into()),
1048 (field, Comparison::Gt, upper.into()),
1049 ])
1050 }
1051
1052 #[must_use]
1057 pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1058 self.filter_fields(field, Comparison::Ge, lower)
1059 .filter_fields(field, Comparison::Le, upper)
1060 }
1061
1062 #[must_use]
1067 pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1068 self.filter_any_operands(&[
1069 (field, Comparison::Lt, QueryOperand::Field(lower)),
1070 (field, Comparison::Gt, QueryOperand::Field(upper)),
1071 ])
1072 }
1073
1074 #[must_use]
1082 pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
1083 self.request.or_clause(
1084 alternatives
1085 .iter()
1086 .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
1087 );
1088
1089 self
1090 }
1091
1092 #[must_use]
1097 pub fn filter_any_operands(
1098 mut self,
1099 alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
1100 ) -> Self {
1101 self.request.or_clause(alternatives.iter().copied());
1102
1103 self
1104 }
1105
1106 #[must_use]
1116 pub fn filter_in(
1117 mut self,
1118 field: &'a str,
1119 values: &[impl Copy + Into<IndexValue<'a>>],
1120 ) -> Self {
1121 self.request.or_clause(
1122 values
1123 .iter()
1124 .copied()
1125 .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
1126 );
1127
1128 self
1129 }
1130
1131 #[must_use]
1139 pub fn filter_not_in(
1140 mut self,
1141 field: &'a str,
1142 values: &[impl Copy + Into<IndexValue<'a>>],
1143 ) -> Self {
1144 self.request
1145 .filter_not_in(field, values.iter().copied().map(Into::into));
1146
1147 self
1148 }
1149
1150 #[must_use]
1155 pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
1156 self.request.using_index(name, values);
1157
1158 self
1159 }
1160
1161 #[must_use]
1164 pub fn order_asc(mut self, field: &'a str) -> Self {
1165 self.request.append_order(field, SortDirection::Ascending);
1166
1167 self
1168 }
1169
1170 #[must_use]
1173 pub fn order_desc(mut self, field: &'a str) -> Self {
1174 self.request.append_order(field, SortDirection::Descending);
1175
1176 self
1177 }
1178
1179 #[must_use]
1191 pub fn order_by(mut self, fields: &[impl Copy + Into<OrderTerm<'a>>]) -> Self {
1192 self.request.order_by(fields);
1193
1194 self
1195 }
1196
1197 #[must_use]
1199 pub fn descending(mut self) -> Self {
1200 self.request.descending = true;
1201
1202 self
1203 }
1204
1205 #[must_use]
1212 pub fn limit(mut self, rows: usize) -> Self {
1213 self.request.rows = rows;
1214
1215 self
1216 }
1217
1218 #[must_use]
1220 pub fn work_limit(mut self, candidates: usize) -> Self {
1221 self.request.work = candidates;
1222
1223 self
1224 }
1225
1226 #[cfg(feature = "test-support")]
1228 #[doc(hidden)]
1229 #[must_use]
1230 pub fn test_output_limit(mut self, bytes: usize) -> Self {
1231 self.request.bytes = bytes;
1232
1233 self
1234 }
1235
1236 #[must_use]
1239 pub fn after(mut self, cursor: impl Into<Option<&'a QueryCursor>>) -> Self {
1240 self.request.cursor = cursor.into();
1241
1242 self
1243 }
1244
1245 pub fn fetch(self) -> Result<QueryPage<E>, Error> {
1252 observe!(query, { self.entity_page() })
1253 }
1254
1255 fn entity_page(self) -> Result<QueryPage<E>, Error> {
1256 fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
1257 }
1258
1259 pub fn first(self) -> Result<Option<E>, Error> {
1265 self.first_with(Self::entity_page)
1266 }
1267
1268 pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
1272 self.first_with(Self::projected_page::<R>)
1273 }
1274
1275 fn first_with<R>(
1276 self,
1277 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1278 ) -> Result<Option<R>, Error> {
1279 observe!(query, { fetch(self.probe_matches(SingleResult::First)?) })
1280 .map(|mut page| page.rows.pop())
1281 }
1282
1283 pub fn try_one(self) -> Result<Option<E>, Error> {
1290 self.try_one_with(Self::entity_page)
1291 }
1292
1293 pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
1299 self.try_one_with(Self::projected_page::<R>)
1300 }
1301
1302 fn try_one_with<R>(
1303 self,
1304 fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1305 ) -> Result<Option<R>, Error> {
1306 observe!(query, {
1307 if self.request.cursor.is_some() {
1308 return Err(Error::InvalidQuery);
1309 }
1310 fetch(self.probe_matches(SingleResult::Only)?)
1311 })
1312 .map(|mut page| page.rows.pop())
1313 }
1314
1315 fn probe_matches(mut self, probe: SingleResult) -> Result<Self, Error> {
1316 if !(1..=32).contains(&self.request.rows) {
1317 return Err(Error::Limit);
1318 }
1319
1320 self.request.single_result_probe = Some(probe);
1321
1322 Ok(self.limit(match probe {
1323 SingleResult::First => 1,
1324 SingleResult::Only => 2,
1325 }))
1326 }
1327
1328 pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1338 observe!(query, { self.projected_page() })
1339 }
1340
1341 fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1342 let raw = fetch_rows(
1343 &*self.db.read()?,
1344 E::SCHEMA,
1345 self.request,
1346 Some(Projection::Record(R::definition())),
1347 )?;
1348
1349 raw.decode_with(R::decode_from)
1350 }
1351}
1352
1353#[derive(Clone, Copy)]
1354enum Projection<'a> {
1355 Record(&'a TypeSchema),
1356 Columns(&'a [u8]),
1357}
1358
1359impl Projection<'_> {
1360 fn mask(self, entity: &EntitySchema) -> Result<u32, Error> {
1361 match self {
1362 Self::Record(record) => admit_projection(entity, record),
1363 Self::Columns(columns) => {
1364 let mut mask = 0;
1365 for &column in columns {
1366 if usize::from(column) >= entity.fields.len() || mask & (1 << column) != 0 {
1367 return Err(Error::InvalidQuery);
1368 }
1369 mask |= 1 << column;
1370 }
1371 Ok(mask)
1372 }
1373 }
1374 }
1375}
1376
1377fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u32, Error> {
1381 let TypeBody::Record(fields) = &output.body else {
1382 return Err(Error::InvalidQuery);
1383 };
1384 if fields.is_empty()
1385 || fields.len() > crate::schema::MAX_FIELDS
1386 || fields.windows(2).any(|w| w[0].name >= w[1].name)
1387 {
1388 return Err(Error::InvalidQuery);
1389 }
1390 let mut source = TypeGraph::default();
1391 let mut target = TypeGraph::default();
1392 let mut mask = 0;
1393 for field in *fields {
1394 let position = entity
1395 .field_position(field.name)
1396 .ok_or(Error::InvalidQuery)?;
1397 let stored = &entity.fields[position];
1398 if stored.value != field.value || stored.optional != field.optional {
1399 return Err(Error::InvalidQuery);
1400 }
1401 source
1402 .include(stored.value)
1403 .map_err(|_| Error::InvalidQuery)?;
1404 target
1405 .include(field.value)
1406 .map_err(|_| Error::InvalidQuery)?;
1407 mask |= 1 << position;
1408 }
1409 if !source.contains(&target) {
1410 return Err(Error::InvalidQuery);
1411 }
1412
1413 Ok(mask)
1414}
1415
1416struct Term {
1417 tests_presence: bool,
1418 position: usize,
1419 comparison: Comparison,
1420 operand: TermOperand,
1421 or_next: bool,
1422}
1423
1424enum TermOperand {
1425 Literal {
1426 bytes: Vec<u8>,
1427 absent: bool,
1428 },
1429 Member {
1430 item: FieldType,
1431 needle: MemberNeedle,
1432 },
1433 Nested {
1434 member: crate::member::RecordMember,
1435 literal: Vec<u8>,
1436 absent: bool,
1437 },
1438 Field {
1439 right: usize,
1440 left_member: Option<crate::member::RecordMember>,
1441 right_member: Option<crate::member::RecordMember>,
1442 },
1443 Length {
1444 member: Option<crate::member::RecordMember>,
1445 threshold: u32,
1446 },
1447}
1448
1449enum MemberNeedle {
1450 Literal(Vec<u8>),
1451 Field(usize, Option<crate::member::RecordMember>),
1452}
1453
1454fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1457 match value {
1458 IndexValue::Text(text) => Some(text.as_bytes()),
1459 IndexValue::Blob(bytes) => Some(bytes),
1460 _ => None,
1461 }
1462}
1463
1464fn consecutive_values(low: IndexValue<'_>, high: IndexValue<'_>) -> bool {
1465 low.discrete_successor()
1466 .is_some_and(|next| equal_values(next, high))
1467}
1468
1469fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1470 match (left, right) {
1472 (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1473 a == b
1474 }
1475 _ => left == right,
1476 }
1477}
1478
1479fn length_limit(field: FieldType) -> Option<u32> {
1480 match key::operand_type(field) {
1481 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1482 FieldType::List { max_items, .. } => Some(max_items),
1483 FieldType::Named(link) => match (link.definition)().body {
1484 TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1485 _ => None,
1486 },
1487 _ => None,
1488 }
1489}
1490
1491fn member_type(field: FieldType) -> Option<FieldType> {
1492 match key::operand_type(field) {
1493 FieldType::List { item, .. } => Some(*item),
1494 FieldType::Named(link) => match (link.definition)().body {
1495 TypeBody::Set { item, .. } => Some(item),
1496 _ => None,
1497 },
1498 _ => None,
1499 }
1500}
1501
1502fn contains_member(
1504 span: &[u8],
1505 optional: bool,
1506 item: FieldType,
1507 needle: IndexValue<'_>,
1508) -> Result<bool, Error> {
1509 let mut reader = Decoder::new(span)?;
1510 if optional && !reader.boolean()? {
1511 return Ok(false);
1512 }
1513 for _ in 0..reader.nat32()? {
1514 let value = IndexValue::read(&mut reader, item)?;
1515 if equal_values(value, needle) {
1516 return Ok(true);
1517 }
1518 }
1519
1520 Ok(false)
1521}
1522
1523fn projection_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 projection_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 projection_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 projection_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 projection_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 if match value {
1665 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1666 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1667 _ => false,
1668 } {
1669 return Err(Error::Limit);
1670 }
1671 }
1672 let primary = entity
1673 .field_position(entity.primary_key)
1674 .filter(|&i| !entity.fields[i].optional)
1675 .ok_or(Error::InvalidQuery)?;
1676 let mut plan = Self {
1677 primary,
1678 index: None,
1679 prefix: prefix(2, entity.id, &[]),
1680 fixed_components: 0,
1681 terms: Vec::new(),
1682 selected: 1 << primary,
1683 span_fields: 0,
1684 binding: [0; 32],
1685 projection: projection.map(|output| output.mask(entity)).transpose()?,
1686 distinct: distinct::Strategy::Identity,
1687 sort: None,
1688 descending: request.descending ^ request.primary_descending(entity),
1689 };
1690 for predicate in &request.predicates {
1691 let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
1692 let field = &entity.fields[position];
1693 let member = if predicate.comparison == Comparison::Contains {
1694 member_type(field.value)
1695 } else {
1696 None
1697 };
1698 let operand = match (predicate.operand, record_member) {
1699 (QueryOperand::Literal(value), Some(member)) => {
1700 if !predicate.comparison.supports_record_member() {
1701 return Err(Error::InvalidQuery);
1702 }
1703 let leaf = member.field();
1704 predicate.comparison.admit(
1705 leaf.value,
1706 field.optional || leaf.optional,
1707 value,
1708 )?;
1709 let mut literal = Vec::new();
1710 value.append_component(field.optional || leaf.optional, &mut literal);
1711 plan.span_fields |= 1 << position;
1712 TermOperand::Nested {
1713 member,
1714 literal,
1715 absent: value == IndexValue::Absent,
1716 }
1717 }
1718 (QueryOperand::Length(length), member) => {
1719 let selected = member.map_or(field.value, |m| m.field().value);
1720 if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1721 return Err(Error::InvalidQuery);
1722 }
1723 plan.span_fields |= 1 << position;
1724
1725 TermOperand::Length {
1726 member,
1727 threshold: length,
1728 }
1729 }
1730 (QueryOperand::Field(name), left_member) => {
1731 let (right, right_member) = crate::member::resolve_field(entity, name)?;
1732 if (left_member.is_some() || right_member.is_some())
1733 && member.is_none()
1734 && !predicate.comparison.supports_record_member()
1735 {
1736 return Err(Error::InvalidQuery);
1737 }
1738 let right_type =
1739 right_member.map_or(entity.fields[right].value, |m| m.field().value);
1740 let left_type =
1741 left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1742 let compatible = left_type == right_type
1743 || matches!(
1744 (left_type, right_type),
1745 (FieldType::Text { .. }, FieldType::Text { .. })
1746 | (FieldType::Blob { .. }, FieldType::Blob { .. })
1747 );
1748 if !compatible
1749 || !key::supports(left_type)
1750 || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1751 {
1752 return Err(Error::InvalidQuery);
1753 }
1754 if right_member.is_some() {
1755 plan.span_fields |= 1 << right;
1756 } else {
1757 plan.selected |= 1 << right;
1758 }
1759
1760 if let Some(item) = member {
1761 plan.span_fields |= 1 << position;
1762
1763 TermOperand::Member {
1764 item,
1765 needle: MemberNeedle::Field(right, right_member),
1766 }
1767 } else {
1768 if left_member.is_some() {
1769 plan.span_fields |= 1 << position;
1770 } else {
1771 plan.selected |= 1 << position;
1772 }
1773 TermOperand::Field {
1774 right,
1775 left_member,
1776 right_member,
1777 }
1778 }
1779 }
1780 (QueryOperand::Literal(value), None) => {
1781 if let Some(item) = member {
1782 if !key::supports(item) {
1783 return Err(Error::InvalidQuery);
1784 }
1785 value.admit(item, false)?;
1786 let mut bytes = Vec::new();
1787 value.append_component(false, &mut bytes);
1788 plan.span_fields |= 1 << position;
1789
1790 TermOperand::Member {
1791 item,
1792 needle: MemberNeedle::Literal(bytes),
1793 }
1794 } else {
1795 let absent = value == IndexValue::Absent;
1796 if key::supports(field.value) {
1797 plan.selected |= 1 << position;
1798 } else if absent
1799 && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1800 {
1801 plan.span_fields |= 1 << position;
1802 } else {
1803 return Err(Error::InvalidQuery);
1804 }
1805 predicate
1806 .comparison
1807 .admit(field.value, field.optional, value)?;
1808 let mut bytes = Vec::new();
1809 value.append_component(field.optional, &mut bytes);
1810
1811 TermOperand::Literal { bytes, absent }
1812 }
1813 }
1814 };
1815 plan.terms.push(Term {
1816 tests_presence: predicate.tests_presence(entity, &operand),
1817 position,
1818 comparison: predicate.comparison,
1819 operand,
1820 or_next: predicate.or_next,
1821 });
1822 }
1823 match order::select(entity, request, output)? {
1826 order::Path::Primary => {}
1827 order::Path::Index(path, descending) => {
1828 plan.use_index(entity, path);
1829 plan.descending = request.descending ^ descending;
1830 }
1831 order::Path::Filtered { sort } => {
1832 order::select_filtered_path(entity, request, &mut plan, None)?;
1833 for field in sort.iter().flatten() {
1834 if field.member.is_some() {
1835 plan.span_fields |= 1 << field.position;
1836 } else {
1837 plan.selected |= 1 << field.position;
1838 }
1839 }
1840 plan.sort = sort;
1841 }
1842 }
1843 if request.distinct {
1844 plan.distinct = distinct::admit(entity, request, &plan)?;
1845 match plan.distinct {
1846 distinct::Strategy::FirstMatch => plan.sort = None,
1847 distinct::Strategy::Complete { key_fields } => plan.selected |= key_fields,
1848 _ => {}
1849 }
1850 }
1851 if matches!(output, PlanOutput::ImmediateCount)
1853 || (request.single_result_probe.is_some() && request.cursor.is_none())
1854 {
1855 return Ok(plan);
1856 }
1857 plan.bind_cursor(entity, request, schema, incarnation, projection)?;
1858
1859 Ok(plan)
1860 }
1861}
1862
1863fn consume_index_component(
1865 entity: &EntitySchema,
1866 index: &IndexSchema,
1867 name: &str,
1868 remaining: &mut &[u8],
1869) -> Result<(), Error> {
1870 let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
1871
1872 key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
1873}
1874
1875#[inline(never)]
1878#[expect(
1879 clippy::needless_pass_by_value,
1880 reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1881)]
1882fn fetch_rows<M: Memory>(
1883 db: &Database<M>,
1884 entity: &EntitySchema,
1885 request: Request<'_>,
1886 projection: Option<Projection<'_>>,
1887) -> Result<QueryPage<Vec<u8>>, Error> {
1888 db.schema.admits(entity)?;
1889 let plan = Plan::admit(
1890 entity,
1891 &request,
1892 db.schema.fingerprint(),
1893 db.incarnation,
1894 projection,
1895 PlanOutput::Rows,
1896 )?;
1897
1898 execute(&db.map, entity, &request, &plan, None)
1899}
1900
1901fn execute<M: Memory>(
1902 map: &Map<M>,
1903 entity: &EntitySchema,
1904 request: &Request<'_>,
1905 plan: &Plan<'_>,
1906 mut aggregate: Option<aggregate::Accumulator<'_>>,
1907) -> Result<QueryPage<Vec<u8>>, Error> {
1908 execute_inner(
1909 map,
1910 entity,
1911 request,
1912 plan,
1913 range::bounds(entity, request, plan)?,
1914 aggregate.as_mut(),
1915 None,
1916 )
1917}
1918
1919const STEP_INPUT_BYTES: usize = 64 * 1024;
1922const fn candidate_byte_limit(row_bytes: usize) -> usize {
1923 row_bytes + 2 * crate::MAX_INDEX_KEY_BYTES
1924}
1925
1926fn execute_inner<M: Memory>(
1927 map: &Map<M>,
1928 entity: &EntitySchema,
1929 request: &Request<'_>,
1930 plan: &Plan<'_>,
1931 bounds: Option<range::Bounds>,
1932 mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1933 mut input_bytes: Option<&mut usize>,
1934) -> Result<QueryPage<Vec<u8>>, Error> {
1935 let mut page = QueryPage {
1936 rows: Vec::new(),
1937 next: None,
1938 examined: 0,
1939 fetched: 0,
1940 output_bytes: 0,
1941 };
1942 let Some(bounds) = bounds else {
1943 return Ok(page);
1944 };
1945 let terminal = range::terminal_key(&bounds, plan.descending);
1946 let mut next_entry = range::entries(map, &bounds, plan.descending);
1947 let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
1948 Some(distinct::Collection::new(
1949 plan.projection.ok_or(Error::InvalidQuery)?,
1950 key_fields,
1951 ))
1952 } else {
1953 None
1954 };
1955 let mut sorted = plan
1956 .sort
1957 .as_ref()
1958 .map(|_| sort::Collection::new(request, plan.distinct));
1959 let mut component = Vec::new();
1960 let mut right_component = Vec::new();
1961 let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
1963 distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1964 } else {
1965 None
1966 };
1967 let candidate_bytes = candidate_byte_limit(entity.max_row_bytes);
1968 let primary_type = entity.fields[plan.primary].value;
1969 let needs_spans = plan.index.is_some()
1970 || plan.span_fields != 0
1971 || match &aggregate {
1972 Some(accumulator) => accumulator.needs_spans(),
1973 None => plan.projection.is_some(),
1974 };
1975 let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1977 let mut index_info = None;
1978 while let Some((stored_key, stored_value)) = next_entry() {
1979 if page.examined == request.work {
1982 return Err(Error::Limit);
1983 }
1984 page.examined += 1;
1985 let mut read_bytes = stored_key.len();
1986 let (owner, bytes) = if plan.index.is_some() {
1987 read_bytes += stored_value.len();
1988 read_index_owner(map, entity.id, primary_type, &stored_value)?
1989 } else {
1990 (
1991 RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
1992 stored_value,
1993 )
1994 };
1995 if let Some(used) = input_bytes.as_deref_mut() {
1996 read_bytes += bytes.len();
1997 if read_bytes > candidate_bytes {
1998 return Err(Error::Corrupt);
1999 }
2000 *used += read_bytes;
2001 }
2002 page.fetched += 1;
2003 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
2004 entity.inspect_fields(
2005 &bytes,
2006 plan.selected,
2007 &mut values,
2008 needs_spans.then_some(&mut spans),
2009 )?;
2010 let row_key = RowKey::from_index(values[plan.primary])?;
2011 if plan.index.is_some() {
2012 let info = index_info.get_or_insert_with(|| crate::__private::RowInfo::new(row_key));
2013 info.key = row_key;
2014 entity.fill_index_info(&values, &bytes, &spans, info)?;
2015 validate_index_entry(entity, info, owner, &stored_key)?;
2016 } else if row_key != owner {
2017 return Err(Error::Corrupt);
2018 }
2019 let matches = predicate::PredicateRow {
2020 entity,
2021 bytes: &bytes,
2022 values: &values,
2023 spans: &spans,
2024 span_fields: plan.span_fields,
2025 }
2026 .matches(
2027 &plan.terms,
2028 &request.predicates,
2029 &mut component,
2030 &mut right_component,
2031 )?;
2032 let boundary = distinct::boundary(entity, plan.index, plan.distinct, &stored_key)?;
2033 let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2034 if matches && let Some(accumulator) = aggregate.as_mut() {
2035 accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2036 if matches!(accumulator, aggregate::Accumulator::Until(remaining) if **remaining == 0) {
2037 return Ok(page);
2039 }
2040 } else if matches && let Some(collection) = collected.as_mut() {
2041 collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2042 if request.single_result_probe == Some(SingleResult::First) {
2044 break;
2045 }
2046 } else if matches && let Some(collection) = sorted.as_mut() {
2047 collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2048 request.check_result_count(collection.result_count())?;
2050 } else if matches && !duplicate {
2051 request.check_result_count(page.rows.len() + 1)?;
2052 let size = plan
2053 .projection
2054 .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2055 if size > request.bytes {
2056 return Err(Error::RowTooLarge);
2057 }
2058 if size > request.bytes - page.output_bytes {
2059 page.next = Some(plan.cursor(&stored_key, Resume::Retry));
2060
2061 return Ok(page);
2062 }
2063 page.output_bytes += size;
2064 if let Some(mask) = plan.projection {
2065 page.rows.push(copy_projection(&bytes, &spans, mask, size));
2066 } else {
2067 page.rows.push(bytes);
2068 }
2069 if request.single_result_probe == Some(SingleResult::First)
2070 || plan.distinct.finishes_on_match(plan.fixed_components)
2071 {
2072 return Ok(page);
2073 }
2074 if let Some(boundary) = boundary {
2075 previous = Some(boundary.to_vec());
2076 }
2077 }
2078 if page.rows.len() == request.rows
2079 || page.examined == request.work
2080 || input_bytes
2081 .as_deref()
2082 .is_some_and(|used| *used > STEP_INPUT_BYTES - candidate_bytes)
2083 {
2084 if terminal == Some(&stored_key) {
2085 break;
2086 }
2087 if request.single_result_probe.is_some()
2088 || (aggregate.is_some() && input_bytes.is_none())
2089 || collected.is_some()
2090 || sorted.is_some()
2091 {
2092 continue;
2095 }
2096 if input_bytes.is_some() && next_entry().is_none() {
2100 break;
2101 }
2102 let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
2103 Resume::AfterUnemittedClass
2104 } else {
2105 Resume::After
2106 };
2107 page.next = Some(plan.cursor(&stored_key, resume));
2108
2109 return Ok(page);
2110 }
2111 }
2112 if let Some(collection) = collected {
2113 page.output_bytes = collection.output_bytes;
2114 page.rows = collection.rows;
2115 }
2116 if let Some(collection) = sorted {
2117 collection.finish(request.bytes, &mut page)?;
2118 }
2119
2120 Ok(page)
2121}