relate-executor 1.5.0

In-memory graph and Cypher physical executor
Documentation
//! CIP-135 conditional (`WHEN … THEN …`) branches: one bucket per branch,
//! the taken branch run on its driving row. The row-shape classification
//! lives in `super::super::row_production` — the classification home —
//! and the branch-set model in `super::super::conditional_branches`;
//! this module keeps the executor.

use std::collections::BTreeMap;

use relate_core::{Result, Value};
use relate_ir::Query;

use crate::ctx::QueryCtx;

use super::{execute_query_seeded_in_scope, project_row, BodyScope};
use crate::eval::{bool_or_null, eval};
use crate::exec::conditional_branches::ConditionalBranches;
use crate::exec::row_production::body_projects_rows;
use crate::exec::scope::refresh_rows;
use crate::exec::{materialize_rows_strict, QueryResult};
use crate::overlay::ExecGraph;
use crate::row::Row;

/// Run the conditional over `rows` and return both the surviving rows — the
/// NEXT stage's seed — and the clause's finished statement result.
///
/// The result's column list is the clause's plan fact: every branch and
/// `ELSE` returns the same ordered names, so it holds for an empty result
/// exactly as for a non-empty one. The derivation is the planner's
/// [`relate_planner::conditional_declared_columns`], whose empty seed is
/// the same one the conditional's validation uses, so the executor's
/// materialization and the plan agree by construction.
pub(in crate::exec) fn exec_conditional(
    graph: &ExecGraph<'_>,
    rows: Vec<Row>,
    branches: &ConditionalBranches<'_>,
    params: &BTreeMap<String, Value>,
    qctx: QueryCtx<'_>,
) -> Result<(Vec<Row>, QueryResult)> {
    // One bucket per branch plus `ELSE`: the conditional's output is grouped
    // by branch in the branches' written order (Neo4j's observed order),
    // while each row is still driven on its own. The buckets are a
    // retaining container: each driving row's production is charged to the
    // running total before its rows land (ADR-0463), the same per-row
    // charge the feed spine's hold bills.
    let mut buckets: Vec<Vec<Row>> = vec![Vec::new(); branches.bucket_count()];
    let mut retained = graph.retain_bytes(0)?;
    // CIP-135's conditional is a per-row operator: a driving row's branch
    // predicate is evaluated against the state its predecessors left (the
    // taken branch body ran already), so a branch that writes is visible to
    // the next row's `WHEN` and a branch aggregates one incoming row at a
    // time — the NEXT-stage scenarios' "sees updates made by the branch of a
    // previous row" shape.
    for mut row in rows {
        // The row's element bindings were captured by the previous stage;
        // a predecessor's branch may have relabelled or changed them since,
        // so the predicate and the body read them again from the graph.
        refresh_rows(graph, std::slice::from_mut(&mut row));
        let Some((index, query)) = taken_branch(graph, &row, branches, params)? else {
            continue;
        };
        // The driving row is the branch body's importing scope: its bindings
        // stay visible through the body's whole NEXT chain (CIP-213), exactly
        // as a `CALL (…) { … }` body's imports do
        // (`NextStatementAcceptance` "By-table semantics: CALL and WHEN no
        // special behavior"). No star exclusion applies, so the branch runs
        // the body-scope core directly under `RowScope` — never the CALL
        // clause's form ([`super::call_body`]).
        let result = execute_query_seeded_in_scope(
            graph,
            query,
            params,
            vec![row.clone()],
            qctx,
            BodyScope::RowScope(&row),
        )?;
        // A body that projects no statement result (a write-only / `FINISH`
        // / DDL body) contributes no rows: its surviving seed row is a
        // pass-through, never a result. The branch still ran, so its writes
        // stand. The fact is read where it is used, on the taken branch's
        // own body — the same [`body_projects_rows`] classification the
        // seeding fold short-circuits over.
        if body_projects_rows(query) {
            retained.add_rows(graph, result.rows.len(), result.columns.len())?;
            append_query_rows(&mut buckets[index], result);
        }
    }
    let rows: Vec<Row> = buckets.into_iter().flatten().collect();
    let (raw_branches, raw_else) = branches.raw();
    let columns = relate_planner::conditional_declared_columns(raw_branches, raw_else)?;
    // The shared clause-exit tail records this clause's PROFILE tick from
    // the returned rows, so the projection runs on a copy: moving the cells
    // out here would make the operator report the nulled slots'
    // `memory_bytes` instead of its output rows'.
    let mut projected = rows.clone();
    let data = materialize_rows_strict(&mut projected, &columns)?;
    Ok((
        rows,
        QueryResult::intermediate(columns, data, graph.stats()),
    ))
}

/// The row's one taken branch, in source order — its bucket index and
/// query. `None` when no predicate holds and there is no `ELSE`: nothing
/// runs for the row. The `ELSE` body's index is one past the last `WHEN`
/// bucket.
fn taken_branch<'q>(
    graph: &ExecGraph<'_>,
    row: &Row,
    branches: &ConditionalBranches<'q>,
    params: &BTreeMap<String, Value>,
) -> Result<Option<(usize, &'q Query)>> {
    let (raw_branches, else_query) = branches.raw();
    for (index, (predicate, query)) in raw_branches.iter().enumerate() {
        let value = eval(graph, row, predicate, params)?;
        // A `WHEN` predicate is a boolean: the one requiring-site policy
        // (`eval::bool_or_null`) leaves the branch untaken on null/false and
        // rejects any other non-boolean value (Neo4j 22G03), never
        // truthy-coercing it.
        if let Some(true) = bool_or_null(&value, "WHEN predicate")? {
            return Ok(Some((index, query)));
        }
    }
    Ok(else_query.map(|query| (branches.else_index(), query)))
}

fn append_query_rows(out: &mut Vec<Row>, result: QueryResult) {
    for values in result.rows {
        out.push(project_row(&result.columns, &values).collect());
    }
}