use std::collections::BTreeMap;
use relate_core::{Error, ErrorKind, Result, Value};
use relate_ir::Query;
use super::{call_subquery_row, empty_body_row, null_pad_call_row, scope_seed, SubquerySpec};
use crate::ctx::QueryCtx;
use crate::eval::{eval, is_agg_expr};
use crate::exec::constraint_validation::validate_constraints;
use crate::exec::scope::{has_star_item, star_scope_names, terminal_return_items};
use crate::overlay::ExecGraph;
use crate::row::Row;
pub(crate) fn exec_call_in_transactions(
graph: &ExecGraph<'_>,
rows: Vec<Row>,
spec: SubquerySpec<'_>,
tx: &relate_ir::InTransactions,
params: &BTreeMap<String, Value>,
qctx: QueryCtx<'_>,
) -> Result<Vec<Row>> {
let SubquerySpec {
query,
optional,
scope,
in_transactions: _,
} = spec;
if rows.is_empty() {
return Ok(Vec::new());
}
let batch_size = resolve_batch_options(graph, &rows[0], tx, params)?;
let status_name = tx.report_status.as_ref().map(|name| name.to_string());
let mut out = Vec::new();
let mut batches = rows.chunks(batch_size).enumerate();
for (batch_index, batch) in batches.by_ref() {
let snapshot = graph.scratch_snapshot();
let tx_id = format!("relate-inner-{}", batch_index + 1);
let mut batch_out = Vec::new();
let attempt = (|| -> Result<()> {
for row in batch {
let mut produced = call_subquery_row(graph, row, query, scope, params, qctx)?;
if produced.is_empty() {
produced.extend(empty_body_row(row.clone(), optional, query, scope));
}
batch_out.extend(produced);
}
BatchOutcome::Committed { id: tx_id.clone() }
.stamp(&mut batch_out, status_name.as_deref());
super::super::property_defaults::apply_property_defaults(graph)?;
validate_constraints(graph)?;
if let Some(sink) = qctx.batch_commit {
graph.commit_batch(sink)?;
}
Ok(())
})();
match attempt {
Ok(()) => out.extend(batch_out),
Err(error) => {
graph.restore_scratch(snapshot);
let mode = tx.on_error.outcome();
if mode == relate_ir::RetryFallback::Fail {
return Err(error);
}
let mut failed_rows = Vec::new();
for row in batch {
failed_rows.push(failed_batch_row(graph, row, query, scope, params)?);
}
BatchOutcome::Failed {
id: tx_id.clone(),
error: transaction_error_message(&error),
}
.stamp(&mut failed_rows, status_name.as_deref());
out.extend(failed_rows);
if mode == relate_ir::RetryFallback::Break {
let mut never_started_rows = Vec::new();
for (_, batch) in batches.by_ref() {
for row in batch {
never_started_rows.push(null_pad_call_row(row.clone(), query, scope));
}
}
BatchOutcome::NeverStarted
.stamp(&mut never_started_rows, status_name.as_deref());
out.extend(never_started_rows);
break;
}
}
}
}
Ok(out)
}
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 = query.final_stage().parts.first().and_then(|part| {
let (clauses, items) = terminal_return_items(part)?;
(!has_star_item(items) && !items.iter().any(|item| is_agg_expr(&item.expr)))
.then_some((clauses, items))
});
let Some((clauses, items)) = projected else {
return Ok(null_pad_call_row(outer.clone(), query, scope));
};
let mut seed = scope_seed(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()),
}
}