use std::collections::BTreeMap;
use relate_core::Value;
use relate_ir::{classify_aggregate, AggregateKind, Expr, SINGLE_INPUT_AGGREGATES};
use crate::exec::aggregate::{agg_eval, discover, AggScope, FoldedGroup, GroupAccs};
use crate::overlay::ExecGraph;
use crate::row::Row;
pub(crate) fn node_value(id: i64) -> Value {
Value::Node(std::sync::Arc::new(relate_core::Node {
id,
labels: std::sync::Arc::new(vec!["V".into()]),
properties: std::sync::Arc::default(),
}))
}
pub(crate) fn agg_fn_over(name: &str, arg: Expr) -> Expr {
agg_call(name, arg, false)
}
fn agg_call(name: &str, arg: Expr, distinct: bool) -> Expr {
Expr::Function {
name: name.into(),
distinct,
args: vec![arg],
}
}
pub(crate) const OPERAND_COLUMN: &str = "x";
pub(crate) fn fold_group_rows<'e>(
graph: &ExecGraph<'_>,
group: &[Row],
exprs: impl IntoIterator<Item = &'e Expr>,
params: &BTreeMap<String, Value>,
) -> relate_core::Result<(FoldedGroup<'e>, u64)> {
let table = discover(graph, exprs, [], params)?;
let mut accs = GroupAccs::open(graph, table)?;
for row in group {
accs.offer(graph, row, params)?;
accs.settle(graph)?;
}
let billed = accs.billed();
let folded = accs.finish(graph, group.first(), params);
Ok((folded, billed))
}
pub(crate) fn agg_eval_rows(
graph: &ExecGraph<'_>,
group: &[Row],
expr: &Expr,
params: &BTreeMap<String, Value>,
) -> relate_core::Result<Value> {
let (folded, _) = fold_group_rows(graph, group, [expr], params)?;
agg_eval(
graph,
AggScope::of_group(&folded, group.first()),
expr,
params,
)
}
pub(crate) fn agg_fn(name: &str) -> Expr {
agg_fn_over(name, Expr::Variable(OPERAND_COLUMN.into()))
}
pub(crate) fn group_with_xs(xs: &[i64]) -> Vec<Row> {
group_with_vals(&xs.iter().map(|&i| Value::Int(i)).collect::<Vec<_>>())
}
pub(crate) fn group_with_vals(vals: &[Value]) -> Vec<Row> {
vals.iter()
.map(|v| {
let mut row = Row::new();
row.insert(OPERAND_COLUMN.into(), v.clone());
row
})
.collect()
}
pub(crate) fn percentile_fn(name: &str, p: f64) -> Expr {
percentile_fn_over(name, Expr::Variable(OPERAND_COLUMN.into()), p)
}
pub(crate) fn distinct_percentile(name: &str, p: f64) -> Expr {
percentile_call(name, Expr::Variable(OPERAND_COLUMN.into()), p, true)
}
pub(crate) fn single_input_calls() -> impl Iterator<Item = (&'static str, AggregateKind)> {
["count"]
.into_iter()
.chain(SINGLE_INPUT_AGGREGATES.iter().copied())
.map(|name| {
let kind = classify_aggregate(name).expect("the table names aggregate kinds");
(name, kind)
})
}
pub(crate) fn distinct_fn(name: &str) -> Expr {
agg_call(name, Expr::Variable(OPERAND_COLUMN.into()), true)
}
pub(crate) fn percentile_fn_over(name: &str, arg: Expr, p: f64) -> Expr {
percentile_call(name, arg, p, false)
}
fn percentile_call(name: &str, arg: Expr, p: f64, distinct: bool) -> Expr {
Expr::Function {
name: name.into(),
distinct,
args: vec![arg, Expr::Float(p)],
}
}
pub(crate) fn assert_charge_partition(label: &str, cap: u64, build: fn(&str) -> Expr) {
let mut g = crate::graph::Graph::default();
g.configure_expression_memory_limit(Some(cap));
let graph = ExecGraph::read(&g);
let group = group_with_xs(&(0..100_000).collect::<Vec<_>>());
for (name, kind) in single_input_calls() {
let call = format!("{label} {name}");
let result = agg_eval_rows(&graph, &group, &build(name), &BTreeMap::new());
if crate::eval::StreamFold::for_kind(kind).is_some() {
result.unwrap_or_else(|error| panic!("{call} streams, yet refused: {error}"));
} else {
let error = result
.err()
.unwrap_or_else(|| panic!("{call} retains, yet answered a value"));
assert_expression_cap(&error, cap);
}
}
}
pub(crate) fn duration(months: i64, days: i64, nanos: i128) -> Value {
Value::Temporal(relate_core::temporal::Temporal::Duration {
months,
days,
nanos,
})
}
pub(crate) fn assert_expression_cap(error: &relate_core::Error, cap: u64) -> u64 {
let relate_core::Error::Capacity {
used,
limit,
kind: relate_core::CapacityKind::Expression,
..
} = error
else {
panic!("the typed expression-capacity refusal at cap {cap}: {error}");
};
assert_eq!(*limit, cap, "{error}");
*used
}
pub(crate) fn assert_crossing_element(used: u64, cap: u64, one_element: u64) {
assert!(
used > cap && used <= cap + one_element,
"the refusal reports the crossing element ({used} over cap {cap}), \
not the whole container"
);
}
pub(crate) fn group_landing_bound(boundary: usize, largest_key: &Value) -> u64 {
crate::workspace::group_entry_insert_delta(
boundary,
&[crate::group_key::GroupKey::new(largest_key)],
) + crate::workspace::value_buffer_bytes(1)
}
pub(crate) fn assert_crossing_row(used: u64, cap: u64, bindings: usize) {
assert_crossing_element(
used,
cap,
crate::workspace::retained_rows_bytes(1, bindings),
);
}