#[cfg(test)]
mod tests;
use crate::db::{
access::AccessPlan,
direction::Direction,
query::plan::{
AccessPlannedQuery, FieldSlot, OrderDirection, OrderSpec,
expr::{ProjectionSpec, projection_field_direct_field_name},
},
};
use crate::{model::entity::EntityModel, value::Value};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) enum CoveringProjectionOrder {
IndexOrder(Direction),
PrimaryKeyOrder(Direction),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) struct CoveringProjectionContext {
pub(in crate::db) component_index: usize,
pub(in crate::db) prefix_len: usize,
pub(in crate::db) order_contract: CoveringProjectionOrder,
}
#[cfg_attr(not(test), allow(dead_code))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) enum CoveringReadFieldSource {
IndexComponent { component_index: usize },
PrimaryKey,
Constant(Value),
}
#[cfg_attr(not(test), allow(dead_code))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) struct CoveringReadField {
pub(in crate::db) field_slot: FieldSlot,
pub(in crate::db) source: CoveringReadFieldSource,
}
#[cfg_attr(not(test), allow(dead_code))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) struct CoveringReadPlan {
pub(in crate::db) fields: Vec<CoveringReadField>,
pub(in crate::db) prefix_len: usize,
pub(in crate::db) order_contract: CoveringProjectionOrder,
}
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) enum CoveringExistingRowMode {
ProvenByPlanner,
RequiresRowPresenceCheck,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) struct CoveringReadExecutionPlan {
pub(in crate::db) fields: Vec<CoveringReadField>,
pub(in crate::db) prefix_len: usize,
pub(in crate::db) order_contract: CoveringProjectionOrder,
pub(in crate::db) existing_row_mode: CoveringExistingRowMode,
}
#[must_use]
pub(in crate::db) fn index_covering_existing_rows_terminal_eligible(
plan: &AccessPlannedQuery,
strict_predicate_compatible: bool,
) -> bool {
if plan.scalar_plan().order.is_some() {
return false;
}
let index_shape_supported =
plan.access.as_index_prefix_path().is_some() || plan.access.as_index_range_path().is_some();
if !index_shape_supported {
return false;
}
if plan.scalar_plan().predicate.is_none() {
return true;
}
strict_predicate_compatible
}
#[must_use]
#[cfg_attr(not(test), allow(dead_code))]
pub(in crate::db) fn covering_read_plan(
model: &EntityModel,
plan: &AccessPlannedQuery,
primary_key_name: &'static str,
strict_predicate_compatible: bool,
) -> Option<CoveringReadPlan> {
if plan.grouped_plan().is_some() || !plan.scalar_plan().mode.is_load() {
return None;
}
if plan.has_residual_predicate() && !strict_predicate_compatible {
return None;
}
let metadata = covering_access_metadata(&plan.access)?;
let order_contract = covering_projection_order_contract(
plan.scalar_plan().order.as_ref(),
metadata.index_fields,
metadata.prefix_len,
primary_key_name,
metadata.path_kind_is_range,
)?;
let projection = plan.projection_spec(model);
let fields = covering_read_fields_from_projection(
model,
&projection,
metadata.index_fields,
primary_key_name,
&plan.access,
)?;
if fields.is_empty() {
return None;
}
Some(CoveringReadPlan {
fields,
prefix_len: metadata.prefix_len,
order_contract,
})
}
#[must_use]
pub(in crate::db) fn covering_read_execution_plan(
model: &EntityModel,
plan: &AccessPlannedQuery,
primary_key_name: &'static str,
strict_predicate_compatible: bool,
) -> Option<CoveringReadExecutionPlan> {
if let Some(covering) =
covering_read_plan(model, plan, primary_key_name, strict_predicate_compatible)
{
return Some(CoveringReadExecutionPlan {
fields: covering.fields,
prefix_len: covering.prefix_len,
order_contract: covering.order_contract,
existing_row_mode: CoveringExistingRowMode::RequiresRowPresenceCheck,
});
}
primary_store_covering_execution_plan(model, plan, primary_key_name)
}
#[must_use]
pub(in crate::db) fn covering_index_projection_context<K>(
access: &AccessPlan<K>,
order: Option<&OrderSpec>,
target_field: &str,
primary_key_name: &'static str,
) -> Option<CoveringProjectionContext> {
let metadata = covering_access_metadata(access)?;
let component_index = metadata
.index_fields
.iter()
.position(|field| *field == target_field)?;
let order_contract = covering_projection_order_contract(
order,
metadata.index_fields,
metadata.prefix_len,
primary_key_name,
metadata.path_kind_is_range,
)?;
Some(CoveringProjectionContext {
component_index,
prefix_len: metadata.prefix_len,
order_contract,
})
}
#[must_use]
pub(in crate::db) fn constant_covering_projection_value_from_access<K>(
access: &AccessPlan<K>,
target_field: &str,
) -> Option<Value> {
let metadata = covering_access_metadata(access)?;
constant_covering_projection_value_from_prefix(
metadata.index_fields,
metadata.prefix_values,
target_field,
)
}
#[must_use]
pub(in crate::db) const fn covering_index_adjacent_distinct_eligible(
context: CoveringProjectionContext,
) -> bool {
matches!(
context.order_contract,
CoveringProjectionOrder::IndexOrder(_)
) && context.component_index == context.prefix_len
}
fn covering_projection_order_contract(
order: Option<&OrderSpec>,
index_fields: &[&'static str],
prefix_len: usize,
primary_key_name: &'static str,
path_kind_is_range: bool,
) -> Option<CoveringProjectionOrder> {
let Some(order) = order else {
return Some(CoveringProjectionOrder::PrimaryKeyOrder(Direction::Asc));
};
if let Some(direction) = order.primary_key_only_direction(primary_key_name) {
let direction = match direction {
OrderDirection::Asc => Direction::Asc,
OrderDirection::Desc => Direction::Desc,
};
return Some(CoveringProjectionOrder::PrimaryKeyOrder(direction));
}
let direction = match order.deterministic_secondary_order_direction(primary_key_name)? {
OrderDirection::Asc => Direction::Asc,
OrderDirection::Desc => Direction::Desc,
};
if order.matches_index_suffix_plus_primary_key(index_fields, prefix_len, primary_key_name) {
return Some(CoveringProjectionOrder::IndexOrder(direction));
}
if path_kind_is_range {
return None;
}
order
.matches_index_full_plus_primary_key(index_fields, primary_key_name)
.then_some(CoveringProjectionOrder::IndexOrder(direction))
}
fn primary_store_covering_execution_plan(
model: &EntityModel,
plan: &AccessPlannedQuery,
primary_key_name: &'static str,
) -> Option<CoveringReadExecutionPlan> {
if plan.grouped_plan().is_some()
|| !plan.scalar_plan().mode.is_load()
|| plan.scalar_plan().distinct
|| plan.has_residual_predicate()
{
return None;
}
let existing_row_mode = primary_store_covering_existing_row_mode(&plan.access)?;
let order_contract = covering_projection_order_contract(
plan.scalar_plan().order.as_ref(),
&[],
0,
primary_key_name,
false,
)?;
let fields = covering_read_fields_from_projection(
model,
&plan.projection_spec(model),
&[],
primary_key_name,
&plan.access,
)?;
if fields.is_empty() {
return None;
}
if fields
.iter()
.any(|field| !matches!(field.source, CoveringReadFieldSource::PrimaryKey))
{
return None;
}
if !primary_store_covering_order_supported(&plan.access, order_contract) {
return None;
}
Some(CoveringReadExecutionPlan {
fields,
prefix_len: 0,
order_contract,
existing_row_mode,
})
}
fn constant_covering_projection_value_from_prefix(
index_fields: &[&'static str],
prefix_values: &[Value],
target_field: &str,
) -> Option<Value> {
index_fields
.iter()
.zip(prefix_values.iter())
.find_map(|(field, value)| (*field == target_field).then(|| value.clone()))
}
struct CoveringAccessMetadata<'a> {
index_fields: &'a [&'static str],
prefix_values: &'a [Value],
prefix_len: usize,
path_kind_is_range: bool,
}
fn covering_access_metadata<K>(access: &AccessPlan<K>) -> Option<CoveringAccessMetadata<'_>> {
if let Some((index, values)) = access.as_index_prefix_path() {
return Some(CoveringAccessMetadata {
index_fields: index.fields(),
prefix_values: values,
prefix_len: values.len(),
path_kind_is_range: false,
});
}
if let Some((index, prefix_values, _, _)) = access.as_index_range_path() {
return Some(CoveringAccessMetadata {
index_fields: index.fields(),
prefix_values,
prefix_len: prefix_values.len(),
path_kind_is_range: true,
});
}
None
}
fn primary_store_covering_existing_row_mode<K>(
access: &AccessPlan<K>,
) -> Option<CoveringExistingRowMode> {
let path = access.as_path()?;
if path.is_primary_store_authoritative_scan() {
return Some(CoveringExistingRowMode::ProvenByPlanner);
}
path.is_primary_key_lookup()
.then_some(CoveringExistingRowMode::RequiresRowPresenceCheck)
}
fn primary_store_covering_order_supported<K>(
access: &AccessPlan<K>,
order_contract: CoveringProjectionOrder,
) -> bool {
let Some(path) = access.as_path() else {
return false;
};
if path.is_primary_store_authoritative_scan() {
return true;
}
if path.is_by_key() {
return matches!(order_contract, CoveringProjectionOrder::PrimaryKeyOrder(_));
}
path.as_by_keys().is_some_and(|_| {
matches!(
order_contract,
CoveringProjectionOrder::PrimaryKeyOrder(Direction::Asc)
)
})
}
#[cfg_attr(not(test), allow(dead_code))]
fn covering_read_fields_from_projection(
model: &EntityModel,
projection: &ProjectionSpec,
index_fields: &[&'static str],
primary_key_name: &'static str,
access: &AccessPlan<Value>,
) -> Option<Vec<CoveringReadField>> {
let mut fields = Vec::with_capacity(projection.len());
for projection_field in projection.fields() {
let field_name = projection_field_direct_field_name(projection_field)?;
let field_slot = FieldSlot::resolve(model, field_name)?;
let source =
covering_read_field_source(field_name, index_fields, primary_key_name, access)?;
fields.push(CoveringReadField { field_slot, source });
}
Some(fields)
}
#[cfg_attr(not(test), allow(dead_code))]
fn covering_read_field_source(
field_name: &str,
index_fields: &[&'static str],
primary_key_name: &'static str,
access: &AccessPlan<Value>,
) -> Option<CoveringReadFieldSource> {
if field_name == primary_key_name {
return Some(CoveringReadFieldSource::PrimaryKey);
}
if let Some(value) = constant_covering_projection_value_from_access(access, field_name) {
return Some(CoveringReadFieldSource::Constant(value));
}
index_fields
.iter()
.position(|field| *field == field_name)
.map(|component_index| CoveringReadFieldSource::IndexComponent { component_index })
}