use alloc::boxed::Box;
use alloc::collections::BTreeSet;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use spg_sql::ast::{Expr, SelectItem, SelectStatement};
use spg_storage::{ColumnSchema, DataType, Row, Value};
use crate::eval::{self, EvalContext, EvalError};
pub fn uses_aggregate(stmt: &SelectStatement) -> bool {
if stmt.group_by.is_some() || stmt.having.is_some() {
return true;
}
for item in &stmt.items {
if let SelectItem::Expr { expr, .. } = item
&& contains_aggregate(expr)
{
return true;
}
}
for o in &stmt.order_by {
if contains_aggregate(&o.expr) {
return true;
}
}
if let Some(h) = &stmt.having
&& contains_aggregate(h)
{
return true;
}
false
}
pub fn contains_aggregate(e: &Expr) -> bool {
match e {
Expr::FunctionCall { name, args } => {
is_aggregate_name(name) || args.iter().any(contains_aggregate)
}
Expr::AggregateOrdered { .. } => true,
Expr::Binary { lhs, rhs, .. } => contains_aggregate(lhs) || contains_aggregate(rhs),
Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
contains_aggregate(expr)
}
Expr::Like { expr, pattern, .. } => contains_aggregate(expr) || contains_aggregate(pattern),
Expr::Extract { source, .. } => contains_aggregate(source),
Expr::ScalarSubquery(_)
| Expr::Exists { .. }
| Expr::InSubquery { .. }
| Expr::WindowFunction { .. }
| Expr::Literal(_)
| Expr::Placeholder(_)
| Expr::Column(_) => false,
Expr::Array(items) => items.iter().any(contains_aggregate),
Expr::ArraySubscript { target, index } => {
contains_aggregate(target) || contains_aggregate(index)
}
Expr::AnyAll { expr, array, .. } => contains_aggregate(expr) || contains_aggregate(array),
Expr::InList { expr, list, .. } => {
contains_aggregate(expr) || list.iter().any(contains_aggregate)
}
Expr::Case {
operand,
branches,
else_branch,
} => {
operand.as_deref().is_some_and(contains_aggregate)
|| branches
.iter()
.any(|(w, t)| contains_aggregate(w) || contains_aggregate(t))
|| else_branch.as_deref().is_some_and(contains_aggregate)
}
}
}
pub fn is_aggregate_name(name: &str) -> bool {
matches!(
name.to_ascii_lowercase().as_str(),
"count"
| "count_star"
| "sum"
| "min"
| "max"
| "avg"
| "string_agg"
| "array_agg"
| "bool_and"
| "bool_or"
| "every"
)
}
#[derive(Debug, Default, Clone)]
struct AggState {
count: i64,
sum_int: i64,
sum_float: f64,
extreme: Option<Value>,
use_float: bool,
items: Vec<Value>,
seen: BTreeSet<String>,
item_keys: Vec<Vec<Value>>,
separator: Option<String>,
bool_acc: Option<bool>,
}
#[derive(Debug, Clone)]
struct AggSpec {
name: String, arg: Option<Expr>,
arg2: Option<Expr>,
distinct: bool,
order_by: Vec<spg_sql::ast::OrderBy>,
}
#[derive(Debug)]
pub struct AggResult {
pub columns: Vec<ColumnSchema>,
pub rows: Vec<Row>,
pub deferred: Vec<(usize, Expr)>,
pub synth_rows: Vec<Row>,
pub synth_schema: Vec<ColumnSchema>,
}
#[allow(clippy::too_many_lines)]
pub type CorrelatedEval<'a> = &'a dyn Fn(&Expr, &Row, &EvalContext<'_>) -> Result<Value, EvalError>;
pub fn run(
stmt: &SelectStatement,
rows: &[&Row],
schema_cols: &[ColumnSchema],
table_alias: Option<&str>,
correlated_eval: Option<CorrelatedEval<'_>>,
) -> Result<AggResult, EvalError> {
let ctx = EvalContext::new(schema_cols, table_alias);
let group_exprs: Vec<Expr> = stmt.group_by.clone().unwrap_or_default();
let mut agg_specs: Vec<AggSpec> = Vec::new();
for item in &stmt.items {
if let SelectItem::Expr { expr, .. } = item {
collect_aggregates(expr, &mut agg_specs);
}
}
for o in &stmt.order_by {
collect_aggregates(&o.expr, &mut agg_specs);
}
if let Some(h) = &stmt.having {
collect_aggregates(h, &mut agg_specs);
}
validate_agg_arities(stmt, &agg_specs)?;
let mut groups: hashbrown::HashMap<String, (Vec<Value>, Vec<AggState>)> =
hashbrown::HashMap::new();
let mut key_order: Vec<String> = Vec::new();
if rows.is_empty() && group_exprs.is_empty() {
let init: Vec<AggState> = (0..agg_specs.len()).map(|_| AggState::default()).collect();
groups.insert(String::new(), (Vec::new(), init));
key_order.push(String::new());
}
let col_pos = |e: &Expr| -> Option<usize> {
if let Expr::Column(c) = e
&& c.qualifier.is_some()
{
eval::find_column_pos(c, &ctx)
} else {
None
}
};
let group_pos: Vec<Option<usize>> = group_exprs.iter().map(col_pos).collect();
let all_groups_bound = group_pos.iter().all(Option::is_some);
let arg_pos: Vec<Option<usize>> = agg_specs
.iter()
.map(|spec| spec.arg.as_ref().and_then(|e| col_pos(e)))
.collect();
let ci_positions: Vec<usize> = group_exprs
.iter()
.enumerate()
.filter(|(_, g)| {
matches!(
eval::column_collation(g, &ctx),
Some(spg_storage::Collation::CaseInsensitive)
)
})
.map(|(i, _)| i)
.collect();
let mut keybuf_s = String::new();
let mut dkeybuf = String::new();
let mut refs: Vec<&Value> = Vec::with_capacity(group_pos.len());
for row in rows {
if all_groups_bound && ci_positions.is_empty() && !group_exprs.is_empty() {
refs.clear();
refs.extend(
group_pos
.iter()
.map(|p| row.values.get(p.unwrap()).unwrap_or(&Value::Null)),
);
encode_key_refs_into(&refs, &mut keybuf_s);
let entry = match groups.entry_ref(keybuf_s.as_str()) {
hashbrown::hash_map::EntryRef::Occupied(o) => o.into_mut(),
hashbrown::hash_map::EntryRef::Vacant(v) => {
key_order.push(keybuf_s.clone());
let init: Vec<AggState> =
(0..agg_specs.len()).map(|_| AggState::default()).collect();
let owned: Vec<Value> = refs.iter().map(|v| (*v).clone()).collect();
v.insert((owned, init))
}
};
for (i, spec) in agg_specs.iter().enumerate() {
let arg_owned: Value;
let arg_ref: &Value = match (&arg_pos[i], &spec.arg) {
(Some(p), _) => row.values.get(*p).unwrap_or(&Value::Null),
(None, None) => {
arg_owned = Value::Bool(true);
&arg_owned
}
(None, Some(e)) => {
arg_owned = eval::eval_expr(e, row, &ctx)?;
&arg_owned
}
};
let arg2_val = match &spec.arg2 {
None => None,
Some(e) => Some(eval::eval_expr(e, row, &ctx)?),
};
let order_keys = if spec.order_by.is_empty() {
None
} else {
let mut keys = Vec::with_capacity(spec.order_by.len());
for o in &spec.order_by {
keys.push(eval::eval_expr(&o.expr, row, &ctx)?);
}
Some(keys)
};
if spec.distinct {
encode_key_refs_into(core::slice::from_ref(&arg_ref), &mut dkeybuf);
if entry.1[i].seen.contains(dkeybuf.as_str()) {
continue;
}
entry.1[i].seen.insert(dkeybuf.clone());
}
update_state(
&mut entry.1[i],
&spec.name,
arg_ref,
arg2_val.as_ref(),
order_keys,
)?;
}
continue;
}
let group_vals: Vec<Value> = group_exprs
.iter()
.map(|g| eval::eval_expr(g, row, &ctx))
.collect::<Result<_, _>>()?;
let key = if ci_positions.is_empty() {
encode_key(&group_vals)
} else {
let mut key_vals = group_vals.clone();
for &i in &ci_positions {
if let Value::Text(s) = &key_vals[i] {
key_vals[i] = Value::Text(s.to_ascii_lowercase());
}
}
encode_key(&key_vals)
};
let entry = match groups.entry_ref(key.as_str()) {
hashbrown::hash_map::EntryRef::Occupied(o) => o.into_mut(),
hashbrown::hash_map::EntryRef::Vacant(v) => {
key_order.push(key.clone());
let init: Vec<AggState> =
(0..agg_specs.len()).map(|_| AggState::default()).collect();
v.insert((group_vals.clone(), init))
}
};
for (i, spec) in agg_specs.iter().enumerate() {
let arg_val = match &spec.arg {
None => Value::Bool(true), Some(e) => eval::eval_expr(e, row, &ctx)?,
};
let arg2_val = match &spec.arg2 {
None => None,
Some(e) => Some(eval::eval_expr(e, row, &ctx)?),
};
let order_keys = if spec.order_by.is_empty() {
None
} else {
let mut keys = Vec::with_capacity(spec.order_by.len());
for o in &spec.order_by {
keys.push(eval::eval_expr(&o.expr, row, &ctx)?);
}
Some(keys)
};
if spec.distinct {
let key = encode_key(core::slice::from_ref(&arg_val));
if !entry.1[i].seen.insert(key) {
continue;
}
}
update_state(
&mut entry.1[i],
&spec.name,
&arg_val,
arg2_val.as_ref(),
order_keys,
)?;
}
}
let group_types: Vec<DataType> = if rows.is_empty() {
group_exprs.iter().map(|_| DataType::Text).collect()
} else {
let probe = rows[0];
group_exprs
.iter()
.map(|g| {
eval::eval_expr(g, probe, &ctx).map(|v| v.data_type().unwrap_or(DataType::Text))
})
.collect::<Result<_, _>>()?
};
let agg_types: Vec<DataType> = agg_specs
.iter()
.map(|spec| infer_agg_type(spec, schema_cols))
.collect();
let mut synth_schema: Vec<ColumnSchema> = Vec::new();
for (i, ty) in group_types.iter().enumerate() {
synth_schema.push(ColumnSchema::new(format!("__grp_{i}"), *ty, true));
}
for (i, ty) in agg_types.iter().enumerate() {
synth_schema.push(ColumnSchema::new(format!("__agg_{i}"), *ty, true));
}
let mut synth_rows: Vec<Row> = Vec::new();
for k in &key_order {
let (gvals, states) = &groups[k];
let mut values: Vec<Value> = Vec::with_capacity(synth_schema.len());
values.extend(gvals.iter().cloned());
for (i, st) in states.iter().enumerate() {
let st_sorted;
let st_final: &AggState =
if !agg_specs[i].order_by.is_empty() && st.item_keys.len() == st.items.len() {
let mut idx: Vec<usize> = (0..st.items.len()).collect();
let ob = &agg_specs[i].order_by;
idx.sort_by(|&x, &y| {
for (k, o) in ob.iter().enumerate() {
let cmp = crate::order_by_value_cmp(
o.desc,
o.nulls_first,
&st.item_keys[x][k],
&st.item_keys[y][k],
);
if cmp != core::cmp::Ordering::Equal {
return cmp;
}
}
core::cmp::Ordering::Equal
});
let mut sorted = st.clone();
sorted.items = idx.iter().map(|&j| st.items[j].clone()).collect();
st_sorted = sorted;
&st_sorted
} else {
st
};
values.push(finalize(&agg_specs[i].name, st_final));
}
synth_rows.push(Row::new(values));
}
let columns: Vec<ColumnSchema> = stmt
.items
.iter()
.map(|item| match item {
SelectItem::Wildcard => Err(EvalError::TypeMismatch {
detail: "SELECT * with aggregates is not supported".into(),
}),
SelectItem::Expr { expr, alias } => {
let rewritten = rewrite_expr(expr, &group_exprs, &agg_specs);
let name = alias.clone().unwrap_or_else(|| expr.to_string());
Ok(ColumnSchema::new(
name,
agg_or_group_type(&rewritten, &synth_schema),
true,
))
}
})
.collect::<Result<_, _>>()?;
let synth_ctx = EvalContext::new(&synth_schema, None);
let having_rewritten = stmt
.having
.as_ref()
.map(|h| rewrite_expr(h, &group_exprs, &agg_specs));
let items_rewritten: alloc::vec::Vec<Option<Expr>> = stmt
.items
.iter()
.map(|item| match item {
SelectItem::Expr { expr, .. } => Some(rewrite_expr(expr, &group_exprs, &agg_specs)),
SelectItem::Wildcard => None,
})
.collect();
let order_rewritten: Vec<Expr> = stmt
.order_by
.iter()
.map(|o| rewrite_expr(&o.expr, &group_exprs, &agg_specs))
.collect();
let defer_enabled = correlated_eval.is_some()
&& !stmt.distinct
&& !having_rewritten
.as_ref()
.is_some_and(crate::expr_has_subquery)
&& !order_rewritten.iter().any(crate::expr_has_subquery);
let deferred: Vec<(usize, Expr)> = if defer_enabled {
items_rewritten
.iter()
.enumerate()
.filter_map(|(i, r)| {
r.as_ref()
.filter(|e| crate::expr_has_subquery(e))
.map(|e| (i, e.clone()))
})
.collect()
} else {
Vec::new()
};
let mut kept_synth: Vec<Row> = Vec::new();
let mut out_rows: Vec<Row> = Vec::new();
for srow in synth_rows {
if let Some(h) = &having_rewritten {
let cond = match correlated_eval {
Some(f) if crate::expr_has_subquery(h) => f(h, &srow, &synth_ctx)?,
_ => eval::eval_expr(h, &srow, &synth_ctx)?,
};
if !matches!(cond, Value::Bool(true)) {
continue;
}
}
let mut values: Vec<Value> = Vec::with_capacity(columns.len());
for (i, rewritten) in items_rewritten.iter().enumerate() {
let Some(rewritten) = rewritten else { continue };
if deferred.iter().any(|(c, _)| *c == i) {
values.push(Value::Null);
continue;
}
values.push(match correlated_eval {
Some(f) if crate::expr_has_subquery(rewritten) => f(rewritten, &srow, &synth_ctx)?,
_ => eval::eval_expr(rewritten, &srow, &synth_ctx)?,
});
}
kept_synth.push(srow);
out_rows.push(Row::new(values));
}
if !stmt.order_by.is_empty() {
let keys_meta: Vec<(bool, Option<bool>)> = stmt
.order_by
.iter()
.map(|o| (o.desc, o.nulls_first))
.collect();
let mut tagged: Vec<(Vec<Value>, Row, Row)> = kept_synth
.into_iter()
.zip(out_rows)
.map(|(s, o)| {
let mut keys = Vec::with_capacity(order_rewritten.len());
for e in &order_rewritten {
keys.push(match correlated_eval {
Some(f) if crate::expr_has_subquery(e) => f(e, &s, &synth_ctx)?,
_ => eval::eval_expr(e, &s, &synth_ctx)?,
});
}
Ok::<_, EvalError>((keys, s, o))
})
.collect::<Result<_, _>>()?;
tagged.sort_by(|a, b| {
use core::cmp::Ordering;
for (i, (ka, kb)) in a.0.iter().zip(b.0.iter()).enumerate() {
let (desc, nf) = keys_meta[i];
let cmp = crate::order_by_value_cmp(desc, nf, ka, kb);
if cmp != Ordering::Equal {
return cmp;
}
}
Ordering::Equal
});
kept_synth = Vec::with_capacity(tagged.len());
out_rows = Vec::with_capacity(tagged.len());
for (_, s, o) in tagged {
kept_synth.push(s);
out_rows.push(o);
}
}
let (synth_rows_out, synth_schema_out) = if deferred.is_empty() {
(Vec::new(), Vec::new())
} else {
(kept_synth, synth_schema.clone())
};
Ok(AggResult {
columns,
rows: out_rows,
deferred,
synth_rows: synth_rows_out,
synth_schema: synth_schema_out,
})
}
fn validate_agg_arities(stmt: &SelectStatement, _specs: &[AggSpec]) -> Result<(), EvalError> {
fn walk(e: &Expr) -> Result<(), EvalError> {
if let Expr::FunctionCall { name, args } = e {
let lower = name.to_ascii_lowercase();
let expected: Option<usize> = match lower.as_str() {
"count_star" => Some(0),
"count" | "sum" | "avg" | "min" | "max" | "array_agg"
| "bool_and" | "bool_or" | "every" => Some(1),
"string_agg" => Some(2),
_ => None,
};
if let Some(want) = expected
&& args.len() != want
{
return Err(EvalError::TypeMismatch {
detail: alloc::format!("{lower}() takes {want} arg(s), got {}", args.len()),
});
}
for a in args {
walk(a)?;
}
} else if let Expr::Binary { lhs, rhs, .. } = e {
walk(lhs)?;
walk(rhs)?;
} else if let Expr::Unary { expr, .. }
| Expr::Cast { expr, .. }
| Expr::IsNull { expr, .. } = e
{
walk(expr)?;
}
Ok(())
}
for item in &stmt.items {
if let SelectItem::Expr { expr, .. } = item {
walk(expr)?;
}
}
for o in &stmt.order_by {
walk(&o.expr)?;
}
if let Some(h) = &stmt.having {
walk(h)?;
}
Ok(())
}
fn collect_aggregates(e: &Expr, out: &mut Vec<AggSpec>) {
match e {
Expr::AggregateOrdered {
call,
order_by,
distinct,
} => {
if let Expr::FunctionCall { name, args } = call.as_ref() {
let lower = name.to_ascii_lowercase();
if is_aggregate_name(&lower) {
let canonical = if lower == "every" {
"bool_and".to_string()
} else {
lower
};
let spec = AggSpec {
name: canonical,
arg: args.first().cloned(),
arg2: if name.eq_ignore_ascii_case("string_agg") {
args.get(1).cloned()
} else {
None
},
distinct: *distinct,
order_by: order_by.clone(),
};
if !out.iter().any(|s| {
s.name == spec.name
&& s.arg == spec.arg
&& s.arg2 == spec.arg2
&& s.distinct == spec.distinct
&& s.order_by == spec.order_by
}) {
out.push(spec);
}
return;
}
}
collect_aggregates(call, out);
for o in order_by {
collect_aggregates(&o.expr, out);
}
}
Expr::FunctionCall { name, args } => {
let lower = name.to_ascii_lowercase();
if is_aggregate_name(&lower) {
let arg = if lower == "count_star" {
None
} else {
args.first().cloned()
};
let arg2 = if lower == "string_agg" {
args.get(1).cloned()
} else {
None
};
let canonical = if lower == "every" {
"bool_and".to_string()
} else {
lower
};
let spec = AggSpec {
name: canonical,
arg: arg.clone(),
arg2: arg2.clone(),
distinct: false,
order_by: Vec::new(),
};
if !out.iter().any(|s| {
s.name == spec.name
&& s.arg == spec.arg
&& s.arg2 == spec.arg2
&& !s.distinct
&& s.order_by == spec.order_by
}) {
out.push(spec);
}
} else {
for a in args {
collect_aggregates(a, out);
}
}
}
Expr::Binary { lhs, rhs, .. } => {
collect_aggregates(lhs, out);
collect_aggregates(rhs, out);
}
Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
collect_aggregates(expr, out);
}
Expr::Like { expr, pattern, .. } => {
collect_aggregates(expr, out);
collect_aggregates(pattern, out);
}
Expr::InList { expr, list, .. } => {
collect_aggregates(expr, out);
for item in list {
collect_aggregates(item, out);
}
}
Expr::Extract { source, .. } => collect_aggregates(source, out),
Expr::ScalarSubquery(_)
| Expr::Exists { .. }
| Expr::InSubquery { .. }
| Expr::WindowFunction { .. }
| Expr::Literal(_)
| Expr::Placeholder(_)
| Expr::Column(_) => {}
Expr::Array(items) => {
for elem in items {
collect_aggregates(elem, out);
}
}
Expr::ArraySubscript { target, index } => {
collect_aggregates(target, out);
collect_aggregates(index, out);
}
Expr::AnyAll { expr, array, .. } => {
collect_aggregates(expr, out);
collect_aggregates(array, out);
}
Expr::Case {
operand,
branches,
else_branch,
} => {
if let Some(o) = operand {
collect_aggregates(o, out);
}
for (w, t) in branches {
collect_aggregates(w, out);
collect_aggregates(t, out);
}
if let Some(e) = else_branch {
collect_aggregates(e, out);
}
}
}
}
fn update_state(
st: &mut AggState,
name: &str,
v: &Value,
arg2: Option<&Value>,
order_keys: Option<Vec<Value>>,
) -> Result<(), EvalError> {
let is_null = matches!(v, Value::Null);
match name {
"count_star" => st.count += 1,
"count" => {
if !is_null {
st.count += 1;
}
}
"sum" | "avg" => {
if is_null {
return Ok(());
}
st.count += 1;
match v {
Value::Int(n) => st.sum_int += i64::from(*n),
Value::BigInt(n) => st.sum_int += *n,
Value::Float(x) => {
st.use_float = true;
st.sum_float += *x;
}
other => {
return Err(EvalError::TypeMismatch {
detail: format!("sum/avg need numeric, got {:?}", other.data_type()),
});
}
}
}
"min" => {
if is_null {
return Ok(());
}
match &st.extreme {
None => st.extreme = Some(v.clone()),
Some(cur) => {
if value_cmp(v, cur) == core::cmp::Ordering::Less {
st.extreme = Some(v.clone());
}
}
}
}
"max" => {
if is_null {
return Ok(());
}
match &st.extreme {
None => st.extreme = Some(v.clone()),
Some(cur) => {
if value_cmp(v, cur) == core::cmp::Ordering::Greater {
st.extreme = Some(v.clone());
}
}
}
}
"string_agg" => {
if let Some(sep) = arg2
&& let Value::Text(s) = sep
{
st.separator = Some(s.clone());
}
if is_null {
return Ok(());
}
if let Value::Text(s) = v {
st.items.push(Value::Text(s.clone()));
if let Some(k) = order_keys {
st.item_keys.push(k);
}
st.count += 1;
} else {
return Err(EvalError::TypeMismatch {
detail: format!("string_agg requires text value, got {:?}", v.data_type()),
});
}
}
"array_agg" => {
st.items.push(v.clone());
if let Some(k) = order_keys {
st.item_keys.push(k);
}
st.count += 1;
}
"bool_and" => {
if is_null {
return Ok(());
}
let b = match v {
Value::Bool(b) => *b,
other => {
return Err(EvalError::TypeMismatch {
detail: format!("bool_and requires bool, got {:?}", other.data_type()),
});
}
};
st.bool_acc = Some(st.bool_acc.map_or(b, |acc| acc && b));
}
"bool_or" => {
if is_null {
return Ok(());
}
let b = match v {
Value::Bool(b) => *b,
other => {
return Err(EvalError::TypeMismatch {
detail: format!("bool_or requires bool, got {:?}", other.data_type()),
});
}
};
st.bool_acc = Some(st.bool_acc.map_or(b, |acc| acc || b));
}
_ => unreachable!("non-aggregate {name} in update_state"),
}
Ok(())
}
#[allow(clippy::cast_precision_loss)]
fn finalize(name: &str, st: &AggState) -> Value {
match name {
"count" | "count_star" => Value::BigInt(st.count),
"sum" => {
if st.count == 0 {
Value::Null
} else if st.use_float {
Value::Float(st.sum_float + (st.sum_int as f64))
} else {
Value::BigInt(st.sum_int)
}
}
"avg" => {
if st.count == 0 {
Value::Null
} else {
let total = if st.use_float {
st.sum_float + (st.sum_int as f64)
} else {
st.sum_int as f64
};
Value::Float(total / (st.count as f64))
}
}
"min" | "max" => st.extreme.clone().unwrap_or(Value::Null),
"string_agg" => {
if st.items.is_empty() {
return Value::Null;
}
let sep = st.separator.clone().unwrap_or_default();
let mut out = String::new();
for (i, item) in st.items.iter().enumerate() {
if i > 0 {
out.push_str(&sep);
}
if let Value::Text(s) = item {
out.push_str(s);
}
}
Value::Text(out)
}
"array_agg" => {
if st.items.is_empty() {
return Value::Null;
}
let probe = st.items.iter().find(|v| !v.is_null());
match probe.and_then(spg_storage::Value::data_type) {
Some(DataType::Int) | Some(DataType::SmallInt) => {
let items: Vec<Option<i32>> = st
.items
.iter()
.map(|v| match v {
Value::Int(n) => Some(*n),
Value::SmallInt(n) => Some(i32::from(*n)),
_ => None,
})
.collect();
Value::IntArray(items)
}
Some(DataType::BigInt) => {
let items: Vec<Option<i64>> = st
.items
.iter()
.map(|v| match v {
Value::BigInt(n) => Some(*n),
_ => None,
})
.collect();
Value::BigIntArray(items)
}
_ => {
let items: Vec<Option<String>> = st
.items
.iter()
.map(|v| match v {
Value::Text(s) => Some(s.clone()),
Value::Null => None,
other => Some(format!("{other:?}")),
})
.collect();
Value::TextArray(items)
}
}
}
"bool_and" | "bool_or" => st.bool_acc.map_or(Value::Null, Value::Bool),
_ => unreachable!(),
}
}
fn infer_agg_type(spec: &AggSpec, schema_cols: &[ColumnSchema]) -> DataType {
let arg_ty = spec
.arg
.as_ref()
.and_then(|a| crate::describe::describe_expr(a, schema_cols))
.map(|shape| shape.ty);
match spec.name.as_str() {
"count" | "count_star" => DataType::BigInt,
"sum" => match arg_ty {
Some(DataType::Float) => DataType::Float,
_ => DataType::BigInt,
},
"avg" => DataType::Float,
"string_agg" => DataType::Text,
"array_agg" => match arg_ty {
Some(DataType::Int | DataType::SmallInt) => DataType::IntArray,
Some(DataType::BigInt) => DataType::BigIntArray,
_ => DataType::TextArray,
},
"bool_and" | "bool_or" => DataType::Bool,
_ => arg_ty.unwrap_or(DataType::Text),
}
}
fn agg_or_group_type(e: &Expr, synth: &[ColumnSchema]) -> DataType {
if let Expr::Column(c) = e
&& let Some(s) = synth.iter().find(|s| s.name == c.name)
{
return s.ty;
}
crate::describe::describe_expr(e, synth)
.map(|shape| shape.ty)
.unwrap_or(DataType::Text)
}
fn rewrite_expr(e: &Expr, group_exprs: &[Expr], aggs: &[AggSpec]) -> Expr {
if let Expr::AggregateOrdered {
call,
order_by,
distinct,
} = e
&& let Expr::FunctionCall { name, args } = call.as_ref()
{
let lower = name.to_ascii_lowercase();
if is_aggregate_name(&lower) {
let canonical: &str = if lower == "every" { "bool_and" } else { &lower };
let arg = args.first().cloned();
let arg2 = if lower == "string_agg" {
args.get(1).cloned()
} else {
None
};
for (i, spec) in aggs.iter().enumerate() {
if spec.name == canonical
&& spec.arg == arg
&& spec.arg2 == arg2
&& spec.distinct == *distinct
&& spec.order_by == *order_by
{
return Expr::Column(spg_sql::ast::ColumnName {
qualifier: None,
name: format!("__agg_{i}"),
});
}
}
}
}
if let Expr::FunctionCall { name, args } = e {
let lower = name.to_ascii_lowercase();
if is_aggregate_name(&lower) {
let arg = if lower == "count_star" {
None
} else {
args.first().cloned()
};
let arg2 = if lower == "string_agg" {
args.get(1).cloned()
} else {
None
};
let canonical: &str = if lower == "every" {
"bool_and"
} else {
lower.as_str()
};
for (i, spec) in aggs.iter().enumerate() {
if spec.name == canonical
&& spec.arg == arg
&& spec.arg2 == arg2
&& !spec.distinct
&& spec.order_by.is_empty()
{
return Expr::Column(spg_sql::ast::ColumnName {
qualifier: None,
name: format!("__agg_{i}"),
});
}
}
}
}
for (i, g) in group_exprs.iter().enumerate() {
if g == e {
return Expr::Column(spg_sql::ast::ColumnName {
qualifier: None,
name: format!("__grp_{i}"),
});
}
}
match e {
Expr::AggregateOrdered {
call,
order_by,
distinct,
} => Expr::AggregateOrdered {
call: Box::new(rewrite_expr(call, group_exprs, aggs)),
distinct: *distinct,
order_by: order_by
.iter()
.map(|o| spg_sql::ast::OrderBy {
expr: rewrite_expr(&o.expr, group_exprs, aggs),
desc: o.desc,
nulls_first: o.nulls_first,
})
.collect(),
},
Expr::Binary { lhs, op, rhs } => Expr::Binary {
lhs: Box::new(rewrite_expr(lhs, group_exprs, aggs)),
op: *op,
rhs: Box::new(rewrite_expr(rhs, group_exprs, aggs)),
},
Expr::Unary { op, expr } => Expr::Unary {
op: *op,
expr: Box::new(rewrite_expr(expr, group_exprs, aggs)),
},
Expr::Cast { expr, target } => Expr::Cast {
expr: Box::new(rewrite_expr(expr, group_exprs, aggs)),
target: *target,
},
Expr::IsNull { expr, negated } => Expr::IsNull {
expr: Box::new(rewrite_expr(expr, group_exprs, aggs)),
negated: *negated,
},
Expr::FunctionCall { name, args } => Expr::FunctionCall {
name: name.clone(),
args: args
.iter()
.map(|a| rewrite_expr(a, group_exprs, aggs))
.collect(),
},
Expr::Like {
expr,
pattern,
negated,
case_insensitive,
} => Expr::Like {
expr: Box::new(rewrite_expr(expr, group_exprs, aggs)),
pattern: Box::new(rewrite_expr(pattern, group_exprs, aggs)),
negated: *negated,
case_insensitive: *case_insensitive,
},
Expr::Extract { field, source } => Expr::Extract {
field: *field,
source: Box::new(rewrite_expr(source, group_exprs, aggs)),
},
Expr::ScalarSubquery(s) => {
Expr::ScalarSubquery(Box::new(rewrite_group_keys_in_select(s, group_exprs)))
}
Expr::Exists { subquery, negated } => Expr::Exists {
subquery: Box::new(rewrite_group_keys_in_select(subquery, group_exprs)),
negated: *negated,
},
Expr::InSubquery {
expr,
subquery,
negated,
} => Expr::InSubquery {
expr: Box::new(rewrite_expr(expr, group_exprs, aggs)),
subquery: Box::new(rewrite_group_keys_in_select(subquery, group_exprs)),
negated: *negated,
},
Expr::WindowFunction { .. } | Expr::Literal(_) | Expr::Placeholder(_) | Expr::Column(_) => {
e.clone()
}
Expr::Array(items) => Expr::Array(
items
.iter()
.map(|elem| rewrite_expr(elem, group_exprs, aggs))
.collect(),
),
Expr::ArraySubscript { target, index } => Expr::ArraySubscript {
target: Box::new(rewrite_expr(target, group_exprs, aggs)),
index: Box::new(rewrite_expr(index, group_exprs, aggs)),
},
Expr::AnyAll {
expr,
op,
array,
is_any,
} => Expr::AnyAll {
expr: Box::new(rewrite_expr(expr, group_exprs, aggs)),
op: *op,
array: Box::new(rewrite_expr(array, group_exprs, aggs)),
is_any: *is_any,
},
Expr::InList {
expr,
list,
negated,
} => Expr::InList {
expr: Box::new(rewrite_expr(expr, group_exprs, aggs)),
list: list
.iter()
.map(|item| rewrite_expr(item, group_exprs, aggs))
.collect(),
negated: *negated,
},
Expr::Case {
operand,
branches,
else_branch,
} => Expr::Case {
operand: operand
.as_deref()
.map(|o| Box::new(rewrite_expr(o, group_exprs, aggs))),
branches: branches
.iter()
.map(|(w, t)| {
(
rewrite_expr(w, group_exprs, aggs),
rewrite_expr(t, group_exprs, aggs),
)
})
.collect(),
else_branch: else_branch
.as_deref()
.map(|e| Box::new(rewrite_expr(e, group_exprs, aggs))),
},
}
}
fn rewrite_group_keys_in_select(
s: &spg_sql::ast::SelectStatement,
group_exprs: &[Expr],
) -> spg_sql::ast::SelectStatement {
let mut out = s.clone();
let _ = crate::walk_select_exprs_mut(&mut out, &mut |e| {
*e = rewrite_expr(e, group_exprs, &[]);
Ok(())
});
out
}
fn encode_one(out: &mut String, v: &Value) {
match v {
Value::Null => out.push_str("N|"),
Value::SmallInt(n) => {
out.push('s');
out.push_str(&n.to_string());
out.push('|');
}
Value::Int(n) => {
out.push('I');
out.push_str(&n.to_string());
out.push('|');
}
Value::BigInt(n) => {
out.push('B');
out.push_str(&n.to_string());
out.push('|');
}
Value::Float(x) => {
out.push('F');
out.push_str(&x.to_string());
out.push('|');
}
Value::Bool(b) => {
out.push(if *b { 'T' } else { 'f' });
out.push('|');
}
Value::Text(s) => {
out.push('S');
out.push_str(s);
out.push('|');
}
Value::Vector(v) => {
out.push('V');
for x in v {
out.push_str(&x.to_string());
out.push(',');
}
out.push('|');
}
Value::Sq8Vector(q) => {
out.push('Q');
out.push_str(&q.min.to_string());
out.push('@');
out.push_str(&q.max.to_string());
out.push(':');
for b in &q.bytes {
out.push_str(&b.to_string());
out.push(',');
}
out.push('|');
}
Value::HalfVector(h) => {
out.push('H');
for b in &h.bytes {
out.push_str(&b.to_string());
out.push(',');
}
out.push('|');
}
Value::Numeric { scaled, scale } => {
out.push('D');
out.push_str(&scaled.to_string());
out.push('@');
out.push_str(&scale.to_string());
out.push('|');
}
Value::Date(d) => {
out.push('d');
out.push_str(&d.to_string());
out.push('|');
}
Value::Timestamp(t) => {
out.push('t');
out.push_str(&t.to_string());
out.push('|');
}
Value::Interval { months, micros } => {
out.push('i');
out.push_str(&months.to_string());
out.push('m');
out.push_str(µs.to_string());
out.push('|');
}
Value::Json(s) => {
out.push('j');
out.push_str(s);
out.push('|');
}
_ => {
out.push('?');
out.push_str(&format!("{v:?}"));
out.push('|');
}
}
}
pub(crate) fn encode_key_refs(vals: &[&Value]) -> String {
let mut out = String::new();
for v in vals {
encode_one(&mut out, v);
}
out
}
pub(crate) fn encode_key_refs_into(vals: &[&Value], out: &mut String) {
out.clear();
for v in vals {
encode_one(out, v);
}
}
pub(crate) fn encode_key(vals: &[Value]) -> String {
let mut out = String::new();
for v in vals {
encode_one(&mut out, v);
}
out
}
#[allow(clippy::cast_precision_loss)]
fn value_cmp(a: &Value, b: &Value) -> core::cmp::Ordering {
use core::cmp::Ordering::Equal;
match (a, b) {
(Value::Null, Value::Null) => Equal,
(Value::Null, _) => core::cmp::Ordering::Greater, (_, Value::Null) => core::cmp::Ordering::Less,
(Value::Int(x), Value::Int(y)) => x.cmp(y),
(Value::BigInt(x), Value::BigInt(y)) => x.cmp(y),
(Value::Int(x), Value::BigInt(y)) => i64::from(*x).cmp(y),
(Value::BigInt(x), Value::Int(y)) => x.cmp(&i64::from(*y)),
(Value::Float(x), Value::Float(y)) => x.partial_cmp(y).unwrap_or(Equal),
(Value::Int(x), Value::Float(y)) => f64::from(*x).partial_cmp(y).unwrap_or(Equal),
(Value::Float(x), Value::Int(y)) => x.partial_cmp(&f64::from(*y)).unwrap_or(Equal),
(Value::BigInt(x), Value::Float(y)) => (*x as f64).partial_cmp(y).unwrap_or(Equal),
(Value::Float(x), Value::BigInt(y)) => x.partial_cmp(&(*y as f64)).unwrap_or(Equal),
(Value::Text(x), Value::Text(y)) => x.cmp(y),
(Value::Bool(x), Value::Bool(y)) => x.cmp(y),
_ => Equal,
}
}