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;
10
11use super::{
12    recheck_storage_names_match, CteScope, RecheckDoc, RecheckSourceRow, RowLockRecheckPins,
13};
14
15type RecheckStoragePin = (String, String, Arc<Vec<RecheckDoc>>);
16
17#[derive(Clone, Copy, Default)]
18pub struct LockIdentityOptions {
19    pub emit: bool,
20    pub retain_after_lock: bool,
21}
22
23#[derive(Clone, Default)]
24pub struct RowLockScopeState {
25    source_row_locks: Vec<ResolvedRowLock>,
26    recheck: Option<Arc<RowLockRecheckPins>>,
27    outer_row: Option<Arc<crate::OwnedPhysicalRow>>,
28    storage_pins: Vec<RecheckStoragePin>,
29}
30
31impl<S: Clone> CteScope<S> {
32    fn row_lock_state(&self) -> Option<&RowLockScopeState> {
33        self.row_lock.as_deref()
34    }
35
36    fn row_lock_state_mut(&mut self) -> &mut RowLockScopeState {
37        self.row_lock
38            .get_or_insert_with(|| Box::new(RowLockScopeState::default()))
39    }
40
41    /// 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.
42    pub fn activate_row_lock_recheck(&mut self, pins: Arc<RowLockRecheckPins>) {
43        self.row_lock_state_mut().recheck = Some(pins);
44    }
45
46    pub fn row_lock_recheck_active(&self) -> bool {
47        self.row_lock_state()
48            .is_some_and(|state| state.recheck.is_some())
49    }
50
51    /// 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.
52    pub fn set_row_lock_outer_row(&mut self, row: crate::OwnedPhysicalRow) {
53        self.row_lock_state_mut().outer_row = Some(Arc::new(row));
54    }
55
56    pub fn row_lock_outer_row(&self) -> Option<&crate::OwnedPhysicalRow> {
57        self.row_lock_state()?.outer_row.as_deref()
58    }
59
60    pub fn clear_row_lock_outer_row(&mut self) {
61        if let Some(state) = self.row_lock.as_mut() {
62            state.outer_row = None;
63        }
64    }
65
66    /// Pinned tuples one base scan must emit during an active recheck.
67    pub fn recheck_docs_for_scan(
68        &self,
69        qualifier: &str,
70        storage_name: &str,
71    ) -> Option<Arc<Vec<RecheckDoc>>> {
72        let state = self.row_lock_state()?;
73        if let Some(pins) = state.recheck.as_ref() {
74            if let Some(docs) = pins.docs_for_scan(qualifier, storage_name) {
75                return Some(docs);
76            }
77        }
78        state
79            .storage_pins
80            .iter()
81            .find(|(pinned_storage, pinned_scan, _)| {
82                pinned_scan == qualifier
83                    && recheck_storage_names_match(pinned_storage, storage_name)
84            })
85            .map(|(_, _, docs)| Arc::clone(docs))
86    }
87
88    /// 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.
89    pub fn recheck_source_row(&self, path: &[u8]) -> Option<RecheckSourceRow> {
90        self.row_lock_state()?
91            .recheck
92            .as_ref()
93            .and_then(|pins| pins.source_row(path))
94    }
95
96    /// 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.
97    pub fn enter_recheck_storage_pins(&mut self, qualifier: &str) -> RecheckStoragePinScope<'_, S> {
98        let added = self
99            .row_lock_state()
100            .and_then(|state| state.recheck.as_ref())
101            .map(|pins| pins.storage_pins_for_identity_source(qualifier))
102            .unwrap_or_default();
103        let previous = if added.is_empty() {
104            None
105        } else {
106            let state = self.row_lock_state_mut();
107            let previous = state.storage_pins.clone();
108            state.storage_pins.extend(added);
109            Some(previous)
110        };
111        RecheckStoragePinScope {
112            ctes: self,
113            previous,
114        }
115    }
116
117    pub fn enter_lock_identity_emission(
118        &mut self,
119        enabled: bool,
120    ) -> LockIdentityEmissionScope<'_, S> {
121        let previous = std::mem::replace(
122            &mut self.lock_identities,
123            LockIdentityOptions {
124                emit: enabled,
125                retain_after_lock: false,
126            },
127        );
128        LockIdentityEmissionScope {
129            ctes: self,
130            previous,
131        }
132    }
133
134    pub fn enter_source_row_locks(
135        &mut self,
136        locks: Vec<ResolvedRowLock>,
137    ) -> SourceRowLockScope<'_, S> {
138        let existing_is_empty = self
139            .row_lock_state()
140            .is_none_or(|state| state.source_row_locks.is_empty());
141        let previous = if locks.is_empty() && existing_is_empty {
142            None
143        } else {
144            Some(std::mem::replace(
145                &mut self.row_lock_state_mut().source_row_locks,
146                locks,
147            ))
148        };
149        SourceRowLockScope {
150            ctes: self,
151            previous,
152        }
153    }
154
155    pub fn source_row_lock_for_view(
156        &self,
157        qualifier: &str,
158        storage_name: &str,
159    ) -> Option<ResolvedRowLock> {
160        self.row_lock_state()?
161            .source_row_locks
162            .iter()
163            .find(|target| {
164                target.identity_source
165                    && target.qualifier == qualifier
166                    && target.storage_name == storage_name
167            })
168            .cloned()
169    }
170}
171
172pub struct LockIdentityEmissionScope<'a, S: Clone> {
173    ctes: &'a mut CteScope<S>,
174    previous: LockIdentityOptions,
175}
176
177pub struct SourceRowLockScope<'a, S: Clone> {
178    ctes: &'a mut CteScope<S>,
179    previous: Option<Vec<ResolvedRowLock>>,
180}
181
182pub struct RecheckStoragePinScope<'a, S: Clone> {
183    ctes: &'a mut CteScope<S>,
184    previous: Option<Vec<RecheckStoragePin>>,
185}
186
187impl<S: Clone> std::ops::Deref for RecheckStoragePinScope<'_, S> {
188    type Target = CteScope<S>;
189
190    fn deref(&self) -> &Self::Target {
191        self.ctes
192    }
193}
194
195impl<S: Clone> std::ops::DerefMut for RecheckStoragePinScope<'_, S> {
196    fn deref_mut(&mut self) -> &mut Self::Target {
197        self.ctes
198    }
199}
200
201impl<S: Clone> Drop for RecheckStoragePinScope<'_, S> {
202    fn drop(&mut self) {
203        if let Some(previous) = self.previous.take() {
204            self.ctes.row_lock_state_mut().storage_pins = previous;
205        }
206    }
207}
208
209impl<S: Clone> std::ops::Deref for SourceRowLockScope<'_, S> {
210    type Target = CteScope<S>;
211
212    fn deref(&self) -> &Self::Target {
213        self.ctes
214    }
215}
216
217impl<S: Clone> std::ops::DerefMut for SourceRowLockScope<'_, S> {
218    fn deref_mut(&mut self) -> &mut Self::Target {
219        self.ctes
220    }
221}
222
223impl<S: Clone> Drop for SourceRowLockScope<'_, S> {
224    fn drop(&mut self) {
225        if let Some(previous) = self.previous.take() {
226            self.ctes.row_lock_state_mut().source_row_locks = previous;
227        }
228    }
229}
230
231impl<S: Clone> std::ops::Deref for LockIdentityEmissionScope<'_, S> {
232    type Target = CteScope<S>;
233
234    fn deref(&self) -> &Self::Target {
235        self.ctes
236    }
237}
238
239impl<S: Clone> std::ops::DerefMut for LockIdentityEmissionScope<'_, S> {
240    fn deref_mut(&mut self) -> &mut Self::Target {
241        self.ctes
242    }
243}
244
245impl<S: Clone> Drop for LockIdentityEmissionScope<'_, S> {
246    fn drop(&mut self) {
247        self.ctes.lock_identities = self.previous;
248    }
249}
250
251pub use uqa_sql::plan::locking::ResolvedRowLock;