use std::cell::OnceCell;
use std::collections::{BTreeMap, HashSet};
use relate_core::{Error, Result, Value};
use relate_ir::{Clause, Projection};
use crate::ctx::ExecCtx;
use crate::eval::{eval, expr_vars, is_agg_expr};
use crate::overlay::{ExecGraph, MaterializeCache};
use crate::row::Row;
use super::aggregate::{aggregate_ex, Aggregation, WhereMode};
use super::classification::{may_cut, ProjectionClass, ProjectionShape};
use super::order::{page, PageBounds};
use super::pattern_policies::MatchFold;
use super::post_merge::{adopt_rows, finish_projection, land_feed, Landed};
use super::scope::{
is_internal_column, return_columns, star_scope_names, visible_keys, ProjectionFields,
};
use super::{materialize_rows_strict, QueryResult, RowFeed};
pub(crate) fn projection_result_columns(
items: &[Projection],
rows: &[Row],
clauses: &[Clause],
) -> Vec<String> {
return_columns(items, || match rows.first() {
None => star_scope_names(clauses),
Some(row) => {
let mut keys = visible_keys(row);
keys.sort();
keys
}
})
}
pub(crate) fn return_result(
graph: &ExecGraph<'_>,
items: &[Projection],
clauses: &[Clause],
rows: &mut [Row],
) -> Result<QueryResult> {
let columns = projection_result_columns(items, rows, clauses);
let data = materialize_rows_strict(rows, &columns)?;
Ok(QueryResult::intermediate(columns, data, graph.stats()))
}
pub(crate) fn maps_each_row(fields: &ProjectionFields<'_>) -> bool {
!fields.distinct
&& fields.group_by.is_none()
&& fields.order.is_empty()
&& fields.skip.is_none()
&& fields.limit.is_none()
&& !fields.items.iter().any(|item| is_agg_expr(&item.expr))
&& !fields.where_clause.is_some_and(is_agg_expr)
}
fn next_fold_shape<'a>(
next: Option<&'a Clause>,
) -> Option<(ProjectionFields<'a>, ProjectionShape)> {
let fields = next.and_then(ProjectionFields::from_clause)?;
let shape = ProjectionShape::decide(&fields).ok()?;
Some((fields, shape))
}
pub(crate) fn streams_into_projection(next: Option<&Clause>) -> bool {
next_fold_shape(next).is_some_and(|(_, shape)| shape.streams())
}
pub(crate) fn unwind_streams_into(next: Option<&Clause>) -> bool {
next_fold_shape(next).is_some_and(|(fields, shape)| shape.streams() || may_cut(&fields))
}
fn open_fold<'a>(
graph: &ExecGraph<'_>,
class: &'a ProjectionClass<'a>,
params: &'a BTreeMap<String, Value>,
scope: Option<&'a Row>,
) -> Result<Aggregation<'a>> {
Aggregation::open(
graph,
&[],
class.fields.items,
class.fields.group_by,
params,
&class.group_subclauses(scope),
)
}
pub(crate) fn open_match_fold<'a>(
graph: &ExecGraph<'_>,
next: Option<&'a Clause>,
class_slot: &'a OnceCell<ProjectionClass<'a>>,
params: &'a BTreeMap<String, Value>,
scope: Option<&'a Row>,
) -> Result<Option<MatchFold<'a>>> {
if class_slot.get().is_some() {
return Ok(None);
}
let Some(fields) = next.and_then(ProjectionFields::from_clause) else {
return Ok(None);
};
let shape = match ProjectionShape::decide(&fields) {
Ok(shape) if shape.streams() => shape,
_ => return Ok(None),
};
let class = class_slot.get_or_init(|| ProjectionClass::new(&fields, shape));
open_fold(graph, class, params, scope).map(|aggregation| Some(MatchFold::new(aggregation)))
}
enum Refresh<'a> {
Identity,
Materialize(&'a mut MaterializeCache),
}
impl Refresh<'_> {
fn apply(&mut self, graph: &ExecGraph<'_>, value: Value) -> Value {
match self {
Refresh::Identity => value,
Refresh::Materialize(cache) => graph.materialize_cached(value, cache),
}
}
fn rows(&mut self, graph: &ExecGraph<'_>, rows: &mut [Row]) {
if matches!(self, Refresh::Identity) {
return;
}
for row in rows {
for (key, value) in row.iter_mut() {
if !is_internal_column(key) {
let taken = std::mem::replace(value, Value::Null);
*value = self.apply(graph, taken);
}
}
}
}
}
pub(crate) enum RowSource {
Bindings,
SinkProjected,
}
pub(crate) fn project_rows(
ctx: ExecCtx<'_>,
feed: RowFeed<'_>,
fields: &ProjectionFields<'_>,
inflate: bool,
source: RowSource,
scope: Option<&Row>,
) -> Result<Vec<Row>> {
let ExecCtx { graph, params, .. } = ctx;
let class = ProjectionClass::new(fields, ProjectionShape::decide(fields)?);
let bounds = class.page_bounds(graph, params)?;
if bounds.answers_nothing() {
return Ok(Vec::new());
}
let feed = materialize_feed(feed, &class, bounds)?;
let _held_feed = if class.window_keep(bounds).is_some() {
Some(relate_core::tokens::WorkspaceCharge::retain_with(|| {
crate::workspace::row_buffer_bytes(feed.probe())
})?)
} else {
None
};
let mut cache = MaterializeCache::default();
let mut refresh = if inflate {
Refresh::Materialize(&mut cache)
} else {
Refresh::Identity
};
let merged = match (source, class.shape) {
(RowSource::SinkProjected, ProjectionShape::Plain) => {
let RowFeed::Held(mut rows) = feed else {
return Err(Error::internal(
"a sink-projected feed arrived as a generated feed",
));
};
refresh.rows(graph, &mut rows);
adopt_rows(graph, params, &class, bounds, rows)?
}
(RowSource::SinkProjected, _) => {
return Err(Error::internal(
"a sink-projected feed reached a shape the sink never projects",
))
}
(RowSource::Bindings, shape) => match shape {
ProjectionShape::Star => star_rows(graph, params, feed, &class, &mut refresh, bounds)?,
ProjectionShape::Aggregate { .. } => Landed {
rows: aggregate_rows(graph, params, feed, &class, scope, &mut refresh)?,
windowed: false,
},
ProjectionShape::Plain => {
plain_rows(graph, params, feed, &class, &mut refresh, bounds)?
}
},
};
finish_projection(graph, params, &class, merged, bounds)
}
fn materialize_feed<'a>(
feed: RowFeed<'a>,
class: &ProjectionClass<'_>,
bounds: PageBounds,
) -> Result<RowFeed<'a>> {
let rows = match feed {
RowFeed::Held(rows) => rows,
unwind @ RowFeed::Unwind(_) if class.folds_feed(bounds) => return Ok(unwind),
folded @ RowFeed::Folded(_) => return Ok(folded),
RowFeed::Unwind(unwind) => unwind.materialize()?,
};
Ok(RowFeed::Held(if class.eager_paged {
page(rows, bounds)
} else {
rows
}))
}
fn star_rows(
graph: &ExecGraph<'_>,
params: &BTreeMap<String, Value>,
feed: RowFeed<'_>,
class: &ProjectionClass<'_>,
refresh: &mut Refresh<'_>,
bounds: PageBounds,
) -> Result<Landed> {
let built = |r: Row| -> Result<Row> {
let mut n = Row::new();
for (k, v) in &r {
if !is_internal_column(k) {
n.insert(k.clone(), refresh.apply(graph, v.clone()));
}
}
for (projection, name) in &class.value_items {
let value = eval(graph, &r, &projection.expr, params)?;
n.insert(name.clone(), refresh.apply(graph, value));
}
drop(r);
Ok(n)
};
land_feed(graph, params, class, bounds, feed, built)
}
fn aggregate_rows(
graph: &ExecGraph<'_>,
params: &BTreeMap<String, Value>,
feed: RowFeed<'_>,
class: &ProjectionClass<'_>,
scope: Option<&Row>,
refresh: &mut Refresh<'_>,
) -> Result<Vec<Row>> {
let mut agg = match feed {
RowFeed::Folded(aggregation) => aggregation.finish(graph)?,
feed => aggregate_ex(
graph,
feed,
class.fields.items,
class.fields.group_by,
params,
&class.group_subclauses(scope),
)?,
};
refresh.rows(graph, &mut agg);
Ok(agg)
}
fn plain_rows(
graph: &ExecGraph<'_>,
params: &BTreeMap<String, Value>,
feed: RowFeed<'_>,
class: &ProjectionClass<'_>,
refresh: &mut Refresh<'_>,
bounds: PageBounds,
) -> Result<Landed> {
let order_keys = &class.order_keys;
let where_mode = class.where_mode;
let mut keep = HashSet::new();
if let Some(w) = where_mode.and_then(WhereMode::plain) {
expr_vars(w, &mut keep);
}
for expr in order_keys.exprs() {
expr_vars(expr, &mut keep);
}
let built = |mut row: Row| -> Result<Row> {
let projected: Vec<(String, Value)> = class
.value_items
.iter()
.map(|(projection, name)| {
let val = eval(graph, &row, &projection.expr, params)?;
Ok((name.clone(), refresh.apply(graph, val)))
})
.collect::<Result<Vec<_>>>()?;
let mut row2 = Row::new();
let kept: Vec<String> = row
.keys()
.filter(|name| keep.contains(name.as_str()))
.cloned()
.collect();
for name in kept {
let value = row
.take_value(&name)
.expect("a key just read from the row is bound in it");
row2.insert(name, value);
}
for (name, value) in projected {
row2.insert(name, value);
}
drop(row);
Ok(row2)
};
land_feed(graph, params, class, bounds, feed, built)
}
#[cfg(test)]
mod refresh_tests {
use super::*;
use crate::graph::Graph;
use crate::row::{interned_schema_calls, RowNames};
#[test]
fn the_inflate_sweep_keeps_each_rows_schema() {
let names: Vec<String> = ["a", "b", "c", "d", "e", "f", "g", "h", "__ord0"]
.map(String::from)
.to_vec();
let schema = RowNames::new(&names);
let mut rows: Vec<Row> = (0..1000)
.map(|i| Row::from_names(&schema, (0..9).map(|c| Value::Int(i + c)).collect()))
.collect();
let graph = Graph::default();
let view = ExecGraph::read(&graph);
let mut cache = MaterializeCache::default();
let before = interned_schema_calls();
let snapshot = rows.clone();
let ptrs: Vec<_> = rows.iter().map(Row::schema_ptr).collect();
Refresh::Materialize(&mut cache).rows(&view, &mut rows);
assert_eq!(interned_schema_calls() - before, 0);
assert_eq!(
rows.iter().map(Row::schema_ptr).collect::<Vec<_>>(),
ptrs,
"the sweep replaced a row's shared schema"
);
assert_eq!(rows, snapshot);
}
}