use std::collections::BTreeMap;
use relate_core::tokens::WorkspaceCharge;
use relate_core::{Error, ErrorKind, Result, Value};
use relate_ir::{Clause, Query};
use super::{
execute_query_seeded, null_pad_call_row, row_product, scope_seed, stage_projects_rows,
SubquerySpec,
};
use crate::ctx::QueryCtx;
use crate::eval::eval;
use crate::exec::feed::RowStream;
use crate::exec::scope::star_scope_names;
use crate::metrics::PlanMetricsSite;
use crate::overlay::ExecGraph;
use crate::row::Row;
pub(crate) fn exec_call_in_transactions<'a>(
graph: &'a ExecGraph<'a>,
rows: RowStream<'a>,
spec: SubquerySpec<'a>,
tx: &'a relate_ir::InTransactions,
params: &'a BTreeMap<String, Value>,
qctx: QueryCtx<'a>,
record: Option<(PlanMetricsSite<'a>, usize)>,
) -> Result<RowStream<'a>> {
let status_name = tx.report_status.as_ref().map(|name| name.to_string());
let batch_pass = batch_pass_admission(spec.query);
Ok(RowStream::emitting_to_completion(
InTransactionsRows {
graph,
params,
qctx,
spec,
tx,
batch_pass,
input: rows,
batch_size: None,
batch_index: 0,
status_name,
pending: None,
breaking: false,
done: false,
},
record,
))
}
struct InTransactionsRows<'a> {
graph: &'a ExecGraph<'a>,
params: &'a BTreeMap<String, Value>,
qctx: QueryCtx<'a>,
spec: SubquerySpec<'a>,
batch_pass: bool,
tx: &'a relate_ir::InTransactions,
input: RowStream<'a>,
batch_size: Option<usize>,
batch_index: usize,
status_name: Option<String>,
pending: Option<InstalledBatch>,
breaking: bool,
done: bool,
}
struct InstalledBatch {
rows: std::vec::IntoIter<Row>,
_charge: WorkspaceCharge,
}
impl Iterator for InTransactionsRows<'_> {
type Item = Result<Row>;
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some(installed) = self.pending.as_mut() {
match installed.rows.next() {
Some(row) => return Some(Ok(row)),
None => self.pending = None,
}
}
if self.done {
return None;
}
match self.advance() {
Ok(true) => {}
Ok(false) => return None,
Err(error) => {
self.done = true;
return Some(Err(error));
}
}
}
}
}
impl InTransactionsRows<'_> {
fn advance(&mut self) -> Result<bool> {
let Some(rows) = self.next_batch()? else {
return Ok(false);
};
self.install(rows);
Ok(true)
}
fn next_batch(&mut self) -> Result<Option<ChargedRows>> {
if self.breaking {
return self.never_started_row();
}
match self.pull_batch()? {
Some(batch) => Ok(Some(self.run_batch(batch)?)),
None => Ok(None),
}
}
fn install(&mut self, batch: ChargedRows) {
self.pending = Some(InstalledBatch {
rows: batch.rows.into_iter(),
_charge: batch.charge,
});
}
fn never_started_row(&mut self) -> Result<Option<ChargedRows>> {
let Some(row) = self.input.next_row()? else {
return Ok(None);
};
let row = null_pad_call_row(self.graph, row, self.spec.query, self.spec.scope);
let mut batch = ChargedRows::new();
batch.push(row)?;
batch.stamp(&BatchOutcome::NeverStarted, self.status_name.as_deref())?;
Ok(Some(batch))
}
fn run_batch(&mut self, batch: ChargedRows) -> Result<ChargedRows> {
let snapshot = self.graph.scratch_snapshot();
let tx_id = format!("relate-inner-{}", self.batch_index + 1);
self.batch_index += 1;
let mut batch_out = ChargedRows::new();
let attempt = (|| -> Result<()> {
if self.batch_pass {
pass_batch_rows(
self.graph,
&batch.rows,
&self.spec,
self.params,
self.qctx,
&mut batch_out,
)?;
} else {
per_row_batch_rows(
self.graph,
&batch.rows,
&self.spec,
self.params,
self.qctx,
&mut batch_out,
)?;
}
batch_out.stamp(
&BatchOutcome::Committed { id: tx_id.clone() },
self.status_name.as_deref(),
)?;
crate::exec::close_write_boundary(self.graph)?;
land_batch(self.graph, &batch_out.rows)?;
if let Some(sink) = self.qctx.batch_commit {
self.graph.commit_batch(sink)?;
}
Ok(())
})();
match attempt {
Ok(()) => Ok(batch_out),
Err(error) => {
self.graph.restore_scratch(snapshot);
match self.tx.on_error.outcome() {
relate_ir::RetryFallback::Fail => return Err(error),
relate_ir::RetryFallback::Break => self.breaking = true,
relate_ir::RetryFallback::Continue => {}
}
let mut failed = ChargedRows::new();
for row in &batch.rows {
failed.push(failed_batch_row(
self.graph,
row,
self.spec.query,
self.spec.scope,
self.params,
)?)?;
}
failed.stamp(
&BatchOutcome::Failed {
id: tx_id.clone(),
error: transaction_error_message(&error),
},
self.status_name.as_deref(),
)?;
land_batch(self.graph, &failed.rows)?;
Ok(failed)
}
}
}
fn pull_batch(&mut self) -> Result<Option<ChargedRows>> {
let Some(first) = self.input.next_row()? else {
return Ok(None);
};
let size = match self.batch_size {
Some(size) => size,
None => {
let size = resolve_batch_options(self.graph, &first, self.tx, self.params)?;
self.batch_size = Some(size);
size
}
};
let mut batch = ChargedRows::new();
batch.push(first)?;
while batch.rows.len() < size {
let Some(row) = self.input.next_row()? else {
break;
};
batch.push(row)?;
}
Ok(Some(batch))
}
}
struct ChargedRows {
rows: Vec<Row>,
charge: WorkspaceCharge,
}
impl ChargedRows {
fn new() -> Self {
Self {
rows: Vec::new(),
charge: WorkspaceCharge::empty(),
}
}
fn from_rows(rows: Vec<Row>) -> Result<Self> {
let mut batch = Self::new();
batch.extend(rows)?;
Ok(batch)
}
fn push(&mut self, row: Row) -> Result<()> {
self.rows.push(row);
self.measure()
}
fn extend(&mut self, rows: impl IntoIterator<Item = Row>) -> Result<()> {
self.rows.extend(rows);
self.measure()
}
fn stamp(&mut self, outcome: &BatchOutcome, name: Option<&str>) -> Result<()> {
outcome.stamp(&mut self.rows, name);
self.measure()
}
fn measure(&mut self) -> Result<()> {
self.charge
.resize_with(|| crate::workspace::retained_rows_of(&self.rows))
}
}
fn land_batch(graph: &ExecGraph<'_>, rows: &[Row]) -> Result<()> {
graph.check_expression_allocation(crate::workspace::retained_rows_of(rows))
}
pub fn batch_pass_admission(query: &Query) -> bool {
query.is_single_flat_part()
&& !stage_projects_rows(&query.final_stage().parts)
&& !relate_planner::query_any_clause(query, &mut |clause| {
matches!(clause, Clause::With { .. }) || relate_planner::clause_is_ddl_command(clause)
})
}
fn pass_batch_rows(
graph: &ExecGraph<'_>,
batch: &[Row],
spec: &SubquerySpec<'_>,
params: &BTreeMap<String, Value>,
qctx: QueryCtx<'_>,
out: &mut ChargedRows,
) -> Result<()> {
let seeds = ChargedRows::from_rows(
batch
.iter()
.map(|row| scope_seed(graph, spec.query, spec.scope, row))
.collect::<Result<Vec<_>>>()?,
)?;
let _ = execute_query_seeded(graph, spec.query, params, seeds.rows, qctx)?;
out.extend(batch.iter().cloned())
}
fn per_row_batch_rows(
graph: &ExecGraph<'_>,
batch: &[Row],
spec: &SubquerySpec<'_>,
params: &BTreeMap<String, Value>,
qctx: QueryCtx<'_>,
out: &mut ChargedRows,
) -> Result<()> {
for row in batch {
out.extend(row_product(
graph,
row,
spec.optional,
spec.query,
spec.scope,
params,
qctx,
)?)?;
}
Ok(())
}
fn resolve_batch_options(
graph: &ExecGraph<'_>,
first: &Row,
tx: &relate_ir::InTransactions,
params: &BTreeMap<String, Value>,
) -> Result<usize> {
const MSG: &str = "batch size must be a positive integer";
let batch_size = match tx.batch_size.as_ref() {
None => 1000,
Some(expr) => {
let size = eval(graph, first, expr, params)?
.as_int()
.ok_or_else(|| Error::ty(MSG))?;
usize::try_from(size)
.ok()
.filter(|n| *n > 0)
.ok_or_else(|| Error::argument_value_kind(ErrorKind::NumberOutOfRange, MSG))?
}
};
if let relate_ir::Concurrency::Value(expr) = &tx.concurrency {
eval(graph, first, expr, params)?
.as_int()
.ok_or_else(|| Error::ty("concurrency must be an integer"))?;
}
Ok(batch_size)
}
enum BatchOutcome {
Committed { id: String },
Failed { id: String, error: String },
NeverStarted,
}
impl BatchOutcome {
fn stamp(&self, rows: &mut [Row], status_name: Option<&str>) {
let Some(name) = status_name else {
return;
};
let status = self.status();
for row in rows {
row.insert(name.to_owned(), status.clone());
}
}
fn status(&self) -> Value {
let (started, committed, id, error) = match self {
Self::Committed { id } => (true, true, Some(id.as_str()), None),
Self::Failed { id, error } => (true, false, Some(id.as_str()), Some(error.as_str())),
Self::NeverStarted => (false, false, None, None),
};
Value::Map(
BTreeMap::from([
("started".into(), Value::Bool(started)),
("committed".into(), Value::Bool(committed)),
(
"transactionId".into(),
id.map(|s| Value::String(s.into())).unwrap_or(Value::Null),
),
(
"errorMessage".into(),
error
.map(|s| Value::String(s.into()))
.unwrap_or(Value::Null),
),
])
.into(),
)
}
}
fn failed_batch_row(
graph: &ExecGraph<'_>,
outer: &Row,
query: &Query,
scope: &relate_ir::CallScope,
params: &BTreeMap<String, Value>,
) -> Result<Row> {
let projected = super::final_export_items(query.final_stage())
.filter(|(_, items)| super::plain_per_row_projection(items));
let Some((clauses, items)) = projected else {
return Ok(null_pad_call_row(graph, outer.clone(), query, scope));
};
let mut seed = scope_seed(graph, query, scope, outer)?;
for name in star_scope_names(clauses) {
seed.entry(name).or_insert(Value::Null);
}
let mut row = outer.clone();
for (index, item) in items.iter().enumerate() {
let name = item.output_name(index);
let value = eval(graph, &seed, &item.expr, params).unwrap_or(Value::Null);
row.insert(name, value);
}
Ok(row)
}
pub(crate) fn transaction_error_message(error: &Error) -> String {
match error {
Error::UniquenessViolation { .. } => {
format!("A value already exists and violates a uniqueness constraint: {error}")
}
Error::Type(message) | Error::Semantic(message) => message.clone(),
Error::Arithmetic(failure) => failure.detail().to_string(),
other => other
.typed_detail_text()
.unwrap_or_else(|| other.to_string()),
}
}