use super::frame::{BoundKind, CurrentRow, FrameCursor, FrameSpec, Membership};
use super::partition::PartitionRows;
use crate::aggregation::{
aggregate_value_with_args, observe_aggregate, AggregateAccumulator,
AggregateAccumulatorTemplate,
};
use uqa_core::Value;
use uqa_sql::ast::FrameExclusion;
use uqa_sql::{SQLError, ScalarExpr};
pub(super) struct WindowAggregate {
name: String,
args: crate::scalar::PreparedExpressions<Vec<ScalarExpr>>,
filter: Option<crate::scalar::PreparedExpressions<ScalarExpr>>,
template: AggregateAccumulatorTemplate,
budget_bytes: usize,
accumulator: Option<AggregateAccumulator>,
aggregated_base: i64,
aggregated_upto: i64,
result: Value,
}
impl WindowAggregate {
pub(super) fn new(
(name, args, filter): (&str, &[ScalarExpr], Option<&ScalarExpr>),
template: AggregateAccumulatorTemplate,
budget_bytes: usize,
) -> Self {
Self {
name: name.to_string(),
args: crate::scalar::PreparedExpressions::scalars(args.to_vec()),
filter: filter
.cloned()
.map(crate::scalar::PreparedExpressions::scalar),
template,
budget_bytes,
accumulator: None,
aggregated_base: 0,
aggregated_upto: 0,
result: Value::Null,
}
}
pub(super) fn begin_partition(&mut self) -> Result<(), SQLError> {
self.close()?;
self.aggregated_base = 0;
self.aggregated_upto = 0;
self.result = Value::Null;
Ok(())
}
pub(super) fn close(&mut self) -> Result<(), SQLError> {
self.accumulator
.take()
.map_or(Ok(()), |mut accumulator| accumulator.close())
}
pub(super) fn value(
&mut self,
frame: &FrameSpec,
cursor: &mut FrameCursor,
current: &mut CurrentRow,
rows: &mut PartitionRows<'_>,
) -> Result<Value, SQLError> {
let head = cursor.head(frame, current, rows)?;
if head < self.aggregated_base {
return Err(SQLError::Internal(
"window frame head moved backward".into(),
));
}
if self.aggregated_base == head
&& matches!(
frame.end,
BoundKind::UnboundedFollowing | BoundKind::CurrentRow
)
&& frame.exclusion == FrameExclusion::NoOthers
&& self.aggregated_base <= current.position
&& self.aggregated_upto > current.position
{
return Ok(self.result.clone());
}
if self.accumulator.is_none()
|| self.aggregated_base != head
|| frame.exclusion != FrameExclusion::NoOthers
|| self.aggregated_upto <= head
{
self.close()?;
self.accumulator = Some(self.template.instantiate(self.budget_bytes)?);
self.aggregated_upto = head;
}
self.aggregated_base = head;
let accumulator = self
.accumulator
.as_mut()
.ok_or_else(|| SQLError::Internal("window aggregate frame has no state".into()))?;
while self.aggregated_upto < rows.len() {
match cursor.membership(frame, current, rows, self.aggregated_upto)? {
Membership::After => break,
Membership::Outside => {}
Membership::Inside => {
let (name, args, filter) = (&self.name, &self.args, &self.filter);
rows.with_context(self.aggregated_upto, |context| {
if let Some(filter) = filter {
if !uqa_sql::expr::truthy(&crate::eval_scalar(
filter,
&(*context).with_function_states(filter.calls()),
)?) {
return Ok(());
}
}
observe_aggregate(
accumulator,
name,
args,
false,
&[],
&(*context).with_function_states(args.calls()),
)
})?;
}
}
self.aggregated_upto += 1;
}
self.result =
aggregate_value_with_args(&self.name, accumulator, &self.args, rows.enum_labels())?;
Ok(self.result.clone())
}
}