Skip to main content

uqa_sql/semantics/
locking.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! SQL row-lock restrictions, propagation, and mutation lock strength.
8
9use crate::ast::{ColumnDef, LockStrength, LockWait, LockingClause, TableKeyConstraint};
10use crate::{
11    plan::{
12        locking::ResolvedRowLock, ComputePlan, QueryBlockPlan, QueryPlan, RelationalPlan,
13        SourcePlan,
14    },
15    SQLError,
16};
17use std::collections::BTreeSet;
18
19pub mod null_rejection;
20mod owned;
21pub use owned::apply_propagated_view_lock_owned;
22
23fn cte_plan_has_row_locks(body: &crate::plan::CtePlanBody) -> bool {
24    match body {
25        crate::plan::CtePlanBody::Query(query) => query_plan_has_row_locks(query),
26        crate::plan::CtePlanBody::Command(command) => {
27            command
28                .ctes()
29                .iter()
30                .any(|cte| cte_plan_has_row_locks(&cte.body))
31                || command.query_inputs().any(query_plan_has_row_locks)
32                || command
33                    .source_input()
34                    .is_some_and(source_plan_has_row_locks)
35        }
36    }
37}
38
39pub fn query_plan_has_row_locks(query: &QueryPlan) -> bool {
40    query
41        .ctes
42        .iter()
43        .any(|cte| cte_plan_has_row_locks(&cte.body))
44        || relational_has_row_locks(&query.root)
45}
46
47fn relational_has_row_locks(plan: &RelationalPlan) -> bool {
48    match plan {
49        RelationalPlan::QueryBlock(block) => {
50            !block.locking.is_empty()
51                || block.from.as_ref().is_some_and(source_plan_has_row_locks)
52                || block.subqueries.iter().any(query_plan_has_row_locks)
53        }
54        RelationalPlan::SetOp { left, right, .. } => {
55            query_plan_has_row_locks(left) || query_plan_has_row_locks(right)
56        }
57        RelationalPlan::Values { .. } => false,
58    }
59}
60
61fn source_plan_has_row_locks(source: &SourcePlan) -> bool {
62    match source {
63        crate::plan::SourcePlan::RetainedRows(_) => false,
64        SourcePlan::Join { left, right, .. } => {
65            source_plan_has_row_locks(left) || source_plan_has_row_locks(right)
66        }
67        SourcePlan::Subquery { body, .. } => query_plan_has_row_locks(body),
68        SourcePlan::Table { .. }
69        | SourcePlan::Values { .. }
70        | SourcePlan::Function { .. }
71        | SourcePlan::FunctionGroup { .. } => false,
72    }
73}
74
75/// Apply a row mark selected for a stored view to the view plan before execution. Stored view plans are not present when the SQL compiler pushes row marks into derived tables, so runtime expansion must perform the same propagation to ensure an outer `NOWAIT` or `SKIP LOCKED` policy is merged before an inner row mark can block.
76pub fn apply_propagated_view_lock(plan: &mut QueryPlan, target: &ResolvedRowLock) {
77    apply_propagated_lock_to_relational(&mut plan.root, target.strength, target.wait);
78}
79
80fn apply_propagated_lock_to_relational(
81    plan: &mut RelationalPlan,
82    strength: LockStrength,
83    wait: LockWait,
84) {
85    let RelationalPlan::QueryBlock(block) = plan else {
86        return;
87    };
88    block.locking.push(LockingClause {
89        strength,
90        wait,
91        relations: Vec::new(),
92    });
93    if let Some(source) = block.from.as_mut() {
94        apply_propagated_lock_to_subqueries(source, strength, wait);
95    }
96}
97
98fn apply_propagated_lock_to_subqueries(
99    source: &mut SourcePlan,
100    strength: LockStrength,
101    wait: LockWait,
102) {
103    match source {
104        crate::plan::SourcePlan::RetainedRows(_) => {}
105        SourcePlan::Join { left, right, .. } => {
106            apply_propagated_lock_to_subqueries(left, strength, wait);
107            apply_propagated_lock_to_subqueries(right, strength, wait);
108        }
109        SourcePlan::Subquery { body, .. } => {
110            apply_propagated_lock_to_relational(&mut body.root, strength, wait);
111        }
112        SourcePlan::Table { .. }
113        | SourcePlan::Values { .. }
114        | SourcePlan::Function { .. }
115        | SourcePlan::FunctionGroup { .. } => {}
116    }
117}
118
119pub fn validate_locking_block_shape(
120    block: &QueryBlockPlan,
121    strength: LockStrength,
122) -> Result<(), SQLError> {
123    let label = strength.sql_name();
124    if block.distinct || !block.distinct_on.is_empty() {
125        return Err(SQLError::Unsupported(format!(
126            "{label} is not allowed with DISTINCT clause"
127        )));
128    }
129    if !block.group_by.is_empty() || !block.grouping_sets.is_empty() {
130        return Err(SQLError::Unsupported(format!(
131            "{label} is not allowed with GROUP BY clause"
132        )));
133    }
134    if block.having.is_some() {
135        return Err(SQLError::Unsupported(format!(
136            "{label} is not allowed with HAVING clause"
137        )));
138    }
139    if matches!(block.compute, ComputePlan::Window)
140        || block
141            .order_by
142            .iter()
143            .any(|ordering| ordering.expr.contains_window())
144    {
145        return Err(SQLError::Unsupported(format!(
146            "{label} is not allowed with window functions"
147        )));
148    }
149    if matches!(block.compute, ComputePlan::Aggregate) {
150        return Err(SQLError::Unsupported(format!(
151            "{label} is not allowed with aggregate functions"
152        )));
153    }
154    Ok(())
155}
156
157pub fn update_lock_strength(
158    keys: &[TableKeyConstraint],
159    definitions: &[ColumnDef],
160    columns: &[String],
161) -> LockStrength {
162    let assigned = columns.iter().map(String::as_str).collect::<BTreeSet<_>>();
163    let touches_key = keys.iter().any(|constraint| {
164        constraint.columns.iter().any(|column| {
165            if assigned.contains(column.as_str()) {
166                return true;
167            }
168            let Some(generated) = definitions
169                .iter()
170                .find(|definition| definition.name == *column)
171                .and_then(|definition| definition.generated.as_ref())
172            else {
173                return false;
174            };
175            let mut dependencies = BTreeSet::new();
176            let expression = crate::plan::ExpressionPlan::lower((*generated.expression).clone());
177            !expression.scalar.collect_columns(&mut dependencies)
178                || dependencies
179                    .iter()
180                    .any(|dependency| assigned.contains(dependency.as_str()))
181        })
182    });
183    if touches_key {
184        crate::ast::LockStrength::ForUpdate
185    } else {
186        crate::ast::LockStrength::ForNoKeyUpdate
187    }
188}