use crate::mutation::candidate::PhysicalDocumentIdentity;
use crate::mutation::triggers::queue::AfterTriggerQueue;
use std::collections::BTreeSet;
use std::sync::atomic::{AtomicBool, Ordering};
use uqa_core::memory::{MemoryReservation, Produced, ProductionControl, ProductionVec};
use uqa_sql::{plan::RetainedCtePlan, semantics::cte_strategy::ScheduledCte, SQLError};
type PostponedCtes = Produced<Vec<(RetainedCtePlan, bool)>>;
#[derive(Default)]
pub struct StatementCommands {
modifies_with: AtomicBool,
postponed: parking_lot::Mutex<Option<PostponedCtes>>,
written: parking_lot::Mutex<BTreeSet<PhysicalDocumentIdentity>>,
triggered: parking_lot::Mutex<BTreeSet<PhysicalDocumentIdentity>>,
after_triggers: AfterTriggerQueue,
_memory: Option<MemoryReservation>,
}
impl StatementCommands {
pub(crate) fn with_control(
control: &ProductionControl<'_>,
) -> Result<std::sync::Arc<Self>, SQLError> {
let memory = control.reserve(size_of::<Self>())?;
Ok(std::sync::Arc::new(Self {
_memory: memory,
..Self::default()
}))
}
pub(crate) fn begin_data_modifying_with<'a>(
&self,
postponed: impl IntoIterator<Item = ScheduledCte<'a>>,
control: &ProductionControl<'_>,
) -> Result<(), SQLError> {
let mut schedule = ProductionVec::new(*control);
for entry in postponed {
schedule.reserve(1)?;
let plan = RetainedCtePlan::capture(entry.plan, control)?;
schedule.push_produced(
control.finish((plan, entry.deferred), control.empty_reservation())?,
)?;
}
let schedule = schedule.finish()?;
*self.postponed.lock() = Some(schedule);
self.modifies_with.store(true, Ordering::Relaxed);
Ok(())
}
pub fn modifies_with(&self) -> bool {
self.modifies_with.load(Ordering::Relaxed)
}
pub fn after_triggers(&self) -> &AfterTriggerQueue {
&self.after_triggers
}
pub(crate) fn take_scheduled_postponed(&self) -> Option<PostponedCtes> {
self.postponed.lock().take()
}
pub fn note_written(&self, rows: impl IntoIterator<Item = PhysicalDocumentIdentity>) {
self.written.lock().extend(rows);
}
pub fn wrote(&self, row: &PhysicalDocumentIdentity) -> bool {
self.written.lock().contains(row)
}
pub fn note_triggered(&self, rows: impl IntoIterator<Item = PhysicalDocumentIdentity>) {
self.triggered.lock().extend(rows);
}
pub fn triggered_write(&self, row: &PhysicalDocumentIdentity) -> bool {
self.triggered.lock().contains(row)
}
}
#[cfg(test)]
mod tests;