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