Skip to main content

uqa_execution/mutation/
locking.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Canonical DML row-lock acquisition and committed-chain following.
8
9use std::collections::BTreeSet;
10use std::sync::Arc;
11
12use uqa_core::DocId;
13use uqa_sql::SQLError;
14
15use super::candidate::{MutationLockTarget, PhysicalDocumentIdentity, PhysicalMutationLockTarget};
16use crate::row_locks::session::RowLockSession;
17
18pub struct MutationLockCleanup {
19    manager: Arc<crate::row_locks::RowLockManager>,
20    acquisitions: Vec<crate::row_locks::RowLockAcquisition>,
21}
22
23impl MutationLockCleanup {
24    pub fn new(session: &dyn RowLockSession) -> Self {
25        Self {
26            manager: session.lock_manager(),
27            acquisitions: Vec::new(),
28        }
29    }
30
31    pub fn acquire(
32        &mut self,
33        session: &dyn RowLockSession,
34        table: &str,
35        display_name: &str,
36        doc_id: DocId,
37        strength: uqa_sql::ast::LockStrength,
38    ) -> Result<bool, SQLError> {
39        match session.lock_row(
40            table,
41            doc_id,
42            strength,
43            uqa_sql::ast::LockWait::Block,
44            display_name,
45        )? {
46            crate::row_locks::LockAcquire::Granted {
47                acquisition,
48                waited,
49                ..
50            } => {
51                self.acquisitions.extend(acquisition);
52                Ok(waited)
53            }
54            crate::row_locks::LockAcquire::Skipped => Err(SQLError::Internal(
55                "blocking mutation lock unexpectedly skipped a row".into(),
56            )),
57        }
58    }
59
60    pub fn retain(&mut self, acquisitions: Vec<crate::row_locks::RowLockAcquisition>) {
61        self.acquisitions.extend(acquisitions);
62    }
63
64    pub fn rollback(&self, acquisitions: Vec<crate::row_locks::RowLockAcquisition>) {
65        for acquisition in acquisitions.into_iter().rev() {
66            self.manager.rollback_acquisition(acquisition);
67        }
68    }
69}
70
71impl Drop for MutationLockCleanup {
72    fn drop(&mut self) {
73        for acquisition in self.acquisitions.drain(..).rev() {
74            self.manager.rollback_acquisition(acquisition);
75        }
76    }
77}
78
79pub fn concurrent_update_serialization_failure() -> SQLError {
80    SQLError::Routine {
81        sqlstate: "40001".into(),
82        message: "could not serialize access due to concurrent update".into(),
83    }
84}
85
86pub fn lock_mutation_row(
87    session: &dyn RowLockSession,
88    table: &str,
89    display_name: &str,
90    doc_id: DocId,
91    strength: uqa_sql::ast::LockStrength,
92) -> Result<bool, SQLError> {
93    match session.lock_row(
94        table,
95        doc_id,
96        strength,
97        uqa_sql::ast::LockWait::Block,
98        display_name,
99    )? {
100        crate::row_locks::LockAcquire::Granted { waited, .. } => Ok(waited),
101        crate::row_locks::LockAcquire::Skipped => Err(SQLError::Internal(
102            "DML row locking used SKIP LOCKED".into(),
103        )),
104    }
105}
106
107/// Lock a DML target row and follow any primary-key rewrite another transaction committed while this statement waited, exactly like `PostgreSQL` 18 follows the update chain to the row version it lands on. Returns the doc id the statement must act on together with whether any wait or successor hop makes a re-qualification necessary. Callers acquire every row dependency first and promote the backend writer only after that lock phase has completed.
108pub fn lock_mutation_target(
109    session: &dyn RowLockSession,
110    table: &str,
111    display_name: &str,
112    doc_id: DocId,
113    strength: uqa_sql::ast::LockStrength,
114) -> Result<MutationLockTarget, SQLError> {
115    let mut current = doc_id;
116    let mut recheck = false;
117    let mut hops = 0usize;
118    loop {
119        recheck |= lock_mutation_row(session, table, display_name, current, strength)?;
120        let successor = match session.committed_row_successor(table, current)? {
121            crate::row_locks::RowChangeTarget::Unchanged => {
122                return Ok(MutationLockTarget::Present {
123                    doc_id: current,
124                    recheck,
125                });
126            }
127            crate::row_locks::RowChangeTarget::Deleted
128            | crate::row_locks::RowChangeTarget::Present(_)
129                if session.uses_fixed_snapshot() =>
130            {
131                return Err(concurrent_update_serialization_failure());
132            }
133            crate::row_locks::RowChangeTarget::Deleted => {
134                return Ok(MutationLockTarget::Deleted);
135            }
136            crate::row_locks::RowChangeTarget::Present(successor) => successor,
137        };
138        if successor == current {
139            return Ok(MutationLockTarget::Present {
140                doc_id: current,
141                recheck: true,
142            });
143        }
144        hops += 1;
145        if hops > 64 {
146            return Err(SQLError::Internal(format!(
147                "primary-key rewrite chain for `{table}` row {doc_id} did not converge"
148            )));
149        }
150        recheck = true;
151        current = successor;
152    }
153}
154
155/// Lock a DML candidate and follow a committed update chain across physical relations. Declarative partition movement changes the leaf table as well as the document id, so callers that scan a hierarchy must retain the complete successor identity.
156pub fn lock_physical_mutation_target(
157    session: &dyn RowLockSession,
158    table: &str,
159    display_name: &str,
160    doc_id: DocId,
161    strength: uqa_sql::ast::LockStrength,
162) -> Result<PhysicalMutationLockTarget, SQLError> {
163    let mut current = PhysicalDocumentIdentity {
164        table: table.to_string(),
165        doc_id,
166    };
167    let mut recheck = false;
168    let mut visited = BTreeSet::new();
169    loop {
170        if !visited.insert(current.clone()) {
171            return Err(SQLError::Internal(format!(
172                "physical rewrite chain for `{display_name}` row {table}:{doc_id} contains a cycle at {}:{}",
173                current.table, current.doc_id
174            )));
175        }
176        recheck |= lock_mutation_row(
177            session,
178            &current.table,
179            display_name,
180            current.doc_id,
181            strength,
182        )?;
183        match session.committed_physical_row_successor(&current.table, current.doc_id)? {
184            crate::row_locks::PhysicalRowChangeTarget::Unchanged => {
185                return Ok(PhysicalMutationLockTarget::Present {
186                    identity: current,
187                    recheck,
188                });
189            }
190            crate::row_locks::PhysicalRowChangeTarget::Deleted
191            | crate::row_locks::PhysicalRowChangeTarget::Present { .. }
192                if session.uses_fixed_snapshot() =>
193            {
194                return Err(concurrent_update_serialization_failure());
195            }
196            crate::row_locks::PhysicalRowChangeTarget::Deleted => {
197                return Ok(PhysicalMutationLockTarget::Deleted);
198            }
199            crate::row_locks::PhysicalRowChangeTarget::Present { table_hash, doc_id } => {
200                let table = session.table_for_lock_hash(table_hash)?;
201                if table == current.table && doc_id == current.doc_id {
202                    return Ok(PhysicalMutationLockTarget::Present {
203                        identity: current,
204                        recheck: true,
205                    });
206                }
207                recheck = true;
208                current = PhysicalDocumentIdentity { table, doc_id };
209            }
210        }
211    }
212}