use std::collections::BTreeMap;
use relate_core::{CancelToken, Error, QueryClockGuard, Result, Value};
use relate_ir::{Clause, LabelExpr};
use relate_names::{SmallName, Token};
use relate_planner::{clause_mutates_store, clause_writes_store, plan_any_clause, LogicalPlan};
use crate::metrics::{PlanMetricsSink, PlanMetricsSite};
use crate::row::Row;
mod profiling;
use crate::graph::{Graph, QueryStats, SchemaSnapshot};
use crate::overlay::ExecGraph;
use crate::procedure_registry::call_writes_store;
use crate::StatementEffect;
pub(crate) use profiling::{
arm_store_profiling, count_frontier, count_neighbor_walks, count_vector_scan, count_zone_skip,
record_memos, record_walk_start, restore_store_profiling, take_walk_start, DeltaSnapshot,
StageDelta, WalkStartSwap, WalkTallies,
};
#[cfg(test)]
pub(crate) use profiling::{
disarm_store_profiling, memo_counters, take_frontier_counters, take_hop_expands,
take_neighbor_walks, take_node_reads, take_zone_skips,
};
pub(crate) mod agg_fold;
pub(crate) mod aggregate;
pub(crate) mod batch;
pub(crate) mod batch_tail;
pub(crate) mod bulk;
pub(crate) mod call;
pub(crate) mod candidates;
pub(crate) mod catalog;
pub(crate) mod catalog_schema;
pub(crate) mod catalog_show;
pub(crate) mod create_admission;
pub(crate) mod chunk;
pub(crate) mod classification;
mod clause_arms;
pub(crate) mod compose;
mod conditional_branches;
pub(crate) mod constraint_validation;
pub(crate) mod create;
pub(crate) mod ddl;
pub(crate) mod ddl_notifications;
pub(crate) mod ddl_options;
pub(crate) mod dispatch;
pub(crate) mod exists_probe;
pub(crate) mod expand;
pub(crate) mod expand_into;
#[cfg(test)]
mod expand_into_tests;
mod expr_safety;
pub(crate) mod far_probe;
pub(crate) mod feed;
pub(crate) mod fulltext;
pub(crate) mod gpm;
pub(crate) mod graph_type_schema;
mod load_csv;
mod match_arm;
mod plan_grade;
mod profile_chain;
mod profile_tick;
mod read;
pub(crate) mod join;
pub(crate) use join as hash_join;
pub(crate) use join::cross as hash_join_cross;
pub(crate) use join::semi_mask;
pub(crate) use join::varlen as hash_join_varlen;
pub(crate) mod frontier;
pub(crate) mod kernels;
pub(crate) mod match_cap;
pub(crate) mod match_chain;
pub(crate) mod match_clause;
pub(crate) mod match_consumer;
pub(crate) mod match_folds;
pub(crate) mod morsel_agg;
mod morsel_agg_types;
pub(crate) mod morsel_pipeline;
pub(crate) mod named_path;
pub(crate) mod one_path;
pub(crate) mod order;
pub(crate) mod pattern_policies;
pub(crate) mod pivot;
pub(crate) mod post_merge;
pub(crate) mod predicate_spec;
pub(crate) mod procedure_rows;
pub(crate) mod procedures;
pub(crate) mod project;
pub(crate) mod property_defaults;
pub(crate) mod pushdown;
pub(crate) mod rel_seek;
pub(crate) mod rider;
mod row_production;
#[cfg(test)]
mod row_production_tests;
pub(crate) mod scope;
pub(crate) mod search;
pub(crate) mod search_filters;
mod seeded_count;
#[cfg(test)]
mod seeded_count_tests;
pub(crate) mod shortest_eval;
pub(crate) mod sink;
mod stats_short_circuit;
pub(crate) mod subquery_eval;
pub(crate) mod top_k;
pub(crate) mod union;
pub(crate) mod unwind;
pub(crate) mod vector;
pub(crate) mod walk_plans;
pub(crate) mod write;
pub use catalog_show::catalog_create_statements;
pub use plan_grade::GradeProbe;
pub use read::{execute_read_at, execute_read_streaming_at};
pub(crate) fn read_path_rejection(c: &Clause) -> Option<&'static str> {
match c {
Clause::Foreach { .. } => Some("internal: FOREACH on read path"),
Clause::CallSubquery {
in_transactions: Some(_),
..
} => Some("internal: CALL IN TRANSACTIONS requires a write transaction"),
other if clause_mutates_store(other) => Some("internal: write clause on read path"),
_ => None,
}
}
pub(crate) fn mutates_store(clause: &Clause) -> bool {
match clause {
Clause::Call { name, .. } => name.with_str(call_writes_store),
other => clause_writes_store(other),
}
}
pub fn plan_mutates_store(plan: &LogicalPlan) -> bool {
plan_any_clause(plan, &mut mutates_store)
}
pub(crate) fn declare_plan_names(graph: &ExecGraph<'_>, plan: &LogicalPlan) {
plan_any_clause(plan, &mut |clause| {
let names = scope::clause_declared_names(clause);
graph.declare_names(names.iter().map(String::as_str));
false
});
}
use constraint_validation::validate_constraints;
use dispatch::{run_clauses, PartStrategies};
use scope::visible_keys;
pub(crate) use shortest_eval::{eval_shortest, ShortestWant};
pub(crate) use subquery_eval::{eval_collect_query, eval_count_query, eval_exists_query};
use crate::ctx::QueryCtx;
pub(crate) fn static_label_tree(expr: &LabelExpr, names: &[(SmallName, Token)]) -> bool {
fn leaves<'a>(expr: &'a LabelExpr, out: &mut Vec<&'a SmallName>) -> bool {
match expr {
LabelExpr::Label(name) => {
out.push(name);
true
}
LabelExpr::And(parts) | LabelExpr::Or(parts) => {
parts.iter().all(|part| leaves(part, out))
}
_ => false,
}
}
let mut found = Vec::new();
leaves(expr, &mut found)
&& found.len() == names.len()
&& found
.iter()
.all(|name| names.iter().any(|(n, _)| n == *name))
}
pub(crate) fn label_expr_ok(expr: &Option<LabelExpr>, names: &[(SmallName, Token)]) -> bool {
expr.as_ref().is_none_or(|e| static_label_tree(e, names))
}
pub struct QueryResult {
pub columns: Vec<String>,
pub rows: Vec<Vec<Value>>,
pub stats: QueryStats,
pub effect: StatementEffect,
}
impl QueryResult {
pub fn finished(
columns: Vec<String>,
rows: Vec<Vec<Value>>,
stats: QueryStats,
effect: StatementEffect,
) -> Self {
Self {
columns,
rows,
stats,
effect,
}
}
pub(crate) fn intermediate(
columns: Vec<String>,
rows: Vec<Vec<Value>>,
stats: QueryStats,
) -> Self {
Self::finished(columns, rows, stats, StatementEffect::None)
}
pub(crate) fn unit() -> Self {
Self::intermediate(Vec::new(), Vec::new(), QueryStats::default())
}
}
#[derive(Clone, Copy)]
pub struct ExecRequest<'a> {
pub plan: &'a LogicalPlan,
pub params: &'a BTreeMap<String, Value>,
pub query_text: &'a str,
pub principal: Option<&'a str>,
pub batch_commit: Option<&'a dyn crate::ctx::BatchCommit>,
pub plan_metrics: Option<&'a dyn crate::metrics::PlanMetricsSink>,
}
impl<'a> ExecRequest<'a> {
pub fn new(
plan: &'a LogicalPlan,
params: &'a BTreeMap<String, Value>,
query_text: &'a str,
) -> Self {
Self {
plan,
params,
query_text,
principal: None,
batch_commit: None,
plan_metrics: None,
}
}
}
pub struct ReadAdmission<'a> {
pub graph: &'a Graph,
pub snapshot_ts: u64,
pub schema: &'a SchemaSnapshot,
pub request: ExecRequest<'a>,
pub cancel: Option<&'a CancelToken>,
pub ontology_document: Option<&'a str>,
}
pub(crate) fn close_write_boundary(graph: &ExecGraph<'_>) -> Result<()> {
property_defaults::apply_property_defaults(graph)?;
validate_constraints(graph)
}
pub fn execute(graph: &ExecGraph<'_>, request: &ExecRequest<'_>) -> Result<QueryResult> {
let (result, attempted) = run_statement(graph, request)?;
close_write_boundary(graph)?;
finish_statement(result, graph, attempted)
}
#[cfg(test)]
pub(crate) fn execute_unvalidated(
graph: &ExecGraph<'_>,
request: &ExecRequest<'_>,
) -> Result<QueryResult> {
let (result, attempted) = run_statement(graph, request)?;
finish_statement(result, graph, attempted)
}
fn run_statement(graph: &ExecGraph<'_>, request: &ExecRequest<'_>) -> Result<(QueryResult, bool)> {
let entry = begin_statement_entry(graph, request)?;
let result = walk_statement(
graph,
request.plan,
vec![entry.root],
request.plan_metrics,
|part_clauses, part_seeds, site, strategies| {
let (mut rows, last) = run_clauses(
graph,
part_clauses,
request.params,
part_seeds,
entry.ctx,
site,
Some(strategies),
)?;
Ok(call::concluding_part_result(
graph,
part_clauses,
&mut rows,
last,
graph.stats(),
))
},
)?;
Ok((result, entry.attempted))
}
struct StatementEntry<'q> {
root: Row,
attempted: bool,
ctx: QueryCtx<'q>,
_clock: QueryClockGuard,
}
fn begin_statement_entry<'q>(
graph: &ExecGraph<'_>,
request: &'q ExecRequest<'q>,
) -> Result<StatementEntry<'q>> {
let root = graph.begin_statement(request.plan);
graph.check_cancelled()?;
let clock = QueryClockGuard::within(graph.transaction_clock());
let attempted = plan_mutates_store(request.plan);
let ctx = QueryCtx::new(request.query_text)
.with_principal(request.principal)
.with_batch_commit(request.batch_commit);
Ok(StatementEntry {
root,
attempted,
ctx,
_clock: clock,
})
}
fn finish_statement(
mut result: QueryResult,
graph: &ExecGraph<'_>,
attempted: bool,
) -> Result<QueryResult> {
result.effect = StatementEffect::from_facts(attempted, graph.applied_ops() > 0);
let result = finish_tokens(result)?;
graph.check_result_expansion(&result.rows)?;
Ok(result)
}
fn finish_tokens(result: QueryResult) -> Result<QueryResult> {
relate_core::tokens::poll()?;
Ok(result)
}
pub(crate) fn result_seed_rows(result: &QueryResult) -> Vec<Row> {
result
.rows
.iter()
.map(|values| {
result
.columns
.iter()
.enumerate()
.map(|(i, name)| {
(
name.clone(),
values
.get(i)
.cloned()
.expect("QueryResult rows are rectangular with respect to its columns"),
)
})
.collect()
})
.collect()
}
pub(crate) fn rows_as_result(graph: &ExecGraph<'_>, rows: &[Row]) -> QueryResult {
let mut columns = rows
.first()
.map(|row| visible_keys(graph, row))
.unwrap_or_default();
columns.sort();
let data = rows
.iter()
.map(|row| {
read_declared_columns(row, &columns, Missing::Null)
.expect("padding a missing result column with null is infallible")
})
.collect();
QueryResult::intermediate(columns, data, graph.stats())
}
#[derive(Clone, Copy)]
pub(crate) enum Missing {
Null,
Error,
}
fn declared_cell(value: Option<Value>, column: &str, missing: Missing) -> Result<Value> {
match (value, missing) {
(Some(value), _) => Ok(value),
(None, Missing::Null) => Ok(Value::Null),
(None, Missing::Error) => Err(missing_column_error(column)),
}
}
pub(crate) fn missing_column_error(column: &str) -> Error {
Error::internal(format!("row is missing declared result column {column:?}"))
}
pub(crate) fn take_declared_columns(
row: &mut Row,
columns: &[String],
missing: Missing,
) -> Result<Vec<Value>> {
columns
.iter()
.map(|column| declared_cell(row.take_value(column), column, missing))
.collect()
}
pub(crate) fn read_declared_columns(
row: &Row,
columns: &[String],
missing: Missing,
) -> Result<Vec<Value>> {
columns
.iter()
.map(|column| declared_cell(row.get(column).cloned(), column, missing))
.collect()
}
fn materialize_rows_with(
rows: &mut [Row],
columns: &[String],
missing: Missing,
) -> Result<Vec<Vec<Value>>> {
rows.iter_mut()
.map(|row| take_declared_columns(row, columns, missing))
.collect()
}
pub(crate) fn materialize_rows(rows: &mut [Row], columns: &[String]) -> Vec<Vec<Value>> {
materialize_rows_with(rows, columns, Missing::Null)
.expect("padding a missing result column with null is infallible")
}
pub(crate) fn materialize_rows_strict(
rows: &mut [Row],
columns: &[String],
) -> Result<Vec<Vec<Value>>> {
materialize_rows_with(rows, columns, Missing::Error)
}
pub(crate) enum RowFeed<'a> {
Held(feed::RowStream<'a>),
Folded(Box<aggregate::Aggregation<'a>>),
}
impl<'a> RowFeed<'a> {
pub(crate) fn probe(&self) -> &[Row] {
match self {
RowFeed::Held(stream) => stream.probe(),
RowFeed::Folded(_) => &[],
}
}
}
fn walk_statement(
graph: &ExecGraph<'_>,
plan: &LogicalPlan,
seeds: Vec<Row>,
sink: Option<&dyn PlanMetricsSink>,
run_part: impl Fn(
&[Clause],
Vec<Row>,
Option<PlanMetricsSite<'_>>,
PartStrategies<'_>,
) -> Result<QueryResult>,
) -> Result<QueryResult> {
fn walk_stages(
plan: &LogicalPlan,
stage: usize,
seeds: Vec<Row>,
sink: Option<&dyn PlanMetricsSink>,
run_part: &impl Fn(
&[Clause],
Vec<Row>,
Option<PlanMetricsSite<'_>>,
PartStrategies<'_>,
) -> Result<QueryResult>,
) -> Result<QueryResult> {
let site = |part: usize| sink.map(|sink| PlanMetricsSite::at(sink, stage, part));
let result = if plan.parts.len() == 1 {
run_part(
plan.parts[0].as_slice(),
seeds,
site(0),
PartStrategies::for_part(plan, 0),
)?
} else {
union::fold_parts(plan, |part, part_clauses| {
run_part(
part_clauses,
seeds.clone(),
site(part),
PartStrategies::for_part(plan, part),
)
})?
};
match &plan.next {
Some(next) => walk_stages(
next,
stage + 1,
next_seeds(&result, plan.parts.iter().map(|p| p.as_slice())),
sink,
run_part,
),
None => Ok(result),
}
}
let result = walk_stages(plan, 1, seeds, sink, &run_part)?;
report_statement_memos(graph, sink);
Ok(result)
}
fn report_statement_memos(graph: &ExecGraph<'_>, sink: Option<&dyn PlanMetricsSink>) {
if let Some(sink) = sink {
sink.record_statement_memos(graph.construct_memo_record());
}
}
pub(crate) fn next_seeds<'p>(
result: &QueryResult,
parts: impl Iterator<Item = &'p [Clause]>,
) -> Vec<Row> {
let mut seeds = result_seed_rows(result);
if seeds.is_empty() && row_production::parts_have_unit_output(parts) {
seeds.push(Row::new());
}
seeds
}
#[cfg(test)]
mod aggregate_charge_tests;
#[cfg(test)]
mod aggregate_footprint_tests;
#[cfg(test)]
mod aggregate_percentile_tests;
#[cfg(test)]
mod aggregate_pool_tests;
#[cfg(test)]
mod aggregate_tests;
#[cfg(test)]
mod batch_limit_tests;
#[cfg(test)]
mod batch_tests;
#[cfg(test)]
mod breaker_stream_tests;
#[cfg(test)]
mod chunk_tests;
#[cfg(test)]
mod conditional_tests;
mod count_stats;
#[cfg(test)]
mod count_stats_tests;
#[cfg(test)]
mod direct_fold_tests;
#[cfg(test)]
mod effect_tests;
#[cfg(test)]
mod exists_probe_tests;
#[cfg(test)]
mod expand_tests;
#[cfg(test)]
mod far_node_tests;
mod foreach;
#[cfg(test)]
mod foreach_tests;
pub mod graph_stats;
#[cfg(test)]
mod graph_stats_key_tests;
#[cfg(test)]
mod graph_stats_tests;
#[cfg(test)]
mod hub_join_gate_tests;
#[cfg(test)]
mod id_seek_tests;
mod index_aggregates;
#[cfg(test)]
mod index_aggregates_tests;
#[cfg(test)]
mod integer_arg_tests;
#[cfg(test)]
mod kernels_tests;
mod label_set_groups;
#[cfg(test)]
mod label_set_groups_tests;
#[cfg(test)]
mod limit_where_tests;
#[cfg(test)]
mod match_chain_tests;
#[cfg(test)]
mod match_fold_tests;
#[cfg(test)]
mod match_memory_tests;
#[cfg(test)]
mod morsel_agg_tests;
#[cfg(test)]
mod morsel_pipeline_tests;
#[cfg(test)]
mod nested_eval_tests;
#[cfg(test)]
mod one_hop_fold_tests;
#[cfg(test)]
mod path_fold_lookup_tests;
#[cfg(test)]
mod path_fold_tests;
#[cfg(test)]
mod pivot_tests;
#[cfg(test)]
mod plan_grade_tests;
#[cfg(test)]
mod predicate_spec_tests;
#[cfg(test)]
mod procedures_tests;
#[cfg(test)]
mod profiling_tests;
#[cfg(test)]
mod project_tests;
#[cfg(test)]
mod pushdown_tests;
#[cfg(test)]
mod range_start_tests;
#[cfg(test)]
mod rel_list_binding_tests;
#[cfg(test)]
mod rel_seek_tests;
#[cfg(test)]
mod seek_readiness_tests;
#[cfg(test)]
mod set_labels_function_tests;
mod shortcut_common;
#[cfg(test)]
mod shortest_expression_tests;
#[cfg(test)]
mod shortest_path_tests;
#[cfg(test)]
mod subquery_eval_tests;
#[cfg(test)]
pub(crate) mod test_support;
#[cfg(test)]
mod text_seek_tests;
#[cfg(test)]
mod walk_plans_tests;
#[cfg(test)]
mod write_tests;