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};
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, land_feed, Landed, LandedTail};
use super::scope::{return_columns, star_scope_names, visible_keys, ProjectionFields};
use super::{materialize_rows_strict, QueryResult, RowFeed};
use crate::consumer::{BatchFlow, StreamSink};
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 stream_terminal_return(
ctx: ExecCtx<'_>,
mut stream: RowStream<'_>,
sink: &mut StreamSink<'_>,
fields: &ProjectionFields<'_>,
items: &[Projection],
clauses: &[Clause],
rows_from: RowSource,
) -> Result<QueryResult> {
let graph = ctx.graph;
let announce = |sink: &mut StreamSink<'_>, rows: &[Row]| -> Result<Vec<String>> {
let announced = projection_result_columns(graph, items, rows, clauses);
sink.columns(&announced)?;
Ok(announced)
};
let mut columns: Option<Vec<String>> = None;
while let Some(batch) = stream.next_batch()? {
let batch = batch.into_vec();
let input = match rows_from {
RowSource::Bindings => ProjectionInput::Feed(RowFeed::Held(RowStream::held(batch))),
RowSource::SinkProjected => ProjectionInput::SinkProjected(batch),
RowSource::SinkLanded(_) => {
return Err(Error::internal(
"a landed sink reached the streaming terminal",
))
}
};
let mut rows = project_rows(ctx, input, fields, true, None)?;
let announced = match columns.take() {
Some(announced) => announced,
None => announce(sink, &rows)?,
};
let cells = materialize_rows_strict(&mut rows, &announced)?;
columns = Some(announced);
graph.check_result_expansion(&cells)?;
if matches!(sink.batch(cells)?, BatchFlow::Stop) {
stream.stop()?;
return Err(Error::cancelled());
}
}
let columns = match columns {
Some(columns) => columns,
None => announce(sink, &[])?,
};
Ok(QueryResult::intermediate(
columns,
Vec::new(),
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.subclause_aggregates()
}
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(()),
}
}
fn reservation(
&self,
class: &ProjectionClass<'_>,
) -> Result<relate_core::tokens::WorkspaceCharge> {
match self {
Self::Feed(RowFeed::Folded(_)) => Ok(relate_core::tokens::WorkspaceCharge::empty()),
Self::Feed(RowFeed::Held(stream)) if !stream.is_held() => {
Ok(relate_core::tokens::WorkspaceCharge::empty())
}
_ if matches!(class.shape, ProjectionShape::Aggregate { .. }) => {
Ok(relate_core::tokens::WorkspaceCharge::empty())
}
settled => crate::workspace::charge_row_buffer(settled.probe()),
}
}
}
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 landed = merge_rows(graph, params, class, input, scope, &mut refresh, bounds)?;
landed.finish(graph, params, class, 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, 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(LandedTail::untouched()
.into_landed(aggregate_rows(graph, params, feed, class, scope, refresh)?))
}
(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 input = ProjectionInput::SinkLanded(landed);
let charge = input.reservation(class)?;
return Ok((input, charge));
}
ProjectionInput::SinkProjected(rows) => (rows, ProjectionInput::SinkProjected),
ProjectionInput::Feed(RowFeed::Folded(folded)) => {
let input = ProjectionInput::Feed(RowFeed::Folded(folded));
let charge = input.reservation(class)?;
return Ok((input, charge));
}
ProjectionInput::Feed(RowFeed::Held(stream))
if class.folds_feed(bounds) && !stream.is_held() =>
{
let input = ProjectionInput::Feed(RowFeed::Held(stream));
let charge = input.reservation(class)?;
return Ok((input, charge));
}
ProjectionInput::Feed(RowFeed::Held(stream)) => (stream.materialize()?, held_input),
};
let input = wrap(if class.eager_paged {
page(rows, bounds)
} else {
rows
});
let charge = input.reservation(class)?;
Ok((input, charge))
}
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);
}
}
#[cfg(test)]
mod maps_each_row_tests {
use super::*;
use crate::exec::test_support::clauses_of;
fn maps(cypher: &str) -> bool {
let clauses = clauses_of(cypher);
let fields = clauses
.iter()
.find_map(ProjectionFields::from_clause)
.expect("a projection");
maps_each_row(&fields)
}
#[test]
fn only_a_pure_map_streams() {
assert!(maps("MATCH (n) WITH n.x AS x WHERE x > 1 RETURN x"));
assert!(maps("MATCH (n) RETURN n.x AS x"));
for breaker in [
"MATCH (n) RETURN DISTINCT n.x AS x",
"MATCH (n) RETURN count(n) AS c",
"MATCH (n) RETURN n.x AS x ORDER BY x",
"MATCH (n) RETURN n.x AS x SKIP 1",
"MATCH (n) RETURN n.x AS x LIMIT 1",
"MATCH (n) WITH n.x AS x WHERE count(x) > 1 RETURN x",
] {
assert!(!maps(breaker), "{breaker}");
}
}
}