mod aggregate;
mod distinct;
mod order;
mod range;
mod sort;
pub use aggregate::{
Aggregate, GroupCount, GroupOrder, GroupValue,
jobs::{AggregateJobs, GroupCursor, GroupPage, JobHandle, JobOutcome, JobStep},
};
use super::{
Database, ENTITY_PREFIX_BYTES, INDEX_PREFIX_BYTES, Map, prefix, row_key, validate_index_entry,
};
use crate::{
Entity, EntitySchema, Error, FieldType, IndexSchema, IndexValue, TypeBody, TypeSchema, Value,
codec::Decoder, key, primary::RowKey, types::TypeGraph,
};
use ic_storage::Memory;
use sha2::{Digest, Sha256};
use std::{
cell::{Ref, RefCell},
marker::PhantomData,
ops::Deref,
rc::Rc,
};
const MAX_TERMS: usize = 8;
const MAX_WORK: usize = 512;
const MAX_OUTPUT: usize = 128 * 1024;
const MAX_COMPARISON_KEY: usize = 4096;
const MAX_DISTINCT_VALUES: usize = 32;
const MAX_STATE_BYTES: usize = 128 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SortDirection {
Ascending,
Descending,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Comparison {
Eq = 0,
Ne = 1,
Lt = 2,
Le = 3,
Gt = 4,
Ge = 5,
StartsWith = 6,
EndsWith = 7,
Contains = 8,
}
impl Comparison {
fn is_relational(self) -> bool {
matches!(
self,
Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge
)
}
fn supports_scalar(self, field: FieldType) -> bool {
self.is_relational()
|| matches!(
key::operand_type(field),
FieldType::Text { .. } | FieldType::Blob { .. }
)
}
fn admit(self, field: FieldType, optional: bool, value: IndexValue<'_>) -> Result<(), Error> {
value.admit(field, optional)?;
if !self.supports_scalar(field) {
return Err(Error::InvalidQuery);
}
if value == IndexValue::Absent && !matches!(self, Self::Eq | Self::Ne) {
return Err(Error::InvalidOperand);
}
Ok(())
}
fn accepts(self, actual: Option<&[u8]>, operand: Option<&[u8]>, optional: bool) -> bool {
if actual.is_none() {
return self.accepts_absent(operand.is_none());
}
match self {
Self::Eq => actual == operand,
Self::Ne => actual != operand,
Self::StartsWith | Self::EndsWith | Self::Contains => {
fn content(key: &[u8], optional: bool) -> Option<&[u8]> {
key.get(usize::from(optional)..)?.strip_suffix(&[0, 0])
}
actual
.and_then(|key| content(key, optional))
.zip(operand.and_then(|key| content(key, optional)))
.is_some_and(|(actual, operand)| match self {
Self::StartsWith => actual.starts_with(operand),
Self::EndsWith => actual
.strip_suffix(operand)
.is_some_and(|prefix| prefix.last() != Some(&0)),
_ => contains_component(actual, operand),
})
}
_ if actual.is_none() || operand.is_none() => false,
Self::Lt => actual < operand,
Self::Le => actual <= operand,
Self::Gt => actual > operand,
Self::Ge => actual >= operand,
}
}
fn accepts_length(self, actual: Option<u32>, threshold: u32) -> bool {
let encoded = actual.map(u32::to_be_bytes);
self.accepts(
encoded.as_ref().map(|v| v.as_slice()),
Some(&threshold.to_be_bytes()),
false,
)
}
fn accepts_absent(self, other_absent: bool) -> bool {
match self {
Self::Eq => other_absent,
Self::Ne => !other_absent,
_ => false,
}
}
}
fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
let Some(start) = memchr::memmem::find(actual, needle) else {
return false;
};
if start == 0 || actual[start - 1] != 0 {
return true;
}
fn raw(content: &[u8]) -> Vec<u8> {
let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
let mut encoded = content.iter();
while let Some(&byte) = encoded.next() {
bytes.push(byte);
if byte == 0 {
encoded.next();
}
}
bytes
}
memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueryCursor {
binding: [u8; 32],
position: Vec<u8>,
inclusive: bool,
}
impl QueryCursor {
pub(super) const MAX_ENCODED_BYTES: usize = 34 + crate::MAX_INDEX_KEY_BYTES;
#[must_use]
pub fn to_bytes(&self) -> Vec<u8> {
let mut bytes = vec![1, u8::from(self.inclusive)];
bytes.extend(self.binding);
bytes.extend(&self.position);
bytes
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
if !(35..=Self::MAX_ENCODED_BYTES).contains(&bytes.len()) || bytes[0] != 1 || bytes[1] > 1 {
return Err(Error::InvalidCursor);
}
Ok(Self {
binding: bytes[2..34].try_into().map_err(|_| Error::InvalidCursor)?,
position: bytes[34..].to_vec(),
inclusive: bytes[1] == 1,
})
}
}
#[derive(Debug)]
pub struct QueryPage<T> {
pub rows: Vec<T>,
pub next: Option<QueryCursor>,
pub examined: usize,
pub fetched: usize,
pub output_bytes: usize,
}
impl QueryPage<Vec<u8>> {
#[inline(never)]
pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
Ok(QueryPage {
rows: self
.rows
.iter()
.map(|bytes| E::decode(bytes))
.collect::<Result<_, _>>()?,
next: self.next,
examined: self.examined,
fetched: self.fetched,
output_bytes: self.output_bytes,
})
}
#[inline(never)]
fn decode_projection<R: Value>(self) -> Result<QueryPage<R>, Error> {
Ok(QueryPage {
rows: self
.rows
.iter()
.map(|bytes| {
let mut reader = Decoder::new(bytes)?;
let row = R::decode_from(&mut reader)?;
reader.finish()?;
Ok(row)
})
.collect::<Result<_, Error>>()?,
next: self.next,
examined: self.examined,
fetched: self.fetched,
output_bytes: self.output_bytes,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QueryOperand<'a> {
Literal(IndexValue<'a>),
Length(u32),
Field(&'a str),
}
struct Predicate<'a> {
field: &'a str,
comparison: Comparison,
operand: QueryOperand<'a>,
or_next: bool,
}
struct Request<'a> {
groups: aggregate::GroupRequest<'a>,
predicates: Vec<Predicate<'a>>,
index: Option<(&'a str, Vec<IndexValue<'a>>)>,
order: Option<Vec<&'a str>>,
order_descending: u8,
descending: bool,
distinct: bool,
rows: usize,
work: usize,
bytes: usize,
cursor: Option<&'a QueryCursor>,
over_limit: bool,
}
impl Default for Request<'_> {
fn default() -> Self {
Self {
groups: aggregate::GroupRequest::default(),
predicates: Vec::new(),
index: None,
order: None,
order_descending: 0,
descending: false,
distinct: false,
rows: 32,
work: 128,
bytes: MAX_OUTPUT,
cursor: None,
over_limit: false,
}
}
}
impl<'a> Request<'a> {
fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
self.predicates.split_inclusive(|p| !p.or_next)
}
#[inline(never)]
fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
if self.predicates.len() == MAX_TERMS {
self.over_limit = true;
} else {
self.predicates.push(Predicate {
field,
comparison,
operand,
or_next: false,
});
}
}
#[inline(never)]
fn or_clause(
&mut self,
alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
) {
let count = alternatives.len();
if count == 0 || count > MAX_TERMS - self.predicates.len() {
self.over_limit = true;
} else {
self.predicates.extend(alternatives.enumerate().map(
|(i, (field, comparison, operand))| Predicate {
field,
comparison,
operand,
or_next: i + 1 < count,
},
));
}
}
#[inline(never)]
fn filter_not_in(
&mut self,
field: &'a str,
values: impl ExactSizeIterator<Item = IndexValue<'a>>,
) {
if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
self.over_limit = true;
return;
}
for value in values {
self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
}
}
#[inline(never)]
fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
if values.len() > 4 {
self.over_limit = true;
} else {
self.index = Some((name, values.to_vec()));
}
}
#[inline(never)]
fn order_by(&mut self, fields: &[&'a str]) {
self.order_descending = 0;
if fields.len() > 4 {
self.over_limit = true;
} else {
self.order = Some(fields.to_vec());
}
}
#[inline(never)]
fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
if fields.len() > 4 {
self.over_limit = true;
return;
}
self.order = Some(Vec::with_capacity(fields.len()));
self.order_descending = 0;
for &(field, direction) in fields {
self.append_order(field, direction);
}
}
fn append_order(&mut self, field: &'a str, direction: SortDirection) {
let fields = self.order.get_or_insert_with(Vec::new);
if fields.len() == 4 {
self.over_limit = true;
return;
}
if direction == SortDirection::Descending {
self.order_descending |= 1 << fields.len();
}
fields.push(field);
}
fn primary_descending(&self, entity: &EntitySchema) -> bool {
self.order_descending != 0
&& self.order.as_ref().is_some_and(|fields| {
fields.last() == Some(&entity.primary_key)
&& self.order_descending & (1 << (fields.len() - 1)) != 0
})
}
}
pub(super) fn source_page<M: Memory>(
map: &Map<M>,
entity: &EntitySchema,
binding: [u8; 32],
incarnation: [u8; 16],
cursor: Option<&QueryCursor>,
rows: usize,
bytes: usize,
) -> Result<QueryPage<Vec<u8>>, Error> {
let request = Request {
rows,
work: rows,
bytes,
cursor,
..Request::default()
};
let plan = Plan::admit(
entity,
&request,
binding,
incarnation,
None,
PlanOutput::Rows,
)?;
execute(map, entity, &request, &plan, None)
}
enum QuerySource<'a, M: Memory> {
Direct(&'a Database<M>),
Session(Rc<RefCell<Database<M>>>),
}
enum QueryRead<'a, M: Memory> {
Direct(&'a Database<M>),
Session(Ref<'a, Database<M>>),
}
impl<M: Memory> Deref for QueryRead<'_, M> {
type Target = Database<M>;
fn deref(&self) -> &Self::Target {
match self {
Self::Direct(db) => db,
Self::Session(db) => db,
}
}
}
impl<M: Memory> QuerySource<'_, M> {
fn read(&self) -> Result<QueryRead<'_, M>, Error> {
match self {
Self::Direct(db) => Ok(QueryRead::Direct(db)),
Self::Session(db) => db
.try_borrow()
.map(QueryRead::Session)
.map_err(|_| Error::BorrowConflict),
}
}
}
pub struct Query<'a, E, M: Memory> {
db: QuerySource<'a, M>,
request: Request<'a>,
entity: PhantomData<E>,
}
impl<M: Memory> Database<M> {
#[must_use]
pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
Query {
db: QuerySource::Direct(self),
entity: PhantomData,
request: Request::default(),
}
}
}
impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
Self {
db: QuerySource::Session(db),
request: Request::default(),
entity: PhantomData,
}
}
#[must_use]
pub fn distinct(mut self) -> Self {
self.request.distinct = true;
self
}
#[must_use]
pub fn filter(
mut self,
field: &'a str,
comparison: Comparison,
value: impl Into<IndexValue<'a>>,
) -> Self {
self.request
.filter(field, comparison, QueryOperand::Literal(value.into()));
self
}
#[must_use]
pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
self.filter(field, Comparison::Eq, value)
}
#[must_use]
pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
self.filter(field, Comparison::Ne, value)
}
#[must_use]
pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
self.filter(field, Comparison::Lt, value)
}
#[must_use]
pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
self.filter(field, Comparison::Le, value)
}
#[must_use]
pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
self.filter(field, Comparison::Gt, value)
}
#[must_use]
pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
self.filter(field, Comparison::Ge, value)
}
#[must_use]
pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
self.request
.filter(left, comparison, QueryOperand::Field(right));
self
}
#[must_use]
pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
self.request
.filter(field, comparison, QueryOperand::Length(length));
self
}
#[must_use]
pub fn filter_present(self, field: &'a str) -> Self {
self.filter(field, Comparison::Ne, IndexValue::Absent)
}
#[must_use]
pub fn filter_absent(self, field: &'a str) -> Self {
self.filter(field, Comparison::Eq, IndexValue::Absent)
}
#[must_use]
pub fn filter_between(
self,
field: &'a str,
lower: impl Into<IndexValue<'a>>,
upper: impl Into<IndexValue<'a>>,
) -> Self {
self.filter(field, Comparison::Ge, lower)
.filter(field, Comparison::Le, upper)
}
#[must_use]
pub fn filter_not_between(
self,
field: &'a str,
lower: impl Into<IndexValue<'a>>,
upper: impl Into<IndexValue<'a>>,
) -> Self {
self.filter_any(&[
(field, Comparison::Lt, lower.into()),
(field, Comparison::Gt, upper.into()),
])
}
#[must_use]
pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
self.filter_fields(field, Comparison::Ge, lower)
.filter_fields(field, Comparison::Le, upper)
}
#[must_use]
pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
self.filter_any_operands(&[
(field, Comparison::Lt, QueryOperand::Field(lower)),
(field, Comparison::Gt, QueryOperand::Field(upper)),
])
}
#[must_use]
pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
self.request.or_clause(
alternatives
.iter()
.map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
);
self
}
#[must_use]
pub fn filter_any_operands(
mut self,
alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
) -> Self {
self.request.or_clause(alternatives.iter().copied());
self
}
#[must_use]
pub fn filter_in(
mut self,
field: &'a str,
values: &[impl Copy + Into<IndexValue<'a>>],
) -> Self {
self.request.or_clause(
values
.iter()
.copied()
.map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
);
self
}
#[must_use]
pub fn filter_not_in(
mut self,
field: &'a str,
values: &[impl Copy + Into<IndexValue<'a>>],
) -> Self {
self.request
.filter_not_in(field, values.iter().copied().map(Into::into));
self
}
#[must_use]
pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
self.request.using_index(name, values);
self
}
#[must_use]
pub fn order_asc(mut self, field: &'a str) -> Self {
self.request.append_order(field, SortDirection::Ascending);
self
}
#[must_use]
pub fn order_desc(mut self, field: &'a str) -> Self {
self.request.append_order(field, SortDirection::Descending);
self
}
#[must_use]
pub fn order_by(mut self, fields: &[&'a str]) -> Self {
self.request.order_by(fields);
self
}
#[must_use]
pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
self.request.order_by_each(fields);
self
}
#[must_use]
pub fn descending(mut self) -> Self {
self.request.descending = true;
self
}
#[must_use]
pub fn limit(mut self, rows: usize) -> Self {
self.request.rows = rows;
self
}
#[must_use]
pub fn work_limit(mut self, candidates: usize) -> Self {
self.request.work = candidates;
self
}
#[cfg(feature = "test-support")]
#[doc(hidden)]
#[must_use]
pub fn test_output_limit(mut self, bytes: usize) -> Self {
self.request.bytes = bytes;
self
}
#[must_use]
pub fn after(mut self, cursor: &'a QueryCursor) -> Self {
self.request.cursor = Some(cursor);
self
}
pub fn fetch(self) -> Result<QueryPage<E>, Error> {
fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
}
pub fn first(self) -> Result<Option<E>, Error> {
let mut page = self.probe_matches(1)?;
match page.rows.pop() {
None if page.next.is_some() => Err(Error::Limit),
result => Ok(result),
}
}
pub fn try_one(self) -> Result<Option<E>, Error> {
if self.request.cursor.is_some() {
return Err(Error::InvalidQuery);
}
let mut page = self.probe_matches(2)?;
if page.rows.len() == 2 {
return Err(Error::MultipleMatches);
}
if page.next.is_some() {
return Err(Error::Limit);
}
Ok(page.rows.pop())
}
fn probe_matches(self, rows: usize) -> Result<QueryPage<E>, Error> {
if !(1..=32).contains(&self.request.rows) {
return Err(Error::Limit);
}
self.limit(rows).fetch()
}
pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
let raw = fetch_rows(
&*self.db.read()?,
E::SCHEMA,
self.request,
Some(R::definition()),
)?;
raw.decode_projection()
}
}
fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u16, Error> {
let TypeBody::Record(fields) = &output.body else {
return Err(Error::InvalidQuery);
};
if fields.is_empty()
|| fields.len() > crate::schema::MAX_FIELDS
|| fields.windows(2).any(|w| w[0].name >= w[1].name)
{
return Err(Error::InvalidQuery);
}
let mut source = TypeGraph::default();
let mut target = TypeGraph::default();
let mut mask = 0;
for field in *fields {
let position = entity
.field_position(field.name)
.ok_or(Error::InvalidQuery)?;
let stored = &entity.fields[position];
if stored.value != field.value || stored.optional != field.optional {
return Err(Error::InvalidQuery);
}
source
.include(stored.value)
.map_err(|_| Error::InvalidQuery)?;
target
.include(field.value)
.map_err(|_| Error::InvalidQuery)?;
mask |= 1 << position;
}
if !source.contains(&target) {
return Err(Error::InvalidQuery);
}
Ok(mask)
}
struct Term {
position: usize,
comparison: Comparison,
operand: TermOperand,
or_next: bool,
}
enum TermOperand {
Literal {
bytes: Vec<u8>,
absent: bool,
},
Member {
item: FieldType,
needle: MemberNeedle,
},
Field(usize),
Length(u32),
}
enum MemberNeedle {
Literal(Vec<u8>),
Field(usize),
}
fn member_type(field: FieldType) -> Option<FieldType> {
match key::operand_type(field) {
FieldType::List { item, .. } => Some(*item),
FieldType::Named(link) => match (link.definition)().body {
TypeBody::Set { item, .. } => Some(item),
_ => None,
},
_ => None,
}
}
fn contains_member(
span: &[u8],
optional: bool,
item: FieldType,
needle: &[u8],
scratch: &mut Vec<u8>,
) -> Result<bool, Error> {
let mut reader = Decoder::new(span)?;
if optional && !reader.boolean()? {
return Ok(false);
}
for _ in 0..reader.nat32()? {
scratch.clear();
IndexValue::read(&mut reader, item)?.append_component(false, scratch);
if scratch.as_slice() == needle {
return Ok(true);
}
}
Ok(false)
}
fn admit_ordered_fields(entity: &EntitySchema, mask: u16) -> Result<(), Error> {
for (i, field) in entity.fields.iter().enumerate() {
if mask & (1 << i) != 0 && !key::supports(field.value) {
return Err(Error::InvalidQuery);
}
}
Ok(())
}
fn comparison_key(
entity: &EntitySchema,
mask: u16,
values: &[IndexValue<'_>],
) -> Result<Vec<u8>, Error> {
let mut key = Vec::new();
for (i, field) in entity.fields.iter().enumerate() {
if mask & (1 << i) != 0 {
values[i].append_component(field.optional, &mut key);
if key.len() > MAX_COMPARISON_KEY {
return Err(Error::Limit);
}
}
}
Ok(key)
}
fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
if size > limit {
return Err(Error::RowTooLarge);
}
if size > limit - *used {
return Err(Error::Limit);
}
*used += size;
Ok(())
}
fn projection_size(spans: &[(u16, u16)], mask: u16) -> usize {
spans
.iter()
.enumerate()
.filter(|(i, _)| mask & (1 << i) != 0)
.map(|(_, (start, end))| usize::from(end - start))
.sum()
}
fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u16, size: usize) -> Vec<u8> {
let mut output = Vec::with_capacity(size);
for (i, &(start, end)) in spans.iter().enumerate() {
if mask & (1 << i) != 0 {
output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
}
}
output
}
#[derive(Clone, Copy)]
enum PlanOutput {
Rows,
Aggregate { grouped: bool },
}
struct Plan<'a> {
primary: usize,
index: Option<&'a IndexSchema>,
prefix: Vec<u8>,
fixed_components: usize,
terms: Vec<Term>,
selected: u16,
span_fields: u16,
binding: [u8; 32],
projection: Option<u16>,
distinct: distinct::Strategy,
sort: Option<Vec<(usize, bool)>>,
descending: bool,
}
impl<'a> Plan<'a> {
fn clauses(&self) -> impl Iterator<Item = &[Term]> {
self.terms.split_inclusive(|term| !term.or_next)
}
fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
self.index = Some(path.index);
self.prefix = path.prefix;
self.fixed_components = path.fixed;
self.selected |= entity.key_fields();
}
fn admit(
entity: &'a EntitySchema,
request: &Request<'_>,
schema: [u8; 32],
incarnation: [u8; 16],
projection: Option<&TypeSchema>,
output: PlanOutput,
) -> Result<Self, Error> {
if request.over_limit
|| !(1..=32).contains(&request.rows)
|| !(1..=MAX_WORK).contains(&request.work)
|| !(1..=MAX_OUTPUT).contains(&request.bytes)
{
return Err(Error::Limit);
}
if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
{
return Err(Error::InvalidQuery);
}
for value in request
.predicates
.iter()
.filter_map(|p| match &p.operand {
QueryOperand::Literal(value) => Some(value),
QueryOperand::Field(_) | QueryOperand::Length(_) => None,
})
.chain(request.index.iter().flat_map(|(_, values)| values.iter()))
{
if match value {
IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
_ => false,
} {
return Err(Error::Limit);
}
}
let primary = entity
.field_position(entity.primary_key)
.filter(|&i| !entity.fields[i].optional)
.ok_or(Error::InvalidQuery)?;
let mut plan = Self {
primary,
index: None,
prefix: prefix(2, entity.id),
fixed_components: 0,
terms: Vec::new(),
selected: 1 << primary,
span_fields: 0,
binding: [0; 32],
projection: projection
.map(|output| admit_projection(entity, output))
.transpose()?,
distinct: distinct::Strategy::Identity,
sort: None,
descending: request.descending ^ request.primary_descending(entity),
};
for predicate in &request.predicates {
let position = entity
.field_position(predicate.field)
.ok_or(Error::InvalidQuery)?;
let field = &entity.fields[position];
let member = if predicate.comparison == Comparison::Contains {
member_type(field.value)
} else {
None
};
let operand = match predicate.operand {
QueryOperand::Length(length) => {
let supported = match key::operand_type(field.value) {
FieldType::Text { .. }
| FieldType::Blob { .. }
| FieldType::List { .. } => true,
FieldType::Named(link) => matches!(
(link.definition)().body,
TypeBody::Map { .. } | TypeBody::Set { .. }
),
_ => false,
};
if !supported || !predicate.comparison.is_relational() {
return Err(Error::InvalidQuery);
}
plan.span_fields |= 1 << position;
TermOperand::Length(length)
}
QueryOperand::Field(name) => {
let right = entity.field_position(name).ok_or(Error::InvalidQuery)?;
let right_type = entity.fields[right].value;
let left_type = member.unwrap_or(field.value);
let compatible = left_type == right_type
|| matches!(
(left_type, right_type),
(FieldType::Text { .. }, FieldType::Text { .. })
| (FieldType::Blob { .. }, FieldType::Blob { .. })
);
if !compatible
|| !key::supports(left_type)
|| (member.is_none() && !predicate.comparison.supports_scalar(left_type))
{
return Err(Error::InvalidQuery);
}
plan.selected |= 1 << right;
if let Some(item) = member {
plan.span_fields |= 1 << position;
TermOperand::Member {
item,
needle: MemberNeedle::Field(right),
}
} else {
plan.selected |= 1 << position;
TermOperand::Field(right)
}
}
QueryOperand::Literal(value) => {
if let Some(item) = member {
if !key::supports(item) {
return Err(Error::InvalidQuery);
}
value.admit(item, false)?;
let mut bytes = Vec::new();
value.append_component(false, &mut bytes);
plan.span_fields |= 1 << position;
TermOperand::Member {
item,
needle: MemberNeedle::Literal(bytes),
}
} else {
let absent = value == IndexValue::Absent;
if key::supports(field.value) {
plan.selected |= 1 << position;
} else if absent
&& matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
{
plan.span_fields |= 1 << position;
} else {
return Err(Error::InvalidQuery);
}
predicate
.comparison
.admit(field.value, field.optional, value)?;
let mut bytes = Vec::new();
value.append_component(field.optional, &mut bytes);
TermOperand::Literal { bytes, absent }
}
}
};
plan.terms.push(Term {
position,
comparison: predicate.comparison,
operand,
or_next: predicate.or_next,
});
}
match order::select(entity, request, output)? {
order::Path::Primary => {}
order::Path::Index(path) => plan.use_index(entity, path),
order::Path::Sort(fields) => {
for &(position, _) in &fields {
plan.selected |= 1 << position;
}
plan.sort = Some(fields);
}
}
if request.distinct {
plan.distinct = distinct::admit(
entity,
request,
plan.projection,
plan.index,
plan.fixed_components,
plan.sort.is_some(),
)?;
if plan.distinct == distinct::Strategy::Complete {
plan.selected |= plan.projection.ok_or(Error::InvalidQuery)?;
}
}
let mut hash = Sha256::new();
hash.update(b"ic-db:query:v1\0");
hash.update(schema);
hash.update(incarnation);
hash.update([u8::from(request.descending)]);
hash.update((plan.prefix.len() as u32).to_le_bytes());
hash.update(&plan.prefix);
for term in &plan.terms {
hash.update([term.position as u8, term.comparison as u8]);
match &term.operand {
TermOperand::Literal { bytes, .. }
| TermOperand::Member {
needle: MemberNeedle::Literal(bytes),
..
} => {
hash.update((bytes.len() as u32).to_le_bytes());
hash.update(bytes);
}
TermOperand::Length(length) => {
hash.update((u32::MAX - 1).to_le_bytes());
hash.update(length.to_le_bytes());
}
TermOperand::Field(right)
| TermOperand::Member {
needle: MemberNeedle::Field(right),
..
} => {
hash.update(u32::MAX.to_le_bytes());
hash.update([*right as u8]);
}
}
}
let clauses = plan
.terms
.iter()
.enumerate()
.fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
if clauses != 0 {
hash.update(b"or-clauses\0");
hash.update([clauses]);
}
if let Some(order) = &request.order {
hash.update(b"order\0");
hash.update([order.len() as u8]);
for name in order {
hash.update([entity.field_position(name).ok_or(Error::InvalidQuery)? as u8]);
}
}
if request.order_descending != 0 {
hash.update(b"order-directions\0");
hash.update([request.order_descending]);
}
if let Some(mask) = plan.projection {
hash.update(b"projection\0");
hash.update(mask.to_le_bytes());
}
if request.distinct {
hash.update(b"distinct\0");
}
plan.binding = hash.finalize().into();
if let Some(cursor) = request.cursor {
if cursor.binding != plan.binding {
return Err(Error::InvalidCursor);
}
plan.validate_position(entity, &cursor.position)
.map_err(|_| Error::InvalidCursor)?;
}
Ok(plan)
}
fn validate_position(&self, entity: &EntitySchema, bytes: &[u8]) -> Result<(), Error> {
if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
return Err(Error::InvalidCursor);
}
if let Some(index) = self.index {
let mut remaining = bytes
.get(INDEX_PREFIX_BYTES..)
.ok_or(Error::InvalidCursor)?;
for name in index.fields {
consume_index_component(entity, index, name, &mut remaining)?;
}
if !index.unique {
key::consume(&mut remaining, entity.key_type()?)?;
}
if !remaining.is_empty() {
return Err(Error::InvalidCursor);
}
} else {
RowKey::decode(
bytes
.get(ENTITY_PREFIX_BYTES..)
.ok_or(Error::InvalidCursor)?,
entity.key_type()?,
)?;
}
Ok(())
}
fn cursor(&self, position: &[u8], inclusive: bool) -> QueryCursor {
QueryCursor {
binding: self.binding,
position: position.to_vec(),
inclusive,
}
}
}
fn consume_index_component(
entity: &EntitySchema,
index: &IndexSchema,
name: &str,
remaining: &mut &[u8],
) -> Result<(), Error> {
let field = entity.field_by_name(name).ok_or(Error::InvalidQuery)?;
key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
}
#[inline(never)]
#[expect(
clippy::needless_pass_by_value,
reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
)]
fn fetch_rows<M: Memory>(
db: &Database<M>,
entity: &EntitySchema,
request: Request<'_>,
projection: Option<&TypeSchema>,
) -> Result<QueryPage<Vec<u8>>, Error> {
db.schema.admits(entity)?;
let plan = Plan::admit(
entity,
&request,
db.schema.fingerprint(),
db.incarnation,
projection,
PlanOutput::Rows,
)?;
execute(&db.map, entity, &request, &plan, None)
}
fn execute<M: Memory>(
map: &Map<M>,
entity: &EntitySchema,
request: &Request<'_>,
plan: &Plan<'_>,
mut aggregate: Option<aggregate::Accumulator<'_>>,
) -> Result<QueryPage<Vec<u8>>, Error> {
execute_inner(map, entity, request, plan, aggregate.as_mut(), None)
}
const STEP_INPUT_BYTES: usize = 64 * 1024;
const CANDIDATE_BYTES: usize = crate::codec::MAX_ROW_BYTES + 2 * crate::MAX_INDEX_KEY_BYTES;
fn execute_inner<M: Memory>(
map: &Map<M>,
entity: &EntitySchema,
request: &Request<'_>,
plan: &Plan<'_>,
mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
mut input_bytes: Option<&mut usize>,
) -> Result<QueryPage<Vec<u8>>, Error> {
let mut page = QueryPage {
rows: Vec::new(),
next: None,
examined: 0,
fetched: 0,
output_bytes: 0,
};
let Some(bounds) = range::bounds(entity, request, plan)? else {
return Ok(page);
};
let terminal = range::terminal_key(&bounds, plan.descending);
let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
let mut collected = if plan.distinct == distinct::Strategy::Complete {
Some(distinct::Collection::new(
plan.projection.ok_or(Error::InvalidQuery)?,
))
} else {
None
};
let mut sorted = plan
.sort
.as_ref()
.map(|_| sort::Collection::new(request, plan.distinct));
let mut component = Vec::new();
let mut right_component = Vec::new();
let mut previous = if let Some(cursor) = request.cursor.filter(|c| !c.inclusive) {
distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
} else {
None
};
let primary_type = entity.fields[plan.primary].value;
while let Some(entry) = if plan.descending {
entries.next_back()
} else {
entries.next()
} {
if request.work == 0 {
return Err(Error::Limit);
}
page.examined += 1;
let stored_key = entry.key();
let mut read_bytes = stored_key.len();
let (owner, bytes) = if plan.index.is_some() {
let owner_bytes = entry.value();
read_bytes += owner_bytes.len();
let owner = RowKey::decode(&owner_bytes, primary_type)?;
let bytes = map.get(&row_key(entity.id, owner)).ok_or(Error::Corrupt)?;
(owner, bytes)
} else {
(
RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
entry.value(),
)
};
if let Some(used) = input_bytes.as_deref_mut() {
read_bytes += bytes.len();
if read_bytes > CANDIDATE_BYTES {
return Err(Error::Corrupt);
}
*used += read_bytes;
}
page.fetched += 1;
let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
entity.inspect_fields(
&bytes,
plan.selected,
&mut values,
(plan.span_fields != 0
|| plan.projection.is_some()
|| aggregate.as_ref().is_some_and(|a| a.needs_spans()))
.then_some(&mut spans),
)?;
if RowKey::from_index(values[plan.primary])? != owner {
return Err(Error::Corrupt);
}
if plan.index.is_some() {
validate_index_entry(entity, &entity.row_info(&values)?, owner, stored_key)?;
}
let mut accepts = |term: &Term| -> Result<bool, Error> {
let value = values[term.position];
component.clear();
let (operand, optional) = match &term.operand {
TermOperand::Literal { absent: true, .. }
if plan.span_fields & (1 << term.position) != 0 =>
{
let absent = bytes[usize::from(spans[term.position].0)] == 0;
return Ok(term.comparison.accepts_absent(absent));
}
TermOperand::Member { item, needle } => {
let needle = match needle {
MemberNeedle::Literal(bytes) => bytes.as_slice(),
MemberNeedle::Field(right) => {
let value = values[*right];
if value == IndexValue::Absent {
return Ok(false);
}
right_component.clear();
value.append_component(false, &mut right_component);
&right_component
}
};
let (start, end) = spans[term.position];
return contains_member(
&bytes[usize::from(start)..usize::from(end)],
entity.fields[term.position].optional,
*item,
needle,
&mut component,
);
}
TermOperand::Length(length) => {
let (start, end) = spans[term.position];
let span = &bytes[usize::from(start)..usize::from(end)];
let actual =
crate::codec::validated_length(span, entity.fields[term.position].optional);
return Ok(term.comparison.accepts_length(actual, *length));
}
TermOperand::Literal { bytes, absent } => (
(!absent).then_some(bytes.as_slice()),
entity.fields[term.position].optional,
),
TermOperand::Field(right) => {
let rhs = values[*right];
right_component.clear();
rhs.append_component(false, &mut right_component);
(
(rhs != IndexValue::Absent).then_some(right_component.as_slice()),
false,
)
}
};
value.append_component(optional, &mut component);
Ok(term.comparison.accepts(
(value != IndexValue::Absent).then_some(component.as_slice()),
operand,
optional,
))
};
let matches = 'matches: {
'clause: for clause in plan.clauses() {
for term in clause {
if accepts(term)? {
continue 'clause;
}
}
break 'matches false;
}
true
};
let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
if matches && let Some(accumulator) = aggregate.as_mut() {
accumulator.push(entity, &values, &bytes, &spans)?;
if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
return Ok(page);
}
} else if matches && let Some(collection) = collected.as_mut() {
collection.push(entity, request, &values, &bytes, &spans)?;
} else if matches && let Some(collection) = sorted.as_mut() {
collection.push(entity, plan, &values, &bytes, &spans)?;
} else if matches && !duplicate {
let size = plan
.projection
.map_or(bytes.len(), |mask| projection_size(&spans, mask));
if size > request.bytes {
return Err(Error::RowTooLarge);
}
if size > request.bytes - page.output_bytes {
page.next = Some(plan.cursor(stored_key, true));
return Ok(page);
}
page.output_bytes += size;
if let Some(mask) = plan.projection {
page.rows.push(copy_projection(&bytes, &spans, mask, size));
} else {
page.rows.push(bytes);
}
if let Some(boundary) = boundary {
previous = Some(boundary.to_vec());
}
}
if page.rows.len() == request.rows
|| page.examined == request.work
|| input_bytes
.as_deref()
.is_some_and(|used| *used > STEP_INPUT_BYTES - CANDIDATE_BYTES)
{
if terminal == Some(stored_key) {
break;
}
if (aggregate.is_some() && input_bytes.is_none())
|| collected.is_some()
|| sorted.is_some()
{
return Err(Error::Limit);
}
page.next = Some(plan.cursor(stored_key, false));
return Ok(page);
}
}
if let Some(collection) = collected {
page.output_bytes = collection.output_bytes;
page.rows = collection.rows;
}
if let Some(collection) = sorted {
collection.finish(request.bytes, &mut page)?;
}
Ok(page)
}