use super::super::*;
use super::aggregate::NativeAggregateHost;
use super::*;
use crate::runtime::record_search::{JOIN_LEFT_AGGREGATE_INPUTS, JOIN_RIGHT_AGGREGATE_INPUTS};
use reddb_engine::query::evaluator::{EvalError, Row};
use reddb_engine::query::labels::projection_name;
use reddb_engine::query::parameters::visit_expr;
use reddb_engine::query::runtime::aggregation::{
aggregate_projection_result_with_host, aggregate_value_to_f64, base_function_name,
build_aggregate_group_key, CompiledAggPlan, ProjSlot, SlottedAggState,
};
use reddb_engine::query::runtime::text::RegexCache;
use reddb_rql::ast::{BinOp, UnaryOp};
use reddb_rql::sql_lowering::{
aggregate_filter_projection, case_condition_projection, effective_join_filter,
effective_join_projections, projection_to_expr, select_item_to_projection,
};
use std::cell::Cell;
#[path = "join_having.rs"]
mod having;
use having::JoinHaving;
pub(crate) fn execute_runtime_join_query(
runtime: &RedDBRuntime,
query: &JoinQuery,
) -> RedDBResult<UnifiedResult> {
let records = execute_runtime_canonical_join_query(runtime, query)?;
let effective_projections = effective_join_projections(query);
let columns = projected_columns(&records, &effective_projections);
Ok(UnifiedResult {
columns,
records,
stats: Default::default(),
pre_serialized_json: None,
})
}
pub(crate) fn execute_runtime_canonical_join_query(
runtime: &RedDBRuntime,
query: &JoinQuery,
) -> RedDBResult<Vec<UnifiedRecord>> {
validate_projection_functions(&query.return_items)?;
let db = &runtime.inner.db;
let plan = CanonicalPlanner::new(db).build(&QueryExpr::Join(query.clone()));
execute_runtime_canonical_join_node(runtime, &plan.root, query)
}
pub(crate) fn execute_runtime_canonical_join_node(
runtime: &RedDBRuntime,
node: &crate::storage::query::planner::CanonicalLogicalNode,
query: &JoinQuery,
) -> RedDBResult<Vec<UnifiedRecord>> {
let db = &runtime.inner.db;
let (left_table_name, left_table_alias, right_table_name, right_table_alias) =
runtime_join_table_context(query);
match node.operator.as_str() {
"filter" => {
let mut records = execute_runtime_canonical_join_child(runtime, node, query)?;
if let Some(filter) = effective_join_filter(query).as_ref() {
records.retain(|record| {
evaluate_runtime_join_filter_with_db(
Some(db),
record,
filter,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
});
}
Ok(records)
}
"join_aggregate" => {
let projections = effective_join_projections(query);
let arguments = join_aggregate_arguments(query, &projections)?;
let output = JoinGroupOutput::compile(query, &projections)?;
let records = execute_runtime_canonical_join_child(runtime, node, query)?;
aggregate_join_records(db, query, &projections, &arguments, &output, &records)
}
"sort" | "document_sort" | "entity_sort" => {
let mut records = execute_runtime_canonical_join_child(runtime, node, query)?;
if !query.order_by.is_empty() {
records.sort_by(|left, right| {
compare_runtime_join_order_with_db(
Some(db),
left,
right,
&query.order_by,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
});
} else if node.operator == "entity_sort" {
records.sort_by(compare_runtime_ranked_records);
}
Ok(records)
}
"offset" => {
let records = execute_runtime_canonical_join_child(runtime, node, query)?;
let offset = query.offset.unwrap_or(0) as usize;
Ok(records.into_iter().skip(offset).collect())
}
"limit" => {
let records = execute_runtime_canonical_join_child(runtime, node, query)?;
let limit = query.limit.map(|value| value as usize);
Ok(match limit {
Some(limit) => records.into_iter().take(limit).collect(),
None => records,
})
}
"projection" => {
let records = execute_runtime_canonical_join_child(runtime, node, query)?;
let effective_projections = effective_join_projections(query);
records
.iter()
.map(|record| {
project_runtime_join_record_with_db(
Some(db),
record,
&effective_projections,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
})
.collect()
}
"join" => execute_runtime_canonical_join_base(
runtime,
node,
query,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
),
other => Err(RedDBError::Query(format!(
"unsupported canonical join operator {other}"
))),
}
}
#[derive(Default)]
struct JoinAggregateInput {
value: Option<Expr>,
filter: Option<Expr>,
}
impl JoinAggregateInput {
fn expressions(&self) -> impl Iterator<Item = &Expr> {
self.value.iter().chain(&self.filter)
}
}
fn join_aggregate_arguments(
query: &JoinQuery,
projections: &[Projection],
) -> RedDBResult<Vec<JoinAggregateInput>> {
let mut items = query
.return_items
.iter()
.filter(|item| select_item_to_projection(item).is_some());
projections
.iter()
.map(|projection| {
let item = items.next();
if !query.group_by.is_empty()
&& matches!(
projection,
Projection::Field(FieldRef::TableColumn { .. }, _)
)
{
return Ok(JoinAggregateInput::default());
}
let expression = match item {
Some(SelectItem::Expr {
expr: Expr::FunctionCall { args, .. },
..
}) => args.first(),
_ => None,
};
join_aggregate_argument(projection, expression)
})
.collect()
}
fn join_aggregate_argument(
projection: &Projection,
expression: Option<&Expr>,
) -> RedDBResult<JoinAggregateInput> {
if let Projection::Function(name, args) = projection {
let (inputs, filter) = aggregate_filter_projection(args)
.map_or((args.as_slice(), None), |(inputs, predicate)| {
(inputs, Some(predicate.clone()))
});
let name = base_function_name(name);
match (name, inputs) {
("COUNT", [Projection::All]) => {
return Ok(JoinAggregateInput {
value: None,
filter,
})
}
(_, [argument])
if matches!(name, "SUM" | "AVG" | "SUM_DISTINCT")
|| (name == "COUNT" && filter.is_some()) =>
{
let expression = expression
.cloned()
.or_else(|| projection_to_expr(argument).map(|(expr, _)| expr));
if let Some(expression) = expression.and_then(join_arithmetic_expression) {
return Ok(JoinAggregateInput {
value: Some(expression),
filter,
});
}
}
_ => {}
}
}
Err(RedDBError::Query(
"join aggregates support grouping columns, COUNT(*) and SUM, SUM(DISTINCT) or AVG of a numeric expression"
.into(),
))
}
fn join_arithmetic_expression(expression: Expr) -> Option<Expr> {
match expression {
Expr::Literal { value, .. } => Some(Expr::lit(value)),
Expr::Column { field, .. } if matches!(&field, FieldRef::TableColumn { column, .. } if column != "*") => {
Some(Expr::col(field))
}
Expr::UnaryOp {
op: UnaryOp::Neg,
operand,
..
} => Some(Expr::UnaryOp {
op: UnaryOp::Neg,
operand: Box::new(join_arithmetic_expression(*operand)?),
span: reddb_rql::ast::Span::synthetic(),
}),
Expr::BinaryOp { op, lhs, rhs, .. }
if matches!(
op,
BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod
) =>
{
Some(Expr::binop(
op,
join_arithmetic_expression(*lhs)?,
join_arithmetic_expression(*rhs)?,
))
}
_ => None,
}
}
fn join_aggregate_fields(
arguments: &[JoinAggregateInput],
group_by: &[FieldRef],
output: &JoinGroupOutput<'_>,
) -> HashMap<FieldRef, usize> {
let mut fields = HashMap::new();
for field in group_by
.iter()
.chain(output.column_references().map(|column| column.field))
{
let next = fields.len();
fields.entry(field.clone()).or_insert(next);
}
for argument in output
.arguments(arguments)
.flat_map(JoinAggregateInput::expressions)
{
visit_expr(argument, &mut |expr| {
if let Expr::Column { field, .. } = expr {
let next = fields.len();
fields.entry(field.clone()).or_insert(next);
}
});
}
fields
}
struct JoinGroupColumn<'a> {
field: &'a FieldRef,
index: usize,
}
enum JoinGroupOrder<'a> {
Key(JoinGroupColumn<'a>),
Projection(usize),
}
struct JoinGroupOutput<'a> {
keys: Vec<Option<JoinGroupColumn<'a>>>,
order: Vec<JoinGroupOrder<'a>>,
having: Option<JoinHaving<'a>>,
}
impl<'a> JoinGroupOutput<'a> {
fn compile(query: &'a JoinQuery, projections: &'a [Projection]) -> RedDBResult<Self> {
let mut output = Self {
keys: Vec::new(),
order: Vec::new(),
having: None,
};
if query.group_by.is_empty() {
if query.having.is_some() {
return Err(RedDBError::Query(
"HAVING on joins requires GROUP BY".into(),
));
}
return Ok(output);
}
if !matches!(query.left.as_ref(), QueryExpr::Table(_))
|| !matches!(query.right.as_ref(), QueryExpr::Table(_))
{
return Err(RedDBError::Query(
"GROUP BY on joins requires two table inputs".into(),
));
}
let group_column = |field: &'a FieldRef| {
query
.group_by
.iter()
.position(|key| key == field)
.or_else(|| {
let FieldRef::TableColumn { table, column } = field else {
return None;
};
query.group_by.iter().position(|key| {
matches!(key, FieldRef::TableColumn { table: key_table, column: key_column }
if column == key_column && (table.is_empty() || key_table.is_empty()))
})
})
.map(|index| JoinGroupColumn { field, index })
.ok_or_else(|| {
let label = reddb_engine::query::labels::field_ref_name(field);
RedDBError::Query(format!(
"join aggregate column {label} must appear in GROUP BY or be an aggregate"
))
})
};
let labels: Vec<_> = projections.iter().map(projection_name).collect();
if let Some(having) = &query.having {
output.having = Some(JoinHaving::compile(
having,
&group_column,
projections.len(),
)?);
}
for projection in projections {
let key = match projection {
Projection::Field(field, _) => Some(group_column(field)?),
_ => None,
};
output.keys.push(key);
}
for clause in &query.order_by {
let ordinal = |position: i64| {
usize::try_from(position)
.ok()
.and_then(|position| position.checked_sub(1))
.filter(|index| *index < projections.len())
.map(JoinGroupOrder::Projection)
.ok_or_else(|| {
RedDBError::Query(format!(
"ORDER BY position {position} is not in the select list"
))
})
};
let key = match &clause.expr {
Some(Expr::Literal {
value: Value::Integer(position),
..
}) => ordinal(*position)?,
Some(Expr::UnaryOp {
op: UnaryOp::Neg,
operand,
..
}) if matches!(
operand.as_ref(),
Expr::Literal {
value: Value::Integer(_),
..
}
) =>
{
let Expr::Literal {
value: Value::Integer(position),
..
} = operand.as_ref()
else {
unreachable!("matched a negative ORDER BY position");
};
ordinal(position.saturating_neg())?
}
None => {
let mut matches = labels.iter().enumerate().filter(|(_, label)| {
matches!(&clause.field, FieldRef::TableColumn { table, column }
if table.is_empty() && column == *label)
});
if let Some((index, label)) = matches.next() {
if matches.next().is_some() {
return Err(RedDBError::Query(format!(
"join aggregate column {label} is ambiguous"
)));
}
JoinGroupOrder::Projection(index)
} else {
JoinGroupOrder::Key(group_column(&clause.field)?)
}
}
_ => return Err(RedDBError::Query(
"ORDER BY on grouped joins requires a group column, SELECT alias, or position"
.into(),
)),
};
output.order.push(key);
}
Ok(output)
}
fn column_references(&self) -> impl Iterator<Item = &JoinGroupColumn<'a>> {
self.keys
.iter()
.flatten()
.chain(self.order.iter().filter_map(|order| match order {
JoinGroupOrder::Key(column) => Some(column),
JoinGroupOrder::Projection(_) => None,
}))
.chain(self.having.iter().flat_map(JoinHaving::group_columns))
}
fn arguments<'b>(
&'b self,
visible: &'b [JoinAggregateInput],
) -> impl Iterator<Item = &'b JoinAggregateInput> {
visible
.iter()
.chain(self.having.iter().flat_map(|having| &having.arguments))
}
}
struct JoinAggregateRow<'a> {
fields: &'a HashMap<FieldRef, usize>,
inputs: [&'a [Value]; 2],
sensitive: Cell<bool>,
regex_cache: &'a RegexCache,
}
impl Row for JoinAggregateRow<'_> {
fn get(&self, field: &FieldRef) -> Option<Value> {
self.try_get(field).ok().flatten()
}
fn regex_cache(&self) -> Option<&RegexCache> {
Some(self.regex_cache)
}
fn try_get(&self, field: &FieldRef) -> Result<Option<Value>, EvalError> {
let Some(index) = self.fields.get(field) else {
return Ok(None);
};
let value = self
.inputs
.iter()
.filter_map(|values| values.get(*index))
.find(|value| !value.is_null())
.cloned()
.unwrap_or(Value::Null);
if matches!(&value, Value::Secret(_)) {
self.sensitive.set(true);
}
super::super::execution_context::try_secret_query_input(value)
.map(|value| Some(value.unwrap_or(Value::Null)))
.map_err(|limit| EvalError::ReadLimitExceeded {
required_bytes: limit.required_bytes,
limit_bytes: limit.limit_bytes,
})
}
}
struct JoinAggregateGroup {
values: Vec<Value>,
sensitive_keys: Vec<bool>,
state: SlottedAggState,
sensitive: Vec<bool>,
integer_sums: Vec<Option<i128>>,
}
impl JoinAggregateGroup {
fn new(plan: &CompiledAggPlan, values: Vec<Value>, sensitive: &[bool]) -> Self {
let state = SlottedAggState::new(plan);
Self {
sensitive_keys: vec![false; values.len()],
values,
sensitive: sensitive.to_vec(),
integer_sums: vec![Some(0); state.sums.len()],
state,
}
}
}
fn join_integer_average(total: i128, count: u64) -> Value {
if count == 0 {
return Value::Null;
}
let leading_group = |mut number: u128| {
let mut weight = 0_i32;
while number >= 10_000 {
number /= 10_000;
weight += 1;
}
(weight, number)
};
let magnitude = total.unsigned_abs();
let count = u128::from(count);
let (sum_weight, sum_digit) = leading_group(magnitude);
let (count_weight, count_digit) = leading_group(count);
let quotient_weight = sum_weight - count_weight - i32::from(sum_digit <= count_digit);
let scale = (16 - 4 * quotient_weight).max(0) as usize;
let mut whole = magnitude / count;
let mut remainder = magnitude % count;
let mut fraction = 0_u128;
for _ in 0..scale {
remainder *= 10;
fraction = fraction * 10 + remainder / count;
remainder %= count;
}
if remainder * 2 >= count {
fraction += 1;
if fraction == 10_u128.pow(scale as u32) {
whole += 1;
fraction = 0;
}
}
let sign = if total < 0 && (whole != 0 || fraction != 0) {
"-"
} else {
""
};
if scale == 0 {
Value::DecimalText(format!("{sign}{whole}"))
} else {
Value::DecimalText(format!("{sign}{whole}.{fraction:0scale$}"))
}
}
fn aggregate_join_records(
db: &RedDB,
query: &JoinQuery,
projections: &[Projection],
arguments: &[JoinAggregateInput],
output: &JoinGroupOutput<'_>,
records: &[UnifiedRecord],
) -> RedDBResult<Vec<UnifiedRecord>> {
let typed_projections: Vec<_> = projections
.iter()
.chain(output.having.iter().flat_map(|having| &having.aggregates))
.zip(output.arguments(arguments))
.map(|(projection, input)| match (projection, &input.value) {
(Projection::Function(name, args), Some(value)) => {
let mut args = args.clone();
args[0] = case_condition_projection(value.clone());
Projection::Function(name.clone(), args)
}
_ => projection.clone(),
})
.collect();
let plan = CompiledAggPlan::compile(&typed_projections).ok_or_else(|| {
RedDBError::Query("join aggregate projections are too deeply nested".into())
})?;
let numeric_slots = plan
.proj_slots
.iter()
.filter(|slot| matches!(slot, ProjSlot::SumCount(_)))
.count();
let count_slots = plan
.proj_slots
.iter()
.filter(|slot| matches!(slot, ProjSlot::CountOnly(_)))
.count();
let sum_distinct_slots = plan
.proj_slots
.iter()
.filter(|slot| matches!(slot, ProjSlot::SumDistinct(_)))
.count();
let sum_distinct_offset = numeric_slots + count_slots;
let sensitivity_index = |slot: &ProjSlot| match *slot {
ProjSlot::SumCount(index) => Some(index),
ProjSlot::CountOnly(index) => Some(numeric_slots + index),
ProjSlot::SumDistinct(index) => Some(sum_distinct_offset + index),
_ => None,
};
let mut sensitive = vec![false; sum_distinct_offset + sum_distinct_slots];
for (slot, input) in plan.proj_slots.iter().zip(output.arguments(arguments)) {
if let Some(index) = sensitivity_index(slot) {
for argument in input.expressions() {
visit_expr(argument, &mut |expr| {
sensitive[index] |= matches!(
expr,
Expr::Literal {
value: Value::Secret(_),
..
}
);
});
}
}
}
let fields = join_aggregate_fields(arguments, &query.group_by, output);
let grouped = !query.group_by.is_empty();
let mut scalar = JoinAggregateGroup::new(&plan, Vec::new(), &sensitive);
let mut groups = HashMap::new();
let group_limit = if grouped {
crate::runtime::materialization_limit::max_materialized_rows(db)?
} else {
usize::MAX
};
let inputs = if !grouped && sensitive.is_empty() {
scalar.state.count = records.len() as u64;
&[]
} else {
records
};
let regex_cache = RegexCache::default();
for record in inputs {
let inputs = [JOIN_LEFT_AGGREGATE_INPUTS, JOIN_RIGHT_AGGREGATE_INPUTS].map(|key| {
match record.get(key) {
Some(Value::Array(values)) => values.as_slice(),
_ => &[],
}
});
let row = JoinAggregateRow {
fields: &fields,
inputs,
sensitive: Cell::new(false),
regex_cache: ®ex_cache,
};
let group = if grouped {
let keys = query
.group_by
.iter()
.map(|field| {
row.sensitive.set(false);
row.try_get(field)
.map(|value| (value.unwrap_or(Value::Null), row.sensitive.get()))
.map_err(|error| RedDBError::Query(error.to_string()))
})
.collect::<RedDBResult<Vec<_>>>()?;
let (values, sensitivity): (Vec<_>, Vec<_>) = keys.into_iter().unzip();
let key = build_aggregate_group_key(&values);
let next = groups.len() + 1;
let group = match groups.entry(key) {
std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
std::collections::hash_map::Entry::Vacant(entry) => {
crate::runtime::materialization_limit::check("aggregation", next, group_limit)?;
entry.insert(JoinAggregateGroup::new(&plan, values, &sensitive))
}
};
for (sensitive, key_sensitive) in group.sensitive_keys.iter_mut().zip(sensitivity) {
*sensitive |= key_sensitive;
}
group
} else {
&mut scalar
};
group.state.count += 1;
for (slot, input) in plan.proj_slots.iter().zip(output.arguments(arguments)) {
let Some(index) = sensitivity_index(slot) else {
continue;
};
row.sensitive.set(false);
let mut evaluate = |expression: &Expr| {
let value = super::super::expr_eval::evaluate_typed_expr_with_secret_literals(
expression, &row,
);
group.sensitive[index] |= row.sensitive.get();
value.map_err(|error| {
RedDBError::Query(
if group.sensitive[index]
&& !matches!(error, EvalError::ReadLimitExceeded { .. })
{
"secret expression evaluation failed".into()
} else {
error.to_string()
},
)
})
};
if let Some(predicate) = &input.filter {
if !super::super::join_filter::aggregate_filter_accepts(Some(evaluate(predicate)?))?
{
continue;
}
}
let value = input
.value
.as_ref()
.map(evaluate)
.transpose()?
.unwrap_or(Value::Boolean(true));
if let ProjSlot::SumCount(index) = *slot {
if let Some(total) = &mut group.integer_sums[index] {
match value {
Value::Integer(value) | Value::BigInt(value) => *total += i128::from(value),
Value::UnsignedInteger(value) => *total += i128::from(value),
_ if aggregate_value_to_f64(&value).is_some() => {
group.integer_sums[index] = None
}
_ => {}
}
}
}
group.state.accumulate(&NativeAggregateHost, slot, value);
}
}
let mut records = Vec::with_capacity(if grouped { groups.len() } else { 1 });
for group in groups.into_values().chain((!grouped).then_some(scalar)) {
let mut values = Vec::with_capacity(typed_projections.len());
for (position, typed) in typed_projections.iter().enumerate() {
let (value, sensitive) = if let Some(Some(key)) = output.keys.get(position) {
(
group.values[key.index].clone(),
group.sensitive_keys[key.index],
)
} else {
let (_, mut value) = aggregate_projection_result_with_host(
&NativeAggregateHost,
typed,
&group.state,
&plan,
)
.expect("validated join aggregate has a result slot");
let mut sensitive = false;
if let Projection::Function(name, args) = typed {
let func = base_function_name(name);
if func == "COUNT" {
if let Some(index) = plan.count_slot(args) {
sensitive = group.sensitive[numeric_slots + index];
}
} else if func == "SUM_DISTINCT" {
if let Some(index) = plan.sum_distinct_slot(args) {
sensitive = group.sensitive[sum_distinct_offset + index];
}
} else if let Some(index) = plan.sum_count_slot(args) {
if let Some(total) = group.integer_sums[index] {
match func {
"SUM" if !value.is_null() => {
value = i64::try_from(total)
.map(Value::Integer)
.unwrap_or_else(|_| Value::DecimalText(total.to_string()))
}
"AVG" => {
value = join_integer_average(
total,
group.state.sum_agg_counts[index],
)
}
_ => {}
}
}
sensitive = group.sensitive[index];
}
}
(value, sensitive)
};
values.push((value, sensitive));
}
if let Some(having) = &output.having {
if !having.matches(&group, &values)? {
continue;
}
}
let mut record = UnifiedRecord::new();
for (projection, (value, sensitive)) in projections.iter().zip(&values) {
let output_value = if *sensitive {
super::super::execution_context::secret_query_output(value.clone())?
} else {
value.clone()
};
record.set(&projection_name(projection), output_value);
}
let sort_keys: Vec<_> = output
.order
.iter()
.map(|key| match key {
JoinGroupOrder::Key(column) => group.values[column.index].clone(),
JoinGroupOrder::Projection(index) => values[*index].0.clone(),
})
.collect();
records.push((record, sort_keys));
}
if !output.order.is_empty() {
records.sort_by(|(_, left), (_, right)| {
for ((left, right), clause) in left.iter().zip(right).zip(&query.order_by) {
let order = compare_runtime_optional_values(
Some(left),
Some(right),
clause.nulls_first == clause.ascending,
);
if order != Ordering::Equal {
return if clause.ascending {
order
} else {
order.reverse()
};
}
}
Ordering::Equal
});
}
Ok(records.into_iter().map(|(record, _)| record).collect())
}
fn attach_join_aggregate_columns(
fields: &HashMap<FieldRef, usize>,
group_by: &[FieldRef],
output: &JoinGroupOutput<'_>,
db: &RedDB,
mut inputs: [(&mut [UnifiedRecord], Option<&str>, Option<&str>); 2],
) -> RedDBResult<()> {
let contracts = inputs
.each_ref()
.map(|(_, name, _)| name.and_then(|name| db.collection_contract_arc(name)));
let mut bound = [vec![None; fields.len()], vec![None; fields.len()]];
for (field, index) in fields {
let FieldRef::TableColumn { table, column } = field else {
return Err(RedDBError::Query(
"join aggregate expressions require table columns".into(),
));
};
let has_column = |side: usize| {
contracts[side].as_ref().is_some_and(|contract| {
contract
.declared_columns
.iter()
.any(|declared| declared.name == *column)
}) || inputs[side]
.0
.iter()
.any(|record| record.contains_column(column))
};
let matching = if table.is_empty() {
std::array::from_fn(has_column)
} else {
inputs
.each_ref()
.map(|(_, name, alias)| runtime_table_context_matches(table, *name, *alias))
};
let side = match matching {
[true, false] => 0,
[false, true] => 1,
[true, true] => {
return Err(RedDBError::Query(format!(
"join aggregate column {column} is ambiguous"
)))
}
[false, false] => {
return Err(RedDBError::Query(format!(
"join aggregate column {column} does not exist"
)))
}
};
if contracts[side]
.as_ref()
.is_some_and(|contract| !contract.declared_columns.is_empty())
&& !has_column(side)
{
return Err(RedDBError::Query(format!(
"join aggregate column {column} does not exist"
)));
}
bound[side][*index] = Some(column.as_str());
}
for column in output.column_references() {
let projected = fields[column.field];
let grouped = fields[&group_by[column.index]];
if !bound
.iter()
.any(|side| side[projected].is_some() && side[projected] == side[grouped])
{
let label = reddb_engine::query::labels::field_ref_name(column.field);
return Err(RedDBError::Query(format!(
"join aggregate column {label} must appear in GROUP BY or be an aggregate"
)));
}
}
let keys = [JOIN_LEFT_AGGREGATE_INPUTS, JOIN_RIGHT_AGGREGATE_INPUTS];
for (side, (records, _, _)) in inputs.iter_mut().enumerate() {
let has_inputs = bound[side].iter().any(Option::is_some);
for record in records.iter_mut() {
if keys.iter().any(|key| record.contains_column(key)) {
return Err(RedDBError::Query(
"join input uses a reserved aggregate column".into(),
));
}
let values = if has_inputs {
bound[side]
.iter()
.map(|column| {
column
.and_then(|column| record.get(column))
.cloned()
.unwrap_or(Value::Null)
})
.collect()
} else {
Vec::new()
};
record.set(keys[side], Value::Array(values));
}
}
Ok(())
}
pub(crate) fn execute_runtime_canonical_join_base(
runtime: &RedDBRuntime,
node: &crate::storage::query::planner::CanonicalLogicalNode,
query: &JoinQuery,
left_table_name: Option<&str>,
left_table_alias: Option<&str>,
right_table_name: Option<&str>,
right_table_alias: Option<&str>,
) -> RedDBResult<Vec<UnifiedRecord>> {
if node.children.len() != 2 {
return Err(RedDBError::Query(
"canonical join operator must contain exactly two child plans".to_string(),
));
}
let join_type = canonical_join_type(node)?;
let left_join_field = canonical_join_field(node, "left_field")?;
let right_join_field = canonical_join_field(node, "right_field")?;
let join_strategy = canonical_join_strategy(node)?;
let synthetic_left_query;
let left_query = match query.left.as_ref() {
QueryExpr::Table(table) => table,
QueryExpr::Join(_) => {
synthetic_left_query = TableQuery::new("");
&synthetic_left_query
}
_ => {
return Err(RedDBError::Query(
"runtime joins currently require a table expression on the left side".to_string(),
))
}
};
let mut left_records =
execute_runtime_canonical_expr_node(runtime, &node.children[0], query.left.as_ref())?;
let mut right_records =
execute_runtime_canonical_expr_node(runtime, &node.children[1], query.right.as_ref())?;
let projections = effective_join_projections(query);
if !query.group_by.is_empty()
|| query.having.is_some()
|| has_aggregate_projections(&projections)
{
let arguments = join_aggregate_arguments(query, &projections)?;
let output = JoinGroupOutput::compile(query, &projections)?;
if !query.group_by.is_empty()
|| arguments
.iter()
.any(|input| input.expressions().next().is_some())
{
attach_join_aggregate_columns(
&join_aggregate_fields(&arguments, &query.group_by, &output),
&query.group_by,
&output,
&runtime.inner.db,
[
(&mut left_records, left_table_name, left_table_alias),
(&mut right_records, right_table_name, right_table_alias),
],
)?;
}
}
let join_strategy = if matches!(join_strategy, CanonicalJoinStrategy::NestedLoop)
&& left_records.len() * right_records.len() > 10_000
{
CanonicalJoinStrategy::HashJoin
} else {
join_strategy
};
match join_strategy {
CanonicalJoinStrategy::IndexedNestedLoop => execute_runtime_indexed_join(
left_query,
&left_records,
left_table_name,
left_table_alias,
&left_join_field,
&right_records,
right_table_name,
right_table_alias,
&right_join_field,
join_type,
),
CanonicalJoinStrategy::HashJoin => execute_runtime_hash_join(
left_query,
&left_records,
left_table_name,
left_table_alias,
&left_join_field,
&right_records,
right_table_name,
right_table_alias,
&right_join_field,
join_type,
),
CanonicalJoinStrategy::NestedLoop => execute_runtime_full_scan_join(
left_query,
&left_records,
left_table_name,
left_table_alias,
&left_join_field,
&right_records,
right_table_name,
right_table_alias,
&right_join_field,
join_type,
),
CanonicalJoinStrategy::GraphLookupJoin => execute_runtime_graph_lookup_join(
left_query,
&left_records,
left_table_name,
left_table_alias,
&left_join_field,
&right_records,
right_table_name,
right_table_alias,
&right_join_field,
join_type,
),
}
}
pub(crate) fn execute_runtime_canonical_join_child(
runtime: &RedDBRuntime,
node: &crate::storage::query::planner::CanonicalLogicalNode,
query: &JoinQuery,
) -> RedDBResult<Vec<UnifiedRecord>> {
let child = node.children.first().ok_or_else(|| {
RedDBError::Query(format!(
"canonical join operator {} is missing its child plan",
node.operator
))
})?;
execute_runtime_canonical_join_node(runtime, child, query)
}
pub(crate) fn runtime_join_table_context(
query: &JoinQuery,
) -> (Option<&str>, Option<&str>, Option<&str>, Option<&str>) {
let (left_table_name, left_table_alias) = match query.left.as_ref() {
QueryExpr::Table(table) => (
Some(table.table.as_str()),
Some(table.alias.as_deref().unwrap_or(table.table.as_str())),
),
_ => (None, None),
};
let (right_table_name, right_table_alias) = match query.right.as_ref() {
QueryExpr::Table(table) => (
Some(table.table.as_str()),
Some(table.alias.as_deref().unwrap_or(table.table.as_str())),
),
QueryExpr::Graph(graph) => (Some("graph"), graph.alias.as_deref().or(Some("graph"))),
QueryExpr::Path(path) => (Some("path"), path.alias.as_deref().or(Some("path"))),
QueryExpr::Vector(vector) => (Some("vector"), vector.alias.as_deref().or(Some("vector"))),
QueryExpr::Hybrid(hybrid) => (Some("hybrid"), hybrid.alias.as_deref().or(Some("hybrid"))),
QueryExpr::Join(_) => (Some("join"), Some("join")),
QueryExpr::Insert(_)
| QueryExpr::Update(_)
| QueryExpr::Delete(_)
| QueryExpr::CreateTable(_)
| QueryExpr::CreateCollection(_)
| QueryExpr::CreateVector(_)
| QueryExpr::DropTable(_)
| QueryExpr::DropGraph(_)
| QueryExpr::DropVector(_)
| QueryExpr::DropDocument(_)
| QueryExpr::DropKv(_)
| QueryExpr::DropCollection(_)
| QueryExpr::Truncate(_)
| QueryExpr::AlterTable(_)
| QueryExpr::CreateVcsRef(_)
| QueryExpr::DropVcsRef(_)
| QueryExpr::GraphCommand(_)
| QueryExpr::SearchCommand(_)
| QueryExpr::CreateIndex(_)
| QueryExpr::DropIndex(_)
| QueryExpr::ProbabilisticCommand(_)
| QueryExpr::Ask(_)
| QueryExpr::SetConfig { .. }
| QueryExpr::ShowConfig { .. }
| QueryExpr::SetSecret { .. }
| QueryExpr::DeleteSecret { .. }
| QueryExpr::SetKv { .. }
| QueryExpr::DeleteKv { .. }
| QueryExpr::ShowSecrets { .. }
| QueryExpr::SetTenant(_)
| QueryExpr::ShowTenant
| QueryExpr::CreateTimeSeries(_)
| QueryExpr::CreateMetric(_)
| QueryExpr::AlterMetric(_)
| QueryExpr::CreateSlo(_)
| QueryExpr::DropTimeSeries(_)
| QueryExpr::CreateQueue(_)
| QueryExpr::AlterQueue(_)
| QueryExpr::DropQueue(_)
| QueryExpr::QueueSelect(_)
| QueryExpr::QueueCommand(_)
| QueryExpr::KvCommand(_)
| QueryExpr::ConfigCommand(_)
| QueryExpr::CreateTree(_)
| QueryExpr::DropTree(_)
| QueryExpr::TreeCommand(_)
| QueryExpr::ExplainAlter(_)
| QueryExpr::TransactionControl(_)
| QueryExpr::MaintenanceCommand(_)
| QueryExpr::CreateSchema(_)
| QueryExpr::DropSchema(_)
| QueryExpr::CreateSequence(_)
| QueryExpr::DropSequence(_)
| QueryExpr::CopyFrom(_)
| QueryExpr::CreateView(_)
| QueryExpr::DropView(_)
| QueryExpr::RefreshMaterializedView(_)
| QueryExpr::CreatePolicy(_)
| QueryExpr::DropPolicy(_)
| QueryExpr::CreateServer(_)
| QueryExpr::DropServer(_)
| QueryExpr::CreateForeignTable(_)
| QueryExpr::DropForeignTable(_)
| QueryExpr::Grant(_)
| QueryExpr::Revoke(_)
| QueryExpr::AlterUser(_)
| QueryExpr::CreateUser(_)
| QueryExpr::CreateIamPolicy { .. }
| QueryExpr::DropIamPolicy { .. }
| QueryExpr::AttachPolicy { .. }
| QueryExpr::DetachPolicy { .. }
| QueryExpr::ShowPolicies { .. }
| QueryExpr::ShowEffectivePermissions { .. }
| QueryExpr::RankOf(_)
| QueryExpr::ApproxRankOf(_)
| QueryExpr::RankRange(_)
| QueryExpr::SimulatePolicy { .. }
| QueryExpr::LintPolicy { .. }
| QueryExpr::MigratePolicyMode { .. }
| QueryExpr::CreateMigration(_)
| QueryExpr::ApplyMigration(_)
| QueryExpr::RollbackMigration(_)
| QueryExpr::ExplainMigration(_)
| QueryExpr::EventsBackfill(_)
| QueryExpr::EventsBackfillStatus { .. } => (None, None),
_ => (None, None),
};
(
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
}
pub(crate) fn resolve_runtime_join_field(
record: &UnifiedRecord,
field: &FieldRef,
left_table_name: Option<&str>,
left_table_alias: Option<&str>,
right_table_name: Option<&str>,
right_table_alias: Option<&str>,
) -> Option<Value> {
match field {
FieldRef::TableColumn { table, column } if !table.is_empty() => {
let matches_left =
runtime_table_context_matches(table.as_str(), left_table_name, left_table_alias);
let matches_right =
runtime_table_context_matches(table.as_str(), right_table_name, right_table_alias);
let left_present = record.contains_column(JOIN_LEFT_AGGREGATE_INPUTS);
let right_present = record.contains_column(JOIN_RIGHT_AGGREGATE_INPUTS);
if (matches_left && right_present && !left_present)
|| (matches_right && left_present && !right_present)
{
return None;
}
if let Some(value) = record.get(format!("{table}.{column}").as_str()) {
return Some(value.clone());
}
if !(matches_left || matches_right) {
if left_table_name.is_none() && left_table_alias.is_none() {
if let Some(value) = record.get(column.as_str()) {
return Some(value.clone());
}
}
return None;
}
record
.get(column.as_str())
.cloned()
.or_else(|| resolve_runtime_document_path(record, column))
}
_ => resolve_runtime_field(record, field, None, None),
}
}
pub(crate) fn project_runtime_join_record(
source: &UnifiedRecord,
projections: &[Projection],
left_table_name: Option<&str>,
left_table_alias: Option<&str>,
right_table_name: Option<&str>,
right_table_alias: Option<&str>,
) -> UnifiedRecord {
project_runtime_join_record_with_db(
None,
source,
projections,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
.unwrap_or_else(|_| UnifiedRecord::new())
}
pub(crate) fn project_runtime_join_record_with_db(
db: Option<&RedDB>,
source: &UnifiedRecord,
projections: &[Projection],
left_table_name: Option<&str>,
left_table_alias: Option<&str>,
right_table_name: Option<&str>,
right_table_alias: Option<&str>,
) -> RedDBResult<UnifiedRecord> {
let select_all = projections.is_empty()
|| projections
.iter()
.any(|item| matches!(item, Projection::All));
let mut record = UnifiedRecord::new();
record.nodes = source.nodes.clone();
record.edges = source.edges.clone();
record.paths = source.paths.clone();
record.vector_results = source.vector_results.clone();
if select_all {
for key in visible_value_keys(source) {
if let Some(value) = source.get(key.as_str()) {
let cloned = value.clone();
record.set_arc(std::sync::Arc::from(key), cloned);
}
}
}
for projection in projections {
if matches!(projection, Projection::All) {
continue;
}
let label = projection_name(projection);
let sensitive =
super::super::join_filter::projection_uses_secret(projection, source, None, None);
let value = match projection {
Projection::Function(_, _) | Projection::Expression(_, _) if sensitive => {
super::super::join_filter::project_runtime_record_with_db(
db,
source,
std::slice::from_ref(projection),
None,
None,
false,
false,
)?
.get(&label)
.cloned()
}
Projection::Column(column) | Projection::Alias(column, _) => source
.get(column.as_str())
.cloned()
.or_else(|| resolve_runtime_document_path(source, column)),
Projection::Field(field, _) => resolve_runtime_join_field(
source,
field,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
),
Projection::Expression(filter, _) => {
Some(Value::Boolean(evaluate_runtime_join_filter_with_db(
db,
source,
filter,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)))
}
Projection::Function(name, args) => {
super::super::join_filter::evaluate_scalar_function_with_db(db, name, args, source)
}
Projection::All => None,
Projection::Window { .. } => None,
};
let value = value.unwrap_or(Value::Null);
let value = if sensitive {
super::super::execution_context::secret_query_output(value)?
} else {
value
};
record.set_arc(std::sync::Arc::from(label), value);
}
Ok(record)
}
pub(crate) fn evaluate_runtime_join_filter(
record: &UnifiedRecord,
filter: &Filter,
left_table_name: Option<&str>,
left_table_alias: Option<&str>,
right_table_name: Option<&str>,
right_table_alias: Option<&str>,
) -> bool {
evaluate_runtime_join_filter_with_db(
None,
record,
filter,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
}
pub(crate) fn evaluate_runtime_join_filter_with_db(
db: Option<&RedDB>,
record: &UnifiedRecord,
filter: &Filter,
left_table_name: Option<&str>,
left_table_alias: Option<&str>,
right_table_name: Option<&str>,
right_table_alias: Option<&str>,
) -> bool {
match filter {
Filter::Compare { field, op, value } => resolve_runtime_join_field(
record,
field,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
.as_ref()
.and_then(|candidate| evaluate_metadata_field_compare(field, candidate, *op, value))
.or_else(|| {
resolve_runtime_join_field(
record,
field,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
.as_ref()
.map(|candidate| compare_runtime_values(candidate, value, *op))
})
.unwrap_or(false),
Filter::CompareFields { left, op, right } => {
let left_val = resolve_runtime_join_field(
record,
left,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
);
let right_val = resolve_runtime_join_field(
record,
right,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
);
match (left_val, right_val) {
(Some(l), Some(r)) => compare_runtime_values(&l, &r, *op),
_ => false,
}
}
Filter::CompareExpr { lhs, op, rhs } => {
let l = super::super::expr_eval::evaluate_runtime_expr_with_db(
db,
lhs,
record,
left_table_name,
left_table_alias,
);
let r = super::super::expr_eval::evaluate_runtime_expr_with_db(
db,
rhs,
record,
left_table_name,
left_table_alias,
);
match (l, r) {
(Some(lv), Some(rv)) => compare_runtime_values(&lv, &rv, *op),
_ => false,
}
}
Filter::And(left, right) => {
evaluate_runtime_join_filter_with_db(
db,
record,
left,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
) && evaluate_runtime_join_filter_with_db(
db,
record,
right,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
}
Filter::Or(left, right) => {
evaluate_runtime_join_filter_with_db(
db,
record,
left,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
) || evaluate_runtime_join_filter_with_db(
db,
record,
right,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
}
Filter::Not(inner) => !evaluate_runtime_join_filter_with_db(
db,
record,
inner,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
),
Filter::IsNull(field) => resolve_runtime_join_field(
record,
field,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
.map(|value| value == Value::Null)
.unwrap_or(true),
Filter::IsNotNull(field) => resolve_runtime_join_field(
record,
field,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
.map(|value| value != Value::Null)
.unwrap_or(false),
Filter::In { field, values } => resolve_runtime_join_field(
record,
field,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
.as_ref()
.is_some_and(|candidate| {
evaluate_metadata_field_in(field, candidate, values).unwrap_or_else(|| {
values
.iter()
.any(|value| compare_runtime_values(candidate, value, CompareOp::Eq))
})
}),
Filter::Between { field, low, high } => resolve_runtime_join_field(
record,
field,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
.as_ref()
.is_some_and(|candidate| {
compare_runtime_values(candidate, low, CompareOp::Ge)
&& compare_runtime_values(candidate, high, CompareOp::Le)
}),
Filter::Like { field, pattern } => resolve_runtime_join_field(
record,
field,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
.as_ref()
.and_then(runtime_value_text)
.is_some_and(|value| like_matches(&value, pattern)),
Filter::StartsWith { field, prefix } => resolve_runtime_join_field(
record,
field,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
.as_ref()
.and_then(runtime_value_text)
.is_some_and(|value| value.starts_with(prefix)),
Filter::EndsWith { field, suffix } => resolve_runtime_join_field(
record,
field,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
.as_ref()
.and_then(runtime_value_text)
.is_some_and(|value| value.ends_with(suffix)),
Filter::Contains { field, substring } => resolve_runtime_join_field(
record,
field,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
.as_ref()
.and_then(runtime_value_text)
.is_some_and(|value| value.contains(substring)),
}
}
pub(crate) fn compare_runtime_join_order(
left: &UnifiedRecord,
right: &UnifiedRecord,
clauses: &[OrderByClause],
left_table_name: Option<&str>,
left_table_alias: Option<&str>,
right_table_name: Option<&str>,
right_table_alias: Option<&str>,
) -> Ordering {
compare_runtime_join_order_with_db(
None,
left,
right,
clauses,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
)
}
pub(crate) fn compare_runtime_join_order_with_db(
db: Option<&RedDB>,
left: &UnifiedRecord,
right: &UnifiedRecord,
clauses: &[OrderByClause],
left_table_name: Option<&str>,
left_table_alias: Option<&str>,
right_table_name: Option<&str>,
right_table_alias: Option<&str>,
) -> Ordering {
for clause in clauses {
let (left_value, right_value) = if let Some(ref expr) = clause.expr {
(
super::super::expr_eval::evaluate_runtime_expr_with_db(
db,
expr,
left,
left_table_name,
left_table_alias,
),
super::super::expr_eval::evaluate_runtime_expr_with_db(
db,
expr,
right,
left_table_name,
left_table_alias,
),
)
} else {
(
resolve_runtime_join_field(
left,
&clause.field,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
),
resolve_runtime_join_field(
right,
&clause.field,
left_table_name,
left_table_alias,
right_table_name,
right_table_alias,
),
)
};
let ordering = compare_runtime_optional_values(
left_value.as_ref(),
right_value.as_ref(),
clause.nulls_first,
);
if ordering != Ordering::Equal {
return if clause.ascending {
ordering
} else {
ordering.reverse()
};
}
}
runtime_record_identity_key(left).cmp(&runtime_record_identity_key(right))
}