Skip to main content

uqa_execution/query/scope/
statement_commands.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! The commands of one statement and what they leave for the statement's end.
8
9use crate::mutation::candidate::PhysicalDocumentIdentity;
10use crate::mutation::triggers::queue::AfterTriggerQueue;
11use std::collections::BTreeSet;
12use std::sync::atomic::{AtomicBool, Ordering};
13use uqa_core::memory::{MemoryReservation, Produced, ProductionControl, ProductionVec};
14use uqa_sql::{plan::RetainedCtePlan, semantics::cte_strategy::ScheduledCte, SQLError};
15
16type PostponedCtes = Produced<Vec<(RetainedCtePlan, bool)>>;
17
18/// The commands of one statement and what they leave for its end, shared by every scope of the statement. `PostgreSQL` runs a statement under one command id and one AFTER trigger query level: the AFTER events of the statement's commands, its data-modifying WITH items and the referential actions those take among them, wait in one queue until the statement has finished (`AfterTriggerEndQuery`), and a row that one of its commands wrote is `TM_SelfModified` to the others.
19#[derive(Default)]
20pub struct StatementCommands {
21    /// Whether the statement's WITH modifies data, which makes its commands leave their AFTER events for the statement's end.
22    modifies_with: AtomicBool,
23    /// The WITH items that run once the primary query has finished, in the order they run.
24    postponed: parking_lot::Mutex<Option<PostponedCtes>>,
25    /// The rows the statement's commands inserted, updated or deleted, which a statement whose WITH modifies data keeps.
26    written: parking_lot::Mutex<BTreeSet<PhysicalDocumentIdentity>>,
27    /// The rows that statements the statement started wrote: statements of its triggers and of the functions it calls, and their referential actions, which run under later command ids.
28    triggered: parking_lot::Mutex<BTreeSet<PhysicalDocumentIdentity>>,
29    after_triggers: AfterTriggerQueue,
30    _memory: Option<MemoryReservation>,
31}
32
33impl StatementCommands {
34    /// Admit the shared command owner before allocation. Its queues retain their own independently admitted payloads.
35    pub(crate) fn with_control(
36        control: &ProductionControl<'_>,
37    ) -> Result<std::sync::Arc<Self>, SQLError> {
38        let memory = control.reserve(size_of::<Self>())?;
39        Ok(std::sync::Arc::new(Self {
40            _memory: memory,
41            ..Self::default()
42        }))
43    }
44
45    /// Prepare the complete postponed schedule before changing this statement's command state. A failure leaves an existing schedule and its owners intact.
46    pub(crate) fn begin_data_modifying_with<'a>(
47        &self,
48        postponed: impl IntoIterator<Item = ScheduledCte<'a>>,
49        control: &ProductionControl<'_>,
50    ) -> Result<(), SQLError> {
51        let mut schedule = ProductionVec::new(*control);
52        for entry in postponed {
53            schedule.reserve(1)?;
54            let plan = RetainedCtePlan::capture(entry.plan, control)?;
55            schedule.push_produced(
56                control.finish((plan, entry.deferred), control.empty_reservation())?,
57            )?;
58        }
59        let schedule = schedule.finish()?;
60        *self.postponed.lock() = Some(schedule);
61        self.modifies_with.store(true, Ordering::Relaxed);
62        Ok(())
63    }
64
65    pub fn modifies_with(&self) -> bool {
66        self.modifies_with.load(Ordering::Relaxed)
67    }
68
69    pub fn after_triggers(&self) -> &AfterTriggerQueue {
70        &self.after_triggers
71    }
72
73    /// Move the once-only schedule together with its vector and immutable plan owners. Readers may share a selected plan without extending unrelated schedule storage.
74    pub(crate) fn take_scheduled_postponed(&self) -> Option<PostponedCtes> {
75        self.postponed.lock().take()
76    }
77
78    pub fn note_written(&self, rows: impl IntoIterator<Item = PhysicalDocumentIdentity>) {
79        self.written.lock().extend(rows);
80    }
81
82    /// Whether one of the statement's commands wrote `row`, which the statement's later commands find in their snapshot as a row the statement already modified.
83    pub fn wrote(&self, row: &PhysicalDocumentIdentity) -> bool {
84        self.written.lock().contains(row)
85    }
86
87    pub fn note_triggered(&self, rows: impl IntoIterator<Item = PhysicalDocumentIdentity>) {
88        self.triggered.lock().extend(rows);
89    }
90
91    /// Whether a statement that this statement started wrote `row`, which `PostgreSQL` finds modified by a later command than the statement's own (`TM_SelfModified` with another `cmax`).
92    pub fn triggered_write(&self, row: &PhysicalDocumentIdentity) -> bool {
93        self.triggered.lock().contains(row)
94    }
95}
96
97#[cfg(test)]
98mod tests;