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;
20
21fn cte_plan_has_row_locks(body: &crate::plan::CtePlanBody) -> bool {
22    match body {
23        crate::plan::CtePlanBody::Query(query) => query_plan_has_row_locks(query),
24        crate::plan::CtePlanBody::Command(command) => {
25            command
26                .ctes()
27                .iter()
28                .any(|cte| cte_plan_has_row_locks(&cte.body))
29                || command
30                    .query_inputs()
31                    .into_iter()
32                    .any(query_plan_has_row_locks)
33                || command
34                    .source_input()
35                    .is_some_and(source_plan_has_row_locks)
36        }
37    }
38}
39
40pub fn query_plan_has_row_locks(query: &QueryPlan) -> bool {
41    query
42        .ctes
43        .iter()
44        .any(|cte| cte_plan_has_row_locks(&cte.body))
45        || relational_has_row_locks(&query.root)
46}
47
48fn relational_has_row_locks(plan: &RelationalPlan) -> bool {
49    match plan {
50        RelationalPlan::QueryBlock(block) => {
51            !block.locking.is_empty()
52                || block.from.as_ref().is_some_and(source_plan_has_row_locks)
53                || block.subqueries.iter().any(query_plan_has_row_locks)
54        }
55        RelationalPlan::SetOp { left, right, .. } => {
56            query_plan_has_row_locks(left) || query_plan_has_row_locks(right)
57        }
58        RelationalPlan::Values { .. } => false,
59    }
60}
61
62fn source_plan_has_row_locks(source: &SourcePlan) -> bool {
63    match source {
64        crate::plan::SourcePlan::RetainedRows(_) => false,
65        SourcePlan::Join { left, right, .. } => {
66            source_plan_has_row_locks(left) || source_plan_has_row_locks(right)
67        }
68        SourcePlan::Subquery { body, .. } => query_plan_has_row_locks(body),
69        SourcePlan::Table { .. }
70        | SourcePlan::Values { .. }
71        | SourcePlan::Function { .. }
72        | SourcePlan::FunctionGroup { .. } => false,
73    }
74}
75
76/// 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.
77pub fn apply_propagated_view_lock(plan: &mut QueryPlan, target: &ResolvedRowLock) {
78    apply_propagated_lock_to_relational(&mut plan.root, target.strength, target.wait);
79}
80
81fn apply_propagated_lock_to_relational(
82    plan: &mut RelationalPlan,
83    strength: LockStrength,
84    wait: LockWait,
85) {
86    let RelationalPlan::QueryBlock(block) = plan else {
87        return;
88    };
89    block.locking.push(LockingClause {
90        strength,
91        wait,
92        relations: Vec::new(),
93    });
94    if let Some(source) = block.from.as_mut() {
95        apply_propagated_lock_to_subqueries(source, strength, wait);
96    }
97}
98
99fn apply_propagated_lock_to_subqueries(
100    source: &mut SourcePlan,
101    strength: LockStrength,
102    wait: LockWait,
103) {
104    match source {
105        crate::plan::SourcePlan::RetainedRows(_) => {}
106        SourcePlan::Join { left, right, .. } => {
107            apply_propagated_lock_to_subqueries(left, strength, wait);
108            apply_propagated_lock_to_subqueries(right, strength, wait);
109        }
110        SourcePlan::Subquery { body, .. } => {
111            apply_propagated_lock_to_relational(&mut body.root, strength, wait);
112        }
113        SourcePlan::Table { .. }
114        | SourcePlan::Values { .. }
115        | SourcePlan::Function { .. }
116        | SourcePlan::FunctionGroup { .. } => {}
117    }
118}
119
120pub fn validate_locking_block_shape(
121    block: &QueryBlockPlan,
122    strength: LockStrength,
123) -> Result<(), SQLError> {
124    let label = strength.sql_name();
125    if block.distinct || !block.distinct_on.is_empty() {
126        return Err(SQLError::Unsupported(format!(
127            "{label} is not allowed with DISTINCT clause"
128        )));
129    }
130    if !block.group_by.is_empty() || !block.grouping_sets.is_empty() {
131        return Err(SQLError::Unsupported(format!(
132            "{label} is not allowed with GROUP BY clause"
133        )));
134    }
135    if block.having.is_some() {
136        return Err(SQLError::Unsupported(format!(
137            "{label} is not allowed with HAVING clause"
138        )));
139    }
140    if matches!(block.compute, ComputePlan::Window)
141        || block
142            .order_by
143            .iter()
144            .any(|ordering| ordering.expr.contains_window())
145    {
146        return Err(SQLError::Unsupported(format!(
147            "{label} is not allowed with window functions"
148        )));
149    }
150    if matches!(block.compute, ComputePlan::Aggregate) {
151        return Err(SQLError::Unsupported(format!(
152            "{label} is not allowed with aggregate functions"
153        )));
154    }
155    Ok(())
156}
157
158pub fn update_lock_strength(
159    keys: &[TableKeyConstraint],
160    definitions: &[ColumnDef],
161    columns: &[String],
162) -> LockStrength {
163    let assigned = columns.iter().map(String::as_str).collect::<BTreeSet<_>>();
164    let touches_key = keys.iter().any(|constraint| {
165        constraint.columns.iter().any(|column| {
166            if assigned.contains(column.as_str()) {
167                return true;
168            }
169            let Some(generated) = definitions
170                .iter()
171                .find(|definition| definition.name == *column)
172                .and_then(|definition| definition.generated.as_ref())
173            else {
174                return false;
175            };
176            let mut dependencies = BTreeSet::new();
177            let expression = crate::plan::ExpressionPlan::lower((*generated.expression).clone());
178            !expression.scalar.collect_columns(&mut dependencies)
179                || dependencies
180                    .iter()
181                    .any(|dependency| assigned.contains(dependency.as_str()))
182        })
183    });
184    if touches_key {
185        crate::ast::LockStrength::ForUpdate
186    } else {
187        crate::ast::LockStrength::ForNoKeyUpdate
188    }
189}