use std::cell::OnceCell;
use std::collections::{BTreeMap, HashSet};
use relate_core::{Error, Result, Value};
use relate_ir::{expr_row_vars, 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};
use super::classification::{ProjectionClass, ProjectionShape};
use super::feed::RowStream;
use super::order::{page, PageBounds};
use super::pattern_policies::MatchFold;
use super::post_merge::{adopt_rows, finish_projection, land_feed, Landed, LandedTail};
use super::scope::{return_columns, star_scope_names, visible_keys, ProjectionFields};
use super::{materialize_rows_strict, QueryResult, RowFeed};
pub(crate) fn projection_result_columns(
graph: &ExecGraph<'_>,
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(graph, 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(graph, 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_aggregate()
&& !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))
}
fn folding_shape(next: Option<&Clause>) -> Option<(ProjectionFields<'_>, ProjectionShape)> {
next_fold_shape(next).filter(|(_, shape)| shape.streams())
}
pub(crate) fn streams_into_projection(next: Option<&Clause>) -> bool {
folding_shape(next).is_some()
}
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, shape)) = folding_shape(next) else {
return Ok(None);
};
let class = class_slot.get_or_init(|| ProjectionClass::new(graph, &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 !graph.is_internal_key(key) {
let taken = std::mem::replace(value, Value::Null);
*value = self.apply(graph, taken);
}
}
}
}
}
#[derive(Clone, Copy)]
pub(crate) enum RowSource {
Bindings,
SinkProjected,
SinkLanded(LandedTail),
}
pub(crate) enum ProjectionInput<'a> {
Feed(RowFeed<'a>),
SinkProjected(Vec<Row>),
SinkLanded(Landed),
}
impl ProjectionInput<'_> {
fn probe(&self) -> &[Row] {
match self {
Self::Feed(feed) => feed.probe(),
Self::SinkProjected(rows) => rows,
Self::SinkLanded(landed) => &landed.rows,
}
}
fn complete(&mut self) -> Result<()> {
match self {
Self::Feed(RowFeed::Held(stream)) => stream.stop(),
Self::Feed(RowFeed::Folded(_)) | Self::SinkProjected(_) | Self::SinkLanded(_) => Ok(()),
}
}
}
pub(crate) fn project_rows(
ctx: ExecCtx<'_>,
input: ProjectionInput<'_>,
fields: &ProjectionFields<'_>,
inflate: bool,
scope: Option<&Row>,
) -> Result<Vec<Row>> {
let ExecCtx { graph, .. } = ctx;
let class = ProjectionClass::new(graph, fields, ProjectionShape::decide(fields)?);
project_classed(ctx, &class, input, inflate, scope)
}
pub(super) fn project_classed(
ctx: ExecCtx<'_>,
class: &ProjectionClass<'_>,
mut input: ProjectionInput<'_>,
inflate: bool,
scope: Option<&Row>,
) -> Result<Vec<Row>> {
let ExecCtx { graph, params, .. } = ctx;
let bounds = class.page_bounds(graph, params)?;
if bounds.answers_nothing() {
input.complete()?;
return Ok(Vec::new());
}
let (input, _input_charge) = prepare_input(input, class, bounds)?;
let mut cache = MaterializeCache::default();
let mut refresh = if inflate {
Refresh::Materialize(&mut cache)
} else {
Refresh::Identity
};
let merged = merge_rows(graph, params, class, input, scope, &mut refresh, bounds)?;
finish_projection(graph, params, class, merged, bounds)
}
fn merge_rows(
graph: &ExecGraph<'_>,
params: &BTreeMap<String, Value>,
class: &ProjectionClass<'_>,
input: ProjectionInput<'_>,
scope: Option<&Row>,
refresh: &mut Refresh<'_>,
bounds: PageBounds,
) -> Result<Landed> {
match (input, class.shape) {
(ProjectionInput::SinkProjected(mut rows), ProjectionShape::Plain) => {
refresh.rows(graph, &mut rows);
adopt_rows(graph, params, class, bounds, rows)
}
(ProjectionInput::SinkLanded(mut landed), ProjectionShape::Plain) => {
refresh.rows(graph, &mut landed.rows);
Ok(landed)
}
(ProjectionInput::SinkProjected(_) | ProjectionInput::SinkLanded(_), _) => Err(
Error::internal("a pre-projected feed reached a shape the sink never projects"),
),
(ProjectionInput::Feed(RowFeed::Held(stream)), ProjectionShape::Star) => {
star_rows(graph, params, stream, class, refresh, bounds)
}
(ProjectionInput::Feed(feed), ProjectionShape::Aggregate { .. }) => Ok(Landed {
rows: aggregate_rows(graph, params, feed, class, scope, refresh)?,
windowed: false,
streamed_distinct: false,
funnel_filtered_where: false,
streamed_page: false,
}),
(ProjectionInput::Feed(RowFeed::Held(stream)), ProjectionShape::Plain) => {
plain_rows(graph, params, stream, class, refresh, bounds)
}
(
ProjectionInput::Feed(RowFeed::Folded(_)),
ProjectionShape::Star | ProjectionShape::Plain,
) => Err(Error::internal(
"a folded feed reached a shape that cannot finish it",
)),
}
}
fn prepare_input<'a>(
input: ProjectionInput<'a>,
class: &ProjectionClass<'_>,
bounds: PageBounds,
) -> Result<(ProjectionInput<'a>, relate_core::tokens::WorkspaceCharge)> {
let (rows, wrap): (Vec<Row>, Rewrap<'a>) = match input {
ProjectionInput::SinkLanded(landed) => {
let charge = held_charge(&landed.rows)?;
return Ok((ProjectionInput::SinkLanded(landed), charge));
}
ProjectionInput::SinkProjected(rows) => (rows, ProjectionInput::SinkProjected),
ProjectionInput::Feed(RowFeed::Folded(folded)) => {
return Ok((
ProjectionInput::Feed(RowFeed::Folded(folded)),
relate_core::tokens::WorkspaceCharge::empty(),
));
}
ProjectionInput::Feed(RowFeed::Held(stream))
if class.folds_feed(bounds) && !stream.is_held() =>
{
return Ok((
ProjectionInput::Feed(RowFeed::Held(stream)),
relate_core::tokens::WorkspaceCharge::empty(),
));
}
ProjectionInput::Feed(RowFeed::Held(stream)) => (stream.materialize()?, held_input),
};
let input = wrap(if class.eager_paged {
page(rows, bounds)
} else {
rows
});
let charge = if matches!(class.shape, ProjectionShape::Aggregate { .. }) {
relate_core::tokens::WorkspaceCharge::empty()
} else {
held_charge(input.probe())?
};
Ok((input, charge))
}
fn held_charge(rows: &[Row]) -> Result<relate_core::tokens::WorkspaceCharge> {
relate_core::tokens::WorkspaceCharge::retain_with(|| crate::workspace::row_buffer_bytes(rows))
}
type Rewrap<'a> = fn(Vec<Row>) -> ProjectionInput<'a>;
fn held_input(rows: Vec<Row>) -> ProjectionInput<'static> {
ProjectionInput::Feed(RowFeed::Held(RowStream::held(rows)))
}
fn star_rows(
graph: &ExecGraph<'_>,
params: &BTreeMap<String, Value>,
stream: RowStream<'_>,
class: &ProjectionClass<'_>,
refresh: &mut Refresh<'_>,
bounds: PageBounds,
) -> Result<Landed> {
let built = |row| star_output_row(graph, params, class, refresh, row);
land_feed(graph, params, class, bounds, stream, built)
}
fn star_output_row(
graph: &ExecGraph<'_>,
params: &BTreeMap<String, Value>,
class: &ProjectionClass<'_>,
refresh: &mut Refresh<'_>,
r: Row,
) -> Result<Row> {
let mut n = Row::new();
for (k, v) in &r {
if !graph.is_internal_key(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)
}
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)?,
RowFeed::Held(stream) => aggregate_ex(
graph,
stream,
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>,
stream: RowStream<'_>,
class: &ProjectionClass<'_>,
refresh: &mut Refresh<'_>,
bounds: PageBounds,
) -> Result<Landed> {
let keep = keep_bindings(class);
let built = |row| plain_output_row(graph, params, class, &keep, refresh, row);
land_feed(graph, params, class, bounds, stream, built)
}
fn keep_bindings(class: &ProjectionClass<'_>) -> HashSet<String> {
let input_names: fn(&relate_ir::Expr, &mut HashSet<String>) = if class.fields.distinct {
expr_row_vars
} else {
expr_vars
};
let mut keep = HashSet::new();
if let Some(w) = class.plain_where() {
input_names(w, &mut keep);
}
for expr in class.order_keys.exprs() {
input_names(expr, &mut keep);
}
keep
}
fn plain_output_row(
graph: &ExecGraph<'_>,
params: &BTreeMap<String, Value>,
class: &ProjectionClass<'_>,
keep: &HashSet<String>,
refresh: &mut Refresh<'_>,
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();
for (name, value) in row.iter_mut() {
if keep.contains(name.as_str()) {
row2.insert(name.clone(), std::mem::replace(value, Value::Null));
}
}
for (name, value) in projected {
row2.insert(name, value);
}
drop(row);
Ok(row2)
}
#[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);
}
}