use super::authz::policy_columns::collect_expr_columns;
use super::join_filter::evaluate_runtime_filter_result_with_db;
use super::query_exec::{
execute_runtime_table_query_with_exists, table_query_is_implicit_scalar_select, RowBufferArena,
};
use super::record_search::scan_runtime_table_source_records_matching;
use super::statement_frame::ReadFrame;
use super::RedDBRuntime;
use crate::storage::query::unified::{UnifiedRecord, UnifiedResult};
use crate::{RedDBError, RedDBResult};
use reddb_engine::query::parameters::{bind, visit_expr};
use reddb_engine::query::planning::aggregation::{
prepare_aggregate_group_bindings, AggregateGroupBinding,
};
use reddb_engine::query::runtime::aggregation::{has_aggregate_projections, is_aggregate_function};
use reddb_rql::ast::{
CompareOp, Expr, FieldRef, Filter, QueryExpr, SelectItem, TableQuery, TableSource, EXISTS_EXPR,
};
use reddb_rql::sql_lowering::effective_table_projections;
use reddb_types::Value;
use std::cell::RefCell;
use std::collections::BTreeSet;
use std::rc::Rc;
fn query_error(message: impl Into<String>) -> RedDBError {
RedDBError::Query(message.into())
}
pub(super) fn visit_having_exists(table: &TableQuery, mut visit: impl FnMut(&QueryExpr)) {
if let Some(having) = &table.having_expr {
visit_expr(having, &mut |expr| {
if let Expr::FunctionCall { name, args, .. } = expr {
if name == EXISTS_EXPR {
if let Some(Expr::Subquery { query, .. }) = args.first() {
visit(&query.query);
}
}
}
});
}
}
impl RedDBRuntime {
pub(super) fn execute_table_with_having_exists(
&self,
mut table: TableQuery,
frame: &dyn ReadFrame,
arena: Option<Rc<RefCell<RowBufferArena>>>,
) -> RedDBResult<UnifiedResult> {
let mut has_exists = false;
visit_having_exists(&table, |_| has_exists = true);
let index_store = Some(&self.inner.index_store);
if !has_exists {
return execute_runtime_table_query_with_exists(
&self.inner.db,
&table,
index_store,
arena,
None,
);
}
if table.source.is_some() && !matches!(table.source, Some(TableSource::Name(_))) {
return Err(query_error(
"HAVING EXISTS requires an ordinary outer table",
));
}
let groups = prepare_aggregate_group_bindings(&table).map_err(query_error)?;
let outer = Relation::new(self, &table);
let mut outer_columns = BTreeSet::new();
let mut having = table.having_expr.take().expect("EXISTS found in HAVING");
rewrite_expr(&mut having, &mut |expr| {
let Expr::FunctionCall { name, args, .. } = expr else {
return Ok(false);
};
if name != EXISTS_EXPR {
return Ok(false);
}
let [Expr::Subquery { query, .. }] = args.as_mut_slice() else {
return Err(query_error("EXISTS requires a SELECT subquery"));
};
let QueryExpr::Table(inner) = query.query.as_mut() else {
return Err(query_error("HAVING EXISTS requires a single inner table"));
};
let bindings = self.bind_having_exists(inner, &outer, &groups, frame)?;
for binding in &bindings {
collect_expr_columns(
binding,
&table.table,
table.alias.as_deref(),
&mut outer_columns,
);
}
args.extend(bindings);
Ok(true)
})?;
table.having_expr = Some(having);
table.having = None;
self.check_table_column_projection_authz_with_columns(&table, frame, outer_columns)?;
let exists = |query: &QueryExpr, parameters: &[Value]| {
let bound = bind(query, parameters).map_err(|err| query_error(err.to_string()))?;
let QueryExpr::Table(inner) = bound else {
return Err(query_error("HAVING EXISTS requires a single inner table"));
};
self.having_exists_matches(&inner)
};
execute_runtime_table_query_with_exists(
&self.inner.db,
&table,
index_store,
arena,
Some(&exists),
)
}
fn having_exists_matches(&self, inner: &TableQuery) -> RedDBResult<bool> {
if inner.limit == Some(0) {
return Ok(false);
}
let filter = inner.where_expr.clone().map(|lhs| Filter::CompareExpr {
lhs,
op: CompareOp::Eq,
rhs: Expr::lit(Value::Boolean(true)),
});
let table = &inner.table;
let db = &self.inner.db;
let offset = inner.offset.unwrap_or(0);
let matches = |record: &UnifiedRecord| match &filter {
Some(filter) => evaluate_runtime_filter_result_with_db(
Some(db),
record,
filter,
Some(table),
inner.alias.as_deref(),
),
None => Ok(true),
};
if table_query_is_implicit_scalar_select(inner) {
return if offset == 0 {
matches(&UnifiedRecord::new())
} else {
Ok(false)
};
}
let contract = db.collection_contract_arc(table);
let retained = super::retention_filter::retained_rows(contract.as_deref());
let tombstones = self.integrity_tombstone_ranges()?;
let records = scan_runtime_table_source_records_matching(
db,
table,
usize::try_from(offset).unwrap_or(usize::MAX),
1,
|record| {
if retained.as_ref().is_some_and(|retained| !retained(record))
|| super::integrity_tombstone::record_tombstoned(&tombstones, record)
{
return Ok(false);
}
matches(record)
},
)?;
Ok(!records.is_empty())
}
fn bind_having_exists(
&self,
inner: &mut TableQuery,
outer: &Relation,
groups: &[AggregateGroupBinding],
frame: &dyn ReadFrame,
) -> RedDBResult<Vec<Expr>> {
if (inner.source.is_some() && !matches!(inner.source, Some(TableSource::Name(_))))
|| !inner.group_by.is_empty()
|| !inner.group_by_exprs.is_empty()
|| inner.having.is_some()
|| inner.having_expr.is_some()
|| inner.expand.is_some()
|| inner.sessionize.is_some()
|| inner.as_of.is_some()
|| inner.limit_param.is_some()
|| inner.offset_param.is_some()
|| inner.distinct && inner.offset.unwrap_or(0) > 0
|| has_aggregate_projections(&effective_table_projections(inner))
{
return Err(query_error("unsupported SELECT shape in HAVING EXISTS"));
}
let local = Relation::new(self, inner);
let mut parameters = Vec::new();
if let Some(predicate) = &mut inner.where_expr {
rewrite_expr(predicate, &mut |expr| {
let span = expr.span();
let outer_arg = match expr {
Expr::Column { field, .. } if is_outer_column(&local, outer, field)? => {
let FieldRef::TableColumn { column, .. } = field else {
unreachable!("relation binding requires table columns");
};
let group = groups.iter().find(|group| {
matches!(&group.expression, Expr::Column {
field: FieldRef::TableColumn { column: name, .. }, ..
} if name == column)
});
let group = group.ok_or_else(|| {
query_error(format!("subquery uses ungrouped column {column}"))
})?;
group.expression.clone()
}
Expr::FunctionCall { name, args, .. } if is_aggregate_function(name) => {
let mut outer_only = true;
let mut contains_column = false;
for arg in args {
rewrite_expr(arg, &mut |part| {
if let Expr::Column { field, .. } = part {
contains_column = true;
if is_outer_column(&local, outer, field)? {
let FieldRef::TableColumn { table, .. } = field else {
unreachable!("relation binding requires table columns");
};
table.clear();
} else {
outer_only = false;
}
}
Ok(false)
})?;
}
if !outer_only || !contains_column {
return Err(query_error(
"aggregate functions are not allowed in WHERE",
));
}
expr.clone()
}
Expr::Parameter { .. } => {
return Err(query_error("unbound parameter in HAVING EXISTS"));
}
_ => return Ok(false),
};
let index = parameters.len();
parameters.push(outer_arg);
*expr = Expr::Parameter { index, span };
Ok(true)
})?;
inner.filter = None;
}
let mut inner_columns = BTreeSet::new();
if let Some(predicate) = &inner.where_expr {
collect_expr_columns(
predicate,
&inner.table,
inner.alias.as_deref(),
&mut inner_columns,
);
}
let Some(authorized) = self.authorize_relational_table_select_with_columns(
inner.clone(),
frame,
inner_columns,
)?
else {
inner.limit = Some(0);
return Ok(parameters);
};
*inner = authorized;
if inner.where_expr.is_none() {
inner.where_expr = inner
.filter
.as_ref()
.map(reddb_rql::sql_lowering::filter_to_expr);
}
inner.select_items = vec![SelectItem::Expr {
expr: Expr::lit(Value::Integer(1)),
alias: None,
}];
inner.columns.clear();
inner.order_by.clear();
inner.distinct = false;
inner.limit = Some(inner.limit.unwrap_or(1).min(1));
Ok(parameters)
}
}
struct Relation {
name: String,
columns: Vec<String>,
}
impl Relation {
fn new(runtime: &RedDBRuntime, query: &TableQuery) -> Self {
Self {
name: query.alias.as_ref().unwrap_or(&query.table).clone(),
columns: runtime
.inner
.db
.collection_contract_arc(&query.table)
.map(|contract| {
contract
.declared_columns
.iter()
.map(|column| column.name.clone())
.collect()
})
.unwrap_or_default(),
}
}
}
fn is_outer_column(local: &Relation, outer: &Relation, field: &FieldRef) -> RedDBResult<bool> {
let FieldRef::TableColumn { table, column } = field else {
return Err(query_error("HAVING EXISTS requires relational columns"));
};
if table.is_empty() {
return Ok(column != "*"
&& !local.columns.contains(column)
&& outer.columns.contains(column));
}
if table == &local.name {
Ok(false)
} else if table == &outer.name {
Ok(true)
} else {
Err(query_error(format!(
"relation {table} does not exist in HAVING EXISTS"
)))
}
}
fn rewrite_expr(
expr: &mut Expr,
replace: &mut impl FnMut(&mut Expr) -> RedDBResult<bool>,
) -> RedDBResult<()> {
if replace(expr)? {
return Ok(());
}
match expr {
Expr::BinaryOp { lhs, rhs, .. } => {
rewrite_expr(lhs, replace)?;
rewrite_expr(rhs, replace)?;
}
Expr::UnaryOp { operand, .. } | Expr::IsNull { operand, .. } => {
rewrite_expr(operand, replace)?;
}
Expr::Cast { inner, .. } => rewrite_expr(inner, replace)?,
Expr::FunctionCall { args, .. } => {
for arg in args {
rewrite_expr(arg, replace)?;
}
}
Expr::Case {
branches, else_, ..
} => {
for (condition, value) in branches {
rewrite_expr(condition, replace)?;
rewrite_expr(value, replace)?;
}
if let Some(value) = else_ {
rewrite_expr(value, replace)?;
}
}
Expr::InList { target, values, .. } => {
rewrite_expr(target, replace)?;
for value in values {
rewrite_expr(value, replace)?;
}
}
Expr::Between {
target, low, high, ..
} => {
rewrite_expr(target, replace)?;
rewrite_expr(low, replace)?;
rewrite_expr(high, replace)?;
}
Expr::Subquery { .. } | Expr::WindowFunctionCall { .. } => {
return Err(query_error(
"nested subqueries and window functions are unsupported in HAVING EXISTS",
));
}
Expr::Literal { .. } | Expr::Column { .. } | Expr::Parameter { .. } => {}
}
Ok(())
}