Skip to main content

uqa_execution/query/scope/
row_locks.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Tuple-lock recheck state and scoped identity emission.
8
9use std::sync::Arc;
10use uqa_core::memory::{Produced, ProductionControl};
11
12use super::{
13    recheck_storage_names_match, CteScope, RecheckDoc, RecheckSourceRow, RowLockRecheckPins,
14};
15
16type RecheckStoragePin = (String, String, Arc<Vec<RecheckDoc>>);
17type SourceRowLocks = Arc<Produced<Vec<ResolvedRowLock>>>;
18type RecheckStoragePins = Arc<Produced<Vec<RecheckStoragePin>>>;
19
20#[derive(Clone, Copy, Default)]
21pub struct LockIdentityOptions {
22    pub emit: bool,
23    pub retain_after_lock: bool,
24}
25
26#[derive(Clone, Default)]
27pub struct RowLockScopeState {
28    source_row_locks: Option<SourceRowLocks>,
29    recheck: Option<Arc<RowLockRecheckPins>>,
30    outer_row: Option<Arc<crate::OwnedPhysicalRow>>,
31    storage_pins: Option<RecheckStoragePins>,
32}
33
34impl<S: Clone> CteScope<S> {
35    fn row_lock_state(&self) -> Option<&RowLockScopeState> {
36        self.row_lock.as_ref()
37    }
38
39    fn row_lock_state_mut(&mut self) -> &mut RowLockScopeState {
40        self.row_lock.get_or_insert_with(RowLockScopeState::default)
41    }
42
43    /// Enter one tuple-local recheck execution: base scans of pinned lock targets emit only the candidate's tuples and every nested `LockRows` is suppressed while lock identities keep flowing.
44    pub fn activate_row_lock_recheck(&mut self, pins: Arc<RowLockRecheckPins>) {
45        self.row_lock_state_mut().recheck = Some(pins);
46    }
47
48    pub fn row_lock_recheck_active(&self) -> bool {
49        self.row_lock_state()
50            .is_some_and(|state| state.recheck.is_some())
51    }
52
53    /// Preserve the complete correlated outer row for a tuple-local locking recheck. The rebuilt inner query must receive the same scope overlay as its original lateral execution or its correlation predicate would see NULL after a lock wait and incorrectly discard the refreshed tuple.
54    pub fn set_row_lock_outer_row(&mut self, row: crate::OwnedPhysicalRow) {
55        self.row_lock_state_mut().outer_row = Some(Arc::new(row));
56    }
57
58    pub fn row_lock_outer_row(&self) -> Option<&crate::OwnedPhysicalRow> {
59        self.row_lock_state()?.outer_row.as_deref()
60    }
61
62    pub(crate) fn outer_row_binding(&self) -> Option<Arc<crate::OwnedPhysicalRow>> {
63        self.row_lock_state()
64            .and_then(|state| state.outer_row.clone())
65    }
66
67    pub(super) fn restore_outer_row_binding(&mut self, row: Option<Arc<crate::OwnedPhysicalRow>>) {
68        if row.is_some() || self.row_lock.is_some() {
69            self.row_lock_state_mut().outer_row = row;
70        }
71    }
72
73    pub fn clear_row_lock_outer_row(&mut self) {
74        if let Some(state) = self.row_lock.as_mut() {
75            state.outer_row = None;
76        }
77    }
78
79    /// Pinned tuples one base scan must emit during an active recheck.
80    pub fn recheck_docs_for_scan(
81        &self,
82        qualifier: &str,
83        storage_name: &str,
84    ) -> Option<Arc<Vec<RecheckDoc>>> {
85        let state = self.row_lock_state()?;
86        if let Some(pins) = state.recheck.as_ref() {
87            if let Some(docs) = pins.docs_for_scan(qualifier, storage_name) {
88                return Some(docs);
89            }
90        }
91        state
92            .storage_pins
93            .iter()
94            .flat_map(|pins| pins.iter())
95            .find(|(pinned_storage, pinned_scan, _)| {
96                pinned_scan == qualifier
97                    && recheck_storage_names_match(pinned_storage, storage_name)
98            })
99            .map(|(_, _, docs)| Arc::clone(docs))
100    }
101
102    /// Exact copy-row mark for one top-level FROM leaf in the active tuple recheck. Paths use 0/1 for left/right join descent and are scoped to the original `LockRows` source, so nested query aliases cannot collide.
103    pub fn recheck_source_row(&self, path: &[u8]) -> Option<RecheckSourceRow> {
104        self.row_lock_state()?
105            .recheck
106            .as_ref()
107            .and_then(|pins| pins.source_row(path))
108    }
109
110    /// Enter the build of one identity-source lock target's subtree so every base scan of its storage inside the derived table or view is pinned. Pins already active from an enclosing target stay active: the target's base scans may sit below further derived-table boundaries.
111    pub fn enter_recheck_storage_pins(&mut self, qualifier: &str) -> RecheckStoragePinScope<'_, S> {
112        let added = self
113            .row_lock_state()
114            .and_then(|state| state.recheck.as_ref())
115            .map(|pins| pins.storage_pins_for_identity_source(qualifier))
116            .unwrap_or_default();
117        let previous = if added.is_empty() {
118            PreviousBinding::Unchanged
119        } else {
120            let state = self.row_lock_state_mut();
121            let previous = state.storage_pins.clone();
122            let entries: Vec<_> = state
123                .storage_pins
124                .iter()
125                .flat_map(|pins| pins.iter())
126                .cloned()
127                .chain(added)
128                .collect();
129            state.storage_pins = Some(
130                ProductionControl::uncontrolled()
131                    .finish(entries, None)
132                    .expect("ordinary recheck pins")
133                    .into_shared(&ProductionControl::uncontrolled())
134                    .expect("ordinary recheck pin owner"),
135            );
136            PreviousBinding::Restore(previous)
137        };
138        RecheckStoragePinScope {
139            ctes: self,
140            previous,
141        }
142    }
143
144    pub fn enter_lock_identity_emission(
145        &mut self,
146        enabled: bool,
147    ) -> LockIdentityEmissionScope<'_, S> {
148        self.enter_lock_identity_options(LockIdentityOptions {
149            emit: enabled,
150            retain_after_lock: false,
151        })
152    }
153
154    pub(crate) fn enter_lock_identity_options(
155        &mut self,
156        options: LockIdentityOptions,
157    ) -> LockIdentityEmissionScope<'_, S> {
158        let previous = std::mem::replace(&mut self.lock_identities, options);
159        LockIdentityEmissionScope {
160            ctes: self,
161            previous,
162        }
163    }
164
165    pub fn enter_source_row_locks(
166        &mut self,
167        locks: Vec<ResolvedRowLock>,
168    ) -> SourceRowLockScope<'_, S> {
169        let control = ProductionControl::uncontrolled();
170        self.enter_source_row_locks_with_control(
171            control
172                .finish(locks, None)
173                .expect("ordinary source row locks"),
174            &control,
175        )
176        .expect("ordinary source row lock owner")
177    }
178
179    /// Construct the complete shared owner before publishing a new binding; failure leaves the enclosing scope intact.
180    pub fn enter_source_row_locks_with_control(
181        &mut self,
182        locks: Produced<Vec<ResolvedRowLock>>,
183        control: &ProductionControl<'_>,
184    ) -> Result<SourceRowLockScope<'_, S>, uqa_sql::SQLError> {
185        control.check()?;
186        let locks = if locks.is_empty() {
187            None
188        } else {
189            Some(locks.into_shared(control)?)
190        };
191        let existing_is_empty = self
192            .row_lock_state()
193            .is_none_or(|state| state.source_row_locks.is_none());
194        let previous = if locks.is_none() && existing_is_empty {
195            PreviousBinding::Unchanged
196        } else {
197            PreviousBinding::Restore(std::mem::replace(
198                &mut self.row_lock_state_mut().source_row_locks,
199                locks,
200            ))
201        };
202        Ok(SourceRowLockScope {
203            ctes: self,
204            previous,
205        })
206    }
207
208    pub fn source_row_lock_for_view(
209        &self,
210        qualifier: &str,
211        storage_name: &str,
212    ) -> Option<SelectedRowLock> {
213        let locks = self.row_lock_state()?.source_row_locks.as_ref()?;
214        let index = locks.iter().position(|target| {
215            target.identity_source
216                && target.qualifier == qualifier
217                && target.storage_name == storage_name
218        })?;
219        Some(SelectedRowLock {
220            locks: Arc::clone(locks),
221            index,
222        })
223    }
224}
225
226/// An allocation-free selection keeps the immutable target's original lease alive through nested view construction.
227pub struct SelectedRowLock {
228    locks: SourceRowLocks,
229    index: usize,
230}
231
232impl std::ops::Deref for SelectedRowLock {
233    type Target = ResolvedRowLock;
234    fn deref(&self) -> &Self::Target {
235        &self.locks[self.index]
236    }
237}
238
239pub struct LockIdentityEmissionScope<'a, S: Clone> {
240    ctes: &'a mut CteScope<S>,
241    previous: LockIdentityOptions,
242}
243
244enum PreviousBinding<T> {
245    Unchanged,
246    Restore(Option<T>),
247}
248
249pub struct SourceRowLockScope<'a, S: Clone> {
250    ctes: &'a mut CteScope<S>,
251    previous: PreviousBinding<SourceRowLocks>,
252}
253
254pub struct RecheckStoragePinScope<'a, S: Clone> {
255    ctes: &'a mut CteScope<S>,
256    previous: PreviousBinding<RecheckStoragePins>,
257}
258
259impl<S: Clone> std::ops::Deref for RecheckStoragePinScope<'_, S> {
260    type Target = CteScope<S>;
261
262    fn deref(&self) -> &Self::Target {
263        self.ctes
264    }
265}
266
267impl<S: Clone> std::ops::DerefMut for RecheckStoragePinScope<'_, S> {
268    fn deref_mut(&mut self) -> &mut Self::Target {
269        self.ctes
270    }
271}
272
273impl<S: Clone> Drop for RecheckStoragePinScope<'_, S> {
274    fn drop(&mut self) {
275        if let PreviousBinding::Restore(previous) = &mut self.previous {
276            self.ctes.row_lock_state_mut().storage_pins = previous.take();
277        }
278    }
279}
280
281impl<S: Clone> std::ops::Deref for SourceRowLockScope<'_, S> {
282    type Target = CteScope<S>;
283
284    fn deref(&self) -> &Self::Target {
285        self.ctes
286    }
287}
288
289impl<S: Clone> std::ops::DerefMut for SourceRowLockScope<'_, S> {
290    fn deref_mut(&mut self) -> &mut Self::Target {
291        self.ctes
292    }
293}
294
295impl<S: Clone> Drop for SourceRowLockScope<'_, S> {
296    fn drop(&mut self) {
297        if let PreviousBinding::Restore(previous) = &mut self.previous {
298            self.ctes.row_lock_state_mut().source_row_locks = previous.take();
299        }
300    }
301}
302
303impl<S: Clone> std::ops::Deref for LockIdentityEmissionScope<'_, S> {
304    type Target = CteScope<S>;
305
306    fn deref(&self) -> &Self::Target {
307        self.ctes
308    }
309}
310
311impl<S: Clone> std::ops::DerefMut for LockIdentityEmissionScope<'_, S> {
312    fn deref_mut(&mut self) -> &mut Self::Target {
313        self.ctes
314    }
315}
316
317impl<S: Clone> Drop for LockIdentityEmissionScope<'_, S> {
318    fn drop(&mut self) {
319        self.ctes.lock_identities = self.previous;
320    }
321}
322
323pub use uqa_sql::plan::locking::ResolvedRowLock;
324
325#[cfg(test)]
326mod tests;