use relate_core::{Error, Result};
use relate_ir::{
is_agg_call, is_agg_expr, walk_scope_children, Bearing, ChildScope, Expr, MapProjectionItem,
Projection,
};
use relate_names::SmallName;
mod subclause;
pub(crate) use subclause::{
check_aggregating_subclause, check_where_subclause, reject_agg_in_pred, reject_order_by_agg,
SubclauseScope,
};
pub(crate) type Imports = std::collections::HashSet<String>;
fn explicit_keys_cover_star_scope(keys: &[Expr], outer_names: &crate::binding::Env) -> bool {
let names: Option<std::collections::HashSet<String>> = keys
.iter()
.map(|k| match k {
Expr::Variable(v) => Some(v.to_string()),
_ => None,
})
.collect();
!keys.is_empty()
&& names.is_some_and(|names| {
names.len() == outer_names.len() && outer_names.keys().all(|s| names.contains(s))
})
}
pub(crate) fn check_agg_projections(
items: &[Projection],
group_by: Option<&[Expr]>,
imports: &Imports,
outer_names: &crate::binding::Env,
) -> Result<()> {
if let Some(keys) = group_by {
let star_item = items.iter().any(|i| matches!(i.expr, Expr::Star));
if star_item && !keys.iter().any(|k| matches!(k, Expr::Star)) {
let covers_scope = items.iter().any(|i| is_agg_expr(&i.expr))
&& explicit_keys_cover_star_scope(keys, outer_names);
if !covers_scope {
return Err(Error::syntax(
"AmbiguousAggregationExpression: `*` projection is not allowed with an explicit GROUP BY",
));
}
}
}
if !items.iter().any(|i| is_agg_expr(&i.expr)) && group_by.is_none() {
return Ok(());
}
let group_keys = grouping_keys(items, group_by);
for item in items {
if !is_agg_expr(&item.expr)
&& (group_by.is_none()
|| contains_subquery_expression(&item.expr)
|| group_keys
.iter()
.any(|key| **key == item.expr || key_is_property_of(key, &item.expr)))
{
continue;
}
check_item_grouping(&item.expr, &group_keys, imports, outer_names)?;
}
Ok(())
}
fn contains_subquery_expression(expr: &Expr) -> bool {
expr.any(&mut |node| node.subquery_body().is_some())
}
fn key_is_property_of(key: &Expr, item: &Expr) -> bool {
matches!(key, Expr::Property { expr, .. } if **expr == *item)
}
fn grouping_keys<'a>(items: &'a [Projection], group_by: Option<&'a [Expr]>) -> Vec<&'a Expr> {
match group_by {
Some(keys) => keys.iter().collect(),
None => items
.iter()
.filter(|i| !is_agg_expr(&i.expr))
.map(|i| &i.expr)
.collect(),
}
}
fn check_item_grouping(
expr: &Expr,
group_keys: &[&Expr],
imports: &Imports,
outer_names: &crate::binding::Env,
) -> Result<()> {
let mut leaves = Vec::new();
collect_non_agg_leaves(expr, &mut leaves);
let mut offending: Vec<String> = Vec::new();
let mut rejected = false;
for leaf in &leaves {
if !leaf_allowed_as_group(leaf, group_keys, imports) {
rejected = true;
push_offending_name(leaf, &mut offending);
}
}
if rejected {
return Err(non_grouping_ref(&offending));
}
check_nested_scope_refs(expr, group_keys, imports, outer_names)
}
fn push_offending_name(leaf: &Expr, out: &mut Vec<String>) {
if let Some(name) = leaf_root_name(leaf) {
let name = name.to_string();
if !out.contains(&name) {
out.push(name);
}
}
}
fn non_grouping_ref(offending: &[String]) -> Error {
let named = match offending {
[] => String::new(),
[one] => format!(": the expression contains a non-grouping sub-expression `{one}`"),
[rest @ .., last] => format!(
": the expression contains non-grouping sub-expressions {} and `{last}`",
rest.iter()
.map(|name| format!("`{name}`"))
.collect::<Vec<_>>()
.join(", ")
),
};
Error::syntax(format!(
"AmbiguousAggregationExpression: non-aggregated expression must be a grouping key{named}"
))
}
fn check_nested_scope_refs(
item: &Expr,
group_keys: &[&Expr],
imports: &Imports,
outer_names: &crate::binding::Env,
) -> Result<()> {
let leaves = collect_nested_scope_leaves(item);
for leaf in &leaves {
let root = leaf_root_name(leaf);
if leaf_is_offending(root, outer_names) && !leaf_allowed_as_group(leaf, group_keys, imports)
{
let offending: Vec<String> = root.map(ToString::to_string).into_iter().collect();
return Err(non_grouping_ref(&offending));
}
}
Ok(())
}
fn leaf_is_offending(root: Option<&SmallName>, outer_names: &crate::binding::Env) -> bool {
root.is_none_or(|name| name.with_str(|text| outer_names.contains_key(text)))
}
fn leaf_root_name(leaf: &Expr) -> Option<&SmallName> {
match leaf {
Expr::Variable(v) => Some(v),
Expr::Property { expr, .. } | Expr::DynamicProperty { expr, .. } => match expr.as_ref() {
Expr::Variable(v) => Some(v),
_ => None,
},
_ => None,
}
}
fn collect_nested_scope_leaves(expr: &Expr) -> Vec<Expr> {
let mut out = Vec::new();
nested_scope_leaves(expr, &mut Vec::new(), SubqueryBodies::Merged, &mut out);
out
}
fn collect_row_scope_leaves(expr: &Expr) -> Vec<Expr> {
let mut out = Vec::new();
nested_scope_leaves(expr, &mut Vec::new(), SubqueryBodies::Excluded, &mut out);
out
}
#[derive(Clone, Copy)]
enum SubqueryBodies {
Merged,
Excluded,
}
fn nested_scope_leaves(
expr: &Expr,
bound: &mut Vec<SmallName>,
bodies: SubqueryBodies,
out: &mut Vec<Expr>,
) {
if is_agg_call(expr) {
return;
}
fn is_bound(name: &SmallName, bound: &[SmallName]) -> bool {
bound.iter().any(|b| b == name)
}
fn read(name: &SmallName, bound: &[SmallName], out: &mut Vec<Expr>) {
if !is_bound(name, bound) {
out.push(Expr::Variable(name.clone()));
}
}
if is_row_leaf(expr) {
if let Some(base) = leaf_root_name(expr) {
if !is_bound(base, bound) {
out.push(expr.clone());
}
return;
}
}
match expr.bearing() {
Some(Bearing::Subquery(query)) => {
if matches!(bodies, SubqueryBodies::Merged) {
let mut names = std::collections::BTreeSet::new();
relate_ir::exists_outer_vars(query, &mut names);
for name in &names {
read(name, bound, out);
}
}
return;
}
Some(Bearing::Pattern(path)) => {
for name in relate_ir::pattern_anchor_variables(path) {
read(&name, bound, out);
}
return;
}
None => {}
}
walk_scope_children(expr, &mut |child, scope| match scope {
ChildScope::Enclosing => nested_scope_leaves(child, bound, bodies, out),
ChildScope::Element(names) => {
let mark = bound.len();
bound.extend(names.iter().cloned());
nested_scope_leaves(child, bound, bodies, out);
bound.truncate(mark);
}
});
}
fn is_row_leaf(expr: &Expr) -> bool {
match expr {
Expr::Variable(_) => true,
Expr::Property { expr: target, .. } => !is_agg_expr(target),
Expr::DynamicProperty { expr: target, key } => {
matches!(target.as_ref(), Expr::Variable(_)) && key.is_seek_const()
}
_ => false,
}
}
fn collect_non_agg_leaves(expr: &Expr, out: &mut Vec<Expr>) {
if is_agg_call(expr) {
return;
}
if is_row_leaf(expr) {
out.push(expr.clone());
return;
}
if expr.binds_identifiers() {
return;
}
if let Expr::MapProjection {
expr: target,
items,
} = expr
{
for item in items {
match item {
MapProjectionItem::Variable { name } => {
out.push(Expr::Variable(name.clone()));
}
MapProjectionItem::Property { key } => {
out.push(Expr::property((**target).clone(), key.clone()));
}
MapProjectionItem::KeyValue { .. } | MapProjectionItem::AllProperties => {}
}
}
}
expr.each_child(&mut |child| collect_non_agg_leaves(child, out));
}
fn leaf_allowed_as_group(leaf: &Expr, group_keys: &[&Expr], imports: &Imports) -> bool {
if group_keys.contains(&leaf) {
return true;
}
if matches!(leaf, Expr::Variable(_)) && group_keys.iter().any(|g| matches!(g, Expr::Star)) {
return true;
}
if let Expr::Variable(v) = leaf {
if v.with_str(|text| imports.contains(text)) {
return true;
}
}
if matches!(leaf, Expr::Property { .. } | Expr::DynamicProperty { .. }) {
if let Some(v) = leaf_root_name(leaf) {
if v.with_str(|text| imports.contains(text)) {
return true;
}
return group_keys
.iter()
.any(|g| matches!(g, Expr::Variable(k) if k == v));
}
}
false
}
pub(crate) fn projection_aggregates(
items: &[Projection],
group_by: Option<&[Expr]>,
distinct: bool,
) -> bool {
items.iter().any(|i| is_agg_expr(&i.expr)) || group_by.is_some() || distinct
}
#[cfg(test)]
mod tests;