use super::{
sources::query_source_memory, MutableQueryPlan, MutableSourcePlan, OwnedScalarExpr,
QueryChildSlot, QueryPlan, QueryScalarSlot, RelationalPlan,
};
use crate::{SQLError, ScalarExpr};
use uqa_core::{memory::ProductionControl, Value};
impl MutableQueryPlan {
pub fn map_scalar_with_parent(
mut self,
slot: QueryScalarSlot,
control: &ProductionControl<'_>,
map: impl FnOnce(&QueryPlan, OwnedScalarExpr) -> Result<OwnedScalarExpr, SQLError>,
) -> Result<Self, SQLError> {
self.assert_owner(control);
control.check()?;
let Some(expression) = slot.expression_mut(&mut self.query) else {
return Ok(self);
};
let memory = self
.memory
.as_mut()
.and_then(|memory| slot.memory_mut(memory).take());
let input = OwnedScalarExpr::from_rewrite_parts(
std::mem::replace(expression, ScalarExpr::Literal(Value::Null)),
memory,
);
let output = input.rewrite(control, |input| map(&self.query, input))?;
let (expression, memory) = output.into_rewrite_parts();
*slot
.expression_mut(&mut self.query)
.expect("original scalar slot") = expression;
if let Some(owner) = &mut self.memory {
*slot.memory_mut(owner) = memory;
}
Ok(self)
}
pub fn map_query_child_with_parent(
mut self,
slot: QueryChildSlot,
control: &ProductionControl<'_>,
map: impl FnOnce(&QueryPlan, Self) -> Result<Self, SQLError>,
) -> Result<Self, SQLError> {
self.assert_owner(control);
control.check()?;
let input = Self {
query: std::mem::replace(
slot.query_mut(&mut self.query),
super::queries::empty_query(),
),
memory: self
.memory
.as_mut()
.and_then(|memory| slot.memory_mut(memory).take()),
};
let output = map(&self.query, input)?;
output.assert_owner(control);
control.check()?;
*slot.query_mut(&mut self.query) = output.query;
if let Some(memory) = &mut self.memory {
*slot.memory_mut(memory) = output.memory;
}
Ok(self)
}
pub fn map_source_with_parent(
mut self,
control: &ProductionControl<'_>,
map: impl FnOnce(&QueryPlan, MutableSourcePlan) -> Result<MutableSourcePlan, SQLError>,
) -> Result<Self, SQLError> {
self.assert_owner(control);
control.check()?;
let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
return Err(SQLError::Internal(
"source rewrite requires a query block".into(),
));
};
let Some(source) = block.from.take() else {
return Ok(self);
};
let memory = self
.memory
.as_mut()
.and_then(|memory| query_source_memory(memory).take());
let output = map(&self.query, MutableSourcePlan { source, memory })?;
output.assert_owner(control);
control.check()?;
let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
unreachable!("read-only parent cannot change topology");
};
block.from = Some(output.source);
if let Some(memory) = &mut self.memory {
*query_source_memory(memory) = output.memory;
}
Ok(self)
}
}