Skip to main content

uqa_execution/batch/
row_lock_origins.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Row-lock lineage carried on composite physical rows.
8
9use std::sync::Arc;
10
11use super::{PhysicalRow, RowLockName};
12
13/// Base-table identity carried on a composite physical row for `FOR UPDATE`.
14///
15/// Origins ride beside value fragments. Joins concatenate them; projections and schema remaps keep them. They are not SQL-visible columns and must not be rebuilt from named maps.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct RowLockOrigin {
18    /// Visible qualifier of the row source that currently owns the origin. Views, CTEs, and derived tables rebind it to their own alias.
19    pub qualifier: RowLockName,
20    /// Qualifier of the base scan that produced the origin. Rebinding at a derived-table boundary leaves it untouched, so a tuple recheck can pin each base scan inside a view or subquery to its own tuples.
21    pub scan_qualifier: RowLockName,
22    pub storage_name: RowLockName,
23    pub doc_id: uqa_core::DocId,
24}
25
26impl RowLockOrigin {
27    #[must_use]
28    pub fn new(
29        qualifier: impl Into<String>,
30        storage_name: impl Into<String>,
31        doc_id: uqa_core::DocId,
32    ) -> Self {
33        Self::from_shared(
34            Arc::<str>::from(qualifier.into()),
35            Arc::<str>::from(storage_name.into()),
36            doc_id,
37        )
38    }
39
40    /// Build an origin from source names shared by every row in one scan.
41    #[must_use]
42    pub fn from_shared(
43        qualifier: impl Into<RowLockName>,
44        storage_name: impl Into<RowLockName>,
45        doc_id: uqa_core::DocId,
46    ) -> Self {
47        let qualifier = qualifier.into();
48        let storage_name = storage_name.into();
49        Self {
50            scan_qualifier: qualifier.clone(),
51            qualifier,
52            storage_name,
53            doc_id,
54        }
55    }
56}
57
58pub(super) fn concat_lock_origins(
59    left: Option<&Arc<Vec<RowLockOrigin>>>,
60    right: Option<&Arc<Vec<RowLockOrigin>>>,
61) -> Option<Arc<Vec<RowLockOrigin>>> {
62    match (left, right) {
63        (None, None) => None,
64        (Some(origins), None) | (None, Some(origins)) => Some(Arc::clone(origins)),
65        (Some(left), Some(right)) => {
66            let mut origins = Vec::with_capacity(left.len() + right.len());
67            origins.extend(left.iter().cloned());
68            origins.extend(right.iter().cloned());
69            Some(Arc::new(origins))
70        }
71    }
72}
73
74impl PhysicalRow {
75    #[must_use]
76    pub fn with_lock_origin(mut self, origin: RowLockOrigin) -> Self {
77        self.lock_origins = match self.lock_origins.take() {
78            None => Some(Arc::new(vec![origin])),
79            Some(existing) => {
80                let mut origins = Vec::with_capacity(existing.len() + 1);
81                origins.extend(existing.iter().cloned());
82                origins.push(origin);
83                Some(Arc::new(origins))
84            }
85        };
86        self
87    }
88
89    #[must_use]
90    pub fn with_lock_origins(mut self, origins: impl IntoIterator<Item = RowLockOrigin>) -> Self {
91        let origins = origins.into_iter().collect::<Vec<_>>();
92        if origins.is_empty() {
93            return self;
94        }
95        self.lock_origins = match self.lock_origins.take() {
96            None => Some(Arc::new(origins)),
97            Some(existing) => {
98                let mut combined = Vec::with_capacity(existing.len() + origins.len());
99                combined.extend(existing.iter().cloned());
100                combined.extend(origins);
101                Some(Arc::new(combined))
102            }
103        };
104        self
105    }
106
107    #[must_use]
108    pub fn lock_origins(&self) -> &[RowLockOrigin] {
109        self.lock_origins
110            .as_deref()
111            .map_or(&[], std::vec::Vec::as_slice)
112    }
113
114    /// Drop row-lock lineage at an execution boundary that cannot expose a lockable base-row identity, such as a set operation.
115    #[must_use]
116    pub fn without_lock_origins(mut self) -> Self {
117        self.lock_origins = None;
118        self
119    }
120
121    /// Remove all row-lock identities without reallocating the row payload.
122    pub fn discard_lock_origins_mut(&mut self) {
123        self.lock_origins = None;
124    }
125
126    /// Point every lock origin at the visible source qualifier. Views, CTEs, and subqueries keep inner storage names so `FOR UPDATE OF` that alias locks only those origins after a join.
127    #[must_use]
128    pub fn rebind_lock_origin_qualifiers(mut self, qualifier: impl Into<RowLockName>) -> Self {
129        self.rebind_lock_origin_qualifiers_mut(qualifier);
130        self
131    }
132
133    pub fn rebind_lock_origin_qualifiers_mut(&mut self, qualifier: impl Into<RowLockName>) {
134        let qualifier = qualifier.into();
135        let Some(origins) = self.lock_origins.as_mut() else {
136            return;
137        };
138        for origin in Arc::make_mut(origins) {
139            origin.qualifier = qualifier.clone();
140        }
141    }
142}