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