use relate_core::{Error, Result};
use relate_ir::{is_agg_call, is_agg_expr, Expr, OrderItem, Projection};
use super::{
collect_non_agg_leaves, collect_row_scope_leaves, grouping_keys, leaf_allowed_as_group,
leaf_root_name, projection_aggregates, Imports,
};
use crate::binding::Env;
pub(crate) struct SubclauseScope<'a> {
items: &'a [Projection],
group_by: Option<&'a [Expr]>,
imports: &'a Imports,
outer_names: &'a Env,
aggregating: bool,
group_keys: Vec<&'a Expr>,
names: Vec<String>,
}
impl<'a> SubclauseScope<'a> {
pub(crate) fn new(
items: &'a [Projection],
group_by: Option<&'a [Expr]>,
distinct: bool,
imports: &'a Imports,
outer_names: &'a Env,
) -> Self {
Self {
items,
group_by,
imports,
outer_names,
aggregating: projection_aggregates(items, group_by, distinct),
group_keys: grouping_keys(items, group_by),
names: output_names(items),
}
}
pub(crate) fn aggregating(&self) -> bool {
self.aggregating
}
}
pub(crate) fn check_aggregating_subclause(
scope: &SubclauseScope<'_>,
expr: &Expr,
context: &str,
) -> Result<()> {
if !scope.aggregating || is_agg_expr(expr) || is_projected_item(scope.items, expr) {
return Ok(());
}
check_post_projection_leaves(scope, expr, context)
}
pub(crate) fn check_post_projection_leaves(
scope: &SubclauseScope<'_>,
expr: &Expr,
context: &str,
) -> Result<()> {
let leaves = collect_row_scope_leaves(expr);
for leaf in &leaves {
if leaf_root_name(leaf)
.is_some_and(|name| !name.with_str(|text| scope.outer_names.contains_key(text)))
{
continue;
}
if leaf_allowed_in_subclause(leaf, &scope.group_keys, &scope.names, scope.imports) {
continue;
}
if scope.group_by.is_none()
&& scope
.group_keys
.iter()
.filter(|key| key.subquery_body().is_none())
.any(|key| key.contains_deep(leaf) && expr.contains_deep(key))
{
continue;
}
return Err(Error::syntax(format!(
"UndefinedVariable: {context} refers to a non-projecting variable"
)));
}
Ok(())
}
fn subexpr_contains(haystack: &Expr, needle: &Expr) -> bool {
haystack.any(&mut |e| e == needle)
}
pub(crate) fn reject_agg_in_pred(expr: &Expr) -> Result<()> {
if is_agg_expr(expr) {
return Err(Error::syntax(
"InvalidAggregation: aggregations are not allowed in WHERE",
));
}
Ok(())
}
pub(crate) fn output_names(items: &[Projection]) -> Vec<String> {
items
.iter()
.enumerate()
.map(|(i, item)| item.output_name(i))
.collect()
}
pub(crate) fn check_subclause_agg_leaves(
scope: &SubclauseScope<'_>,
expr: &Expr,
imports: &Imports,
context: &str,
) -> Result<()> {
let reintroduced: Vec<String> = scope
.items
.iter()
.zip(&scope.names)
.filter(|(item, _)| {
!is_agg_expr(&item.expr) && !item.expr.any(&mut |e| matches!(e, Expr::Variable(_)))
})
.map(|(_, name)| name.clone())
.collect();
let mut leaves = Vec::new();
collect_non_agg_leaves(expr, &mut leaves);
for leaf in &leaves {
if matches!(leaf, Expr::Variable(v) if v.with_str(|t| reintroduced.iter().any(|r| r == t)))
{
return Err(same_clause_ref(context));
}
if !leaf_allowed_in_subclause(leaf, &scope.group_keys, &scope.names, imports)
&& !scope
.items
.iter()
.any(|item| subexpr_contains(&item.expr, leaf) && subexpr_contains(expr, &item.expr))
{
return Err(Error::syntax(format!(
"UndefinedVariable: {context} refers to a non-projected expression"
)));
}
}
check_same_clause_refs(scope.items, expr, &reintroduced, context)?;
Ok(())
}
fn aggregate_calls(expr: &Expr) -> Vec<&Expr> {
fn walk<'a>(expr: &'a Expr, calls: &mut Vec<&'a Expr>) {
if is_agg_call(expr) {
calls.push(expr);
}
expr.each_child(&mut |child| walk(child, calls));
}
let mut calls = Vec::new();
walk(expr, &mut calls);
calls
}
fn reject_call_referencing(
items: &[Projection],
expr: &Expr,
names: &[String],
error: impl Fn() -> Error,
) -> Result<()> {
if is_projected_item(items, expr) {
return Ok(());
}
for call in aggregate_calls(expr) {
if call.any(&mut |node| {
matches!(node, Expr::Variable(v)
if v.with_str(|text| names.iter().any(|name| name == text)))
}) {
return Err(error());
}
}
Ok(())
}
fn same_clause_ref(context: &str) -> Error {
Error::syntax(format!(
"InvalidAggregation: {context} cannot reference variables declared in the same clause"
))
}
fn check_same_clause_refs(
items: &[Projection],
expr: &Expr,
reintroduced: &[String],
context: &str,
) -> Result<()> {
reject_call_referencing(items, expr, reintroduced, || same_clause_ref(context))
}
pub(crate) fn is_projected_item(items: &[Projection], expr: &Expr) -> bool {
items.iter().any(|item| item.expr == *expr)
}
pub(crate) fn reject_order_by_agg(
scope: &SubclauseScope<'_>,
order: &[OrderItem],
imports: &Imports,
) -> Result<()> {
let order_has_agg = order.iter().any(|o| is_agg_expr(&o.expr));
if order_has_agg && !scope.aggregating {
return Err(Error::syntax(
"InvalidAggregation: aggregation functions are not allowed in ORDER BY when clause has no aggregation",
));
}
for o in order {
if !is_agg_expr(&o.expr) {
continue;
}
reject_shadowed_aggregate_argument(scope, &o.expr)?;
check_subclause_agg_leaves(scope, &o.expr, imports, "ORDER BY aggregation")?;
}
Ok(())
}
pub(crate) fn check_where_subclause(
scope: &SubclauseScope<'_>,
demoted_imports: &Imports,
w: &Expr,
) -> Result<()> {
if is_agg_expr(w) {
if !scope.aggregating() {
return reject_agg_in_pred(w);
}
check_subclause_agg_leaves(scope, w, demoted_imports, "WHERE aggregation")
} else {
check_aggregating_subclause(scope, w, "WHERE")
}
}
fn reject_shadowed_aggregate_argument(scope: &SubclauseScope<'_>, expr: &Expr) -> Result<()> {
let aggregate_aliases: Vec<String> = scope
.items
.iter()
.zip(&scope.names)
.filter(|(item, _)| is_agg_expr(&item.expr))
.map(|(_, name)| name.clone())
.collect();
reject_call_referencing(scope.items, expr, &aggregate_aliases, || {
Error::syntax(
"InvalidAggregation: ORDER BY aggregation references an aggregate \
projected in the same clause",
)
})
}
fn leaf_allowed_in_subclause(
leaf: &Expr,
group_keys: &[&Expr],
output_names: &[String],
imports: &Imports,
) -> bool {
if leaf_allowed_as_group(leaf, group_keys, imports) {
return true;
}
let Some(base) = leaf_root_name(leaf) else {
return false;
};
base.with_str(|text| output_names.iter().any(|name| name == text))
|| (matches!(leaf, Expr::Property { .. } | Expr::DynamicProperty { .. })
&& group_keys.iter().any(|key| matches!(key, Expr::Star)))
}