use std::collections::HashSet;
use relate_core::Result;
use crate::ctx::{ExecCtx, QueryCtx};
use crate::exec::feed::{FeedSource, StreamedFeed};
use crate::exec::QueryResult;
use crate::overlay::ExecGraph;
use crate::row::Row;
use super::shared::{import_invariant_body, shared_execution_plan, SharedExecution};
use super::{empty_body_row, merge_body_export, row_product, SubquerySpec};
#[cfg(test)]
thread_local! {
static SHARED_BODY_RUNS: crate::graph::BuildCounter = const {
crate::graph::BuildCounter::new()
};
}
#[cfg(test)]
pub(crate) fn take_shared_body_runs() -> u64 {
SHARED_BODY_RUNS.with(crate::graph::BuildCounter::take)
}
#[cfg(test)]
fn count_shared_body_run() {
SHARED_BODY_RUNS.with(crate::graph::BuildCounter::bump);
}
#[cfg(not(test))]
fn count_shared_body_run() {}
pub(crate) struct SubquerySource<'a> {
query: &'a relate_ir::Query,
optional: bool,
scope: &'a relate_ir::CallScope,
qctx: QueryCtx<'a>,
mode: Mode,
staged: std::vec::IntoIter<Row>,
}
enum Mode {
PerRow,
Shared(SharedBody),
}
struct SharedBody {
plan: SharedExecution,
check: HashSet<String>,
body: Option<Box<QueryResult>>,
}
impl SharedBody {
fn rows_for(
&mut self,
ctx: ExecCtx<'_>,
row: &Row,
query: &relate_ir::Query,
scope: &relate_ir::CallScope,
qctx: QueryCtx<'_>,
) -> Result<Vec<Row>> {
let body: &QueryResult = match self.body.as_deref() {
Some(existing) => existing,
None => {
count_shared_body_run();
let body = super::call_body(scope.has_scope_clause().then_some(&self.check));
let executed = super::execute_query_scoped(
ctx.graph,
query,
ctx.params,
self.plan.seed.clone(),
body,
qctx,
)?;
self.body.insert(Box::new(executed))
}
};
Ok(body
.rows
.iter()
.map(|values| merge_body_export(row, &body.columns, values, &self.check))
.collect())
}
}
impl<'a> SubquerySource<'a> {
fn new(
graph: &ExecGraph<'_>,
spec: SubquerySpec<'a>,
rows: &[Row],
qctx: QueryCtx<'a>,
) -> Result<Self> {
let mode = match shared_execution_plan(graph, spec.query, spec.scope, rows)? {
Some(plan) => {
let check = plan.check();
if import_invariant_body(spec.query, &check) {
Mode::Shared(SharedBody {
plan,
check,
body: None,
})
} else {
Mode::PerRow
}
}
None => Mode::PerRow,
};
Ok(Self {
query: spec.query,
optional: spec.optional,
scope: spec.scope,
qctx,
mode,
staged: Vec::new().into_iter(),
})
}
}
impl FeedSource for SubquerySource<'_> {
fn open(&mut self, ctx: ExecCtx<'_>, row: Row) -> Result<bool> {
self.staged = Vec::new().into_iter();
let produced: Vec<Row> = match &mut self.mode {
Mode::PerRow => row_product(
ctx.graph,
&row,
self.optional,
self.query,
self.scope,
ctx.params,
self.qctx,
)?,
Mode::Shared(shared) => {
let produced = shared.rows_for(ctx, &row, self.query, self.scope, self.qctx)?;
if produced.is_empty() {
pad_rows(ctx.graph, row, self.optional, self.query, self.scope).collect()
} else {
produced
}
}
};
self.staged = produced.into_iter();
Ok(!self.staged.as_slice().is_empty())
}
fn charge_facts(&self) -> Result<(usize, usize)> {
let staged = self.staged.as_slice();
Ok((staged.len(), staged.first().map_or(0, Row::len)))
}
fn pull(&mut self, ctx: ExecCtx<'_>) -> Result<Option<Row>> {
ctx.graph.cancel_tick()?;
Ok(self.staged.next())
}
}
fn pad_rows(
graph: &ExecGraph<'_>,
row: Row,
optional: bool,
query: &relate_ir::Query,
scope: &relate_ir::CallScope,
) -> std::vec::IntoIter<Row> {
empty_body_row(graph, row, optional, query, scope)
.into_iter()
.collect::<Vec<_>>()
.into_iter()
}
pub(crate) fn call_subquery_feed<'a>(
ctx: ExecCtx<'a>,
qctx: QueryCtx<'a>,
rows: Vec<Row>,
spec: SubquerySpec<'a>,
profiled: bool,
) -> Result<StreamedFeed<'a>> {
let source = SubquerySource::new(ctx.graph, spec, &rows, qctx)?;
Ok(StreamedFeed::new(ctx, rows, Box::new(source), profiled))
}
pub(crate) fn exec_call_subquery<'a>(
ctx: ExecCtx<'a>,
qctx: QueryCtx<'a>,
rows: Vec<Row>,
spec: SubquerySpec<'a>,
) -> Result<Vec<Row>> {
call_subquery_feed(ctx, qctx, rows, spec, false)?.materialize()
}