Skip to main content

uqa_execution/query/
locking.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Row-lock target resolution and the physical `LockRows` operator.
8
9use super::recheck_source::LockRowsRecheckSource;
10use crate::catalog::schema::virtual_relation_accepts_row_lock as virtual_row_lockable;
11use crate::catalog::{CatalogReadView, RelationNameResolution};
12use crate::query::{binding::bind_source_plan_schema, CteScope};
13use crate::row_locks::{
14    binding::{bind_relation, lock_descendants, RelationBinding},
15    recheck::recheck_storage_names_match,
16    retry_cache::RowLockRetryCache,
17    LockAcquire,
18};
19use crate::{Batch, ExecResult, PhysicalOperator, PhysicalRow, RowProjectionValue, RowSchema};
20use uqa_sql::ast::{LockStrength, LockWait, LockingClause, RelationPersistence};
21use uqa_sql::{
22    plan::{CommandPlan, QueryBlockPlan, QueryPlan, RelationalPlan, SourcePlan, UnifiedPlan},
23    SQLError, SQLParam, ScalarExpr,
24};
25pub mod context;
26pub use context::RowLockContext;
27
28pub use crate::query::scope::ResolvedRowLock;
29
30pub fn query_has_row_locks(query: &QueryPlan) -> bool {
31    query_plan_has_row_locks(query)
32}
33
34/// Acquire `PostgreSQL` `AccessShareLock` equivalents for every concrete table referenced by a query. The locks are transaction-scoped, so a cursor declaration keeps its bound relations alive until commit while ordinary persistent statements keep DDL from changing a source during execution.
35pub fn lock_query_relations<S: Clone + Send + Sync + 'static>(
36    context: RowLockContext<'_, S>,
37    query: &QueryPlan,
38) -> Result<(), SQLError> {
39    let mut locked = std::collections::BTreeSet::new();
40    let mut visiting_views = std::collections::BTreeSet::new();
41    let transition_relations = context.scopes.transition_relation_names();
42    lock_query_plan_relations(
43        context,
44        query,
45        &transition_relations,
46        &mut locked,
47        &mut visiting_views,
48    )
49}
50
51/// Hold the explained statement's relation identities before collecting physical metadata or executing ANALYZE.
52pub fn lock_explained_relations<S: Clone + Send + Sync + 'static>(
53    context: RowLockContext<'_, S>,
54    plan: &UnifiedPlan,
55) -> Result<(), SQLError> {
56    match plan {
57        UnifiedPlan::Query(query) => lock_query_relations(context, query),
58        UnifiedPlan::Command(command) => match command.as_ref() {
59            CommandPlan::Explain { body, .. } => lock_explained_relations(context, body),
60            CommandPlan::CreateTableAs { query, .. }
61            | CommandPlan::CreateMaterializedView { query, .. }
62            | CommandPlan::DeclareCursor { query, .. } => lock_query_relations(context, query),
63            _ => lock_command_plan_relations(
64                context,
65                command,
66                &context.scopes.transition_relation_names(),
67                &mut std::collections::BTreeSet::new(),
68                &mut std::collections::BTreeSet::new(),
69            ),
70        },
71    }
72}
73
74fn lock_query_plan_relations<S: Clone + Send + Sync + 'static>(
75    context: RowLockContext<'_, S>,
76    query: &QueryPlan,
77    inherited_ctes: &std::collections::BTreeSet<String>,
78    locked: &mut std::collections::BTreeSet<String>,
79    visiting_views: &mut std::collections::BTreeSet<String>,
80) -> Result<(), SQLError> {
81    let mut visible_ctes = inherited_ctes.clone();
82    for cte in &query.ctes {
83        let mut definition_scope = visible_ctes.clone();
84        if cte.recursive {
85            definition_scope.insert(cte.name.clone());
86        }
87        lock_cte_plan_relations(
88            context,
89            &cte.body,
90            &definition_scope,
91            locked,
92            visiting_views,
93        )?;
94        visible_ctes.insert(cte.name.clone());
95    }
96    lock_relational_plan_relations(
97        context,
98        &query.root,
99        &visible_ctes,
100        query.relations_bound,
101        locked,
102        visiting_views,
103    )
104}
105
106fn lock_cte_plan_relations<S: Clone + Send + Sync + 'static>(
107    context: RowLockContext<'_, S>,
108    body: &uqa_sql::plan::CtePlanBody,
109    inherited: &std::collections::BTreeSet<String>,
110    locked: &mut std::collections::BTreeSet<String>,
111    visiting: &mut std::collections::BTreeSet<String>,
112) -> Result<(), SQLError> {
113    match body {
114        uqa_sql::plan::CtePlanBody::Query(query) => {
115            lock_query_plan_relations(context, query, inherited, locked, visiting)
116        }
117        uqa_sql::plan::CtePlanBody::Command(command) => {
118            lock_command_plan_relations(context, command, inherited, locked, visiting)
119        }
120    }
121}
122
123fn lock_command_plan_relations<S: Clone + Send + Sync + 'static>(
124    context: RowLockContext<'_, S>,
125    command: &CommandPlan,
126    inherited: &std::collections::BTreeSet<String>,
127    locked: &mut std::collections::BTreeSet<String>,
128    visiting: &mut std::collections::BTreeSet<String>,
129) -> Result<(), SQLError> {
130    let (bound, target_bound, descendants) = match command {
131        CommandPlan::Insert(plan) => (plan.relations_bound, plan.target_relation_bound, false),
132        CommandPlan::Update(plan) => (
133            plan.relations_bound,
134            plan.target_relation_bound,
135            plan.include_descendants,
136        ),
137        CommandPlan::Delete(plan) => (
138            plan.relations_bound,
139            plan.target_relation_bound,
140            plan.include_descendants,
141        ),
142        CommandPlan::Merge(plan) => (false, false, plan.include_descendants),
143        _ => (false, false, false),
144    };
145    if let Some(target) = command.mutation_target() {
146        let mode = crate::row_locks::RelationLockMode::RowExclusive;
147        if let Some(binding) = bind_relation(
148            context.session,
149            mode,
150            false,
151            || {
152                context
153                    .catalog
154                    .resolve_relation(target, target_bound)?
155                    .map(|(name, kind)| {
156                        Ok(RelationBinding {
157                            object_id: context.catalog.relation_object_id(&name)?,
158                            name,
159                            value: kind,
160                        })
161                    })
162                    .transpose()
163            },
164            |_| Ok(()),
165        )? {
166            if binding.value == "table" {
167                lock_descendants(
168                    context.catalog,
169                    context.session,
170                    context
171                        .catalog
172                        .hierarchy_scan_tables(&binding.name, descendants)?
173                        .into_iter()
174                        .filter(|name| name != &binding.name),
175                    mode,
176                    false,
177                )?;
178            }
179        }
180    }
181    let mut visible = inherited.clone();
182    if command.ctes().iter().any(|cte| cte.recursive) {
183        visible.extend(command.ctes().iter().map(|cte| cte.name.clone()));
184    }
185    for cte in command.ctes() {
186        lock_cte_plan_relations(context, &cte.body, &visible, locked, visiting)?;
187        visible.insert(cte.name.clone());
188    }
189    for query in command.query_inputs() {
190        lock_query_plan_relations(context, query, &visible, locked, visiting)?;
191    }
192    if let Some(source) = command.source_input() {
193        lock_source_plan_relations(context, source, &visible, bound, locked, visiting)?;
194    }
195    Ok(())
196}
197
198fn validate_cte_row_locks<S: Clone + Send + Sync + 'static>(
199    context: RowLockContext<'_, S>,
200    body: &uqa_sql::plan::CtePlanBody,
201    params: &[SQLParam],
202    ctes: &CteScope<S>,
203) -> Result<(), SQLError> {
204    match body {
205        uqa_sql::plan::CtePlanBody::Query(query) => {
206            validate_query_plan_row_locks(context, query, params, ctes)
207        }
208        uqa_sql::plan::CtePlanBody::Command(command) => {
209            for cte in command.ctes() {
210                validate_cte_row_locks(context, &cte.body, params, ctes)?;
211            }
212            for query in command.query_inputs() {
213                validate_query_plan_row_locks(context, query, params, ctes)?;
214            }
215            if let Some(source) = command.source_input() {
216                validate_source_row_locks(context, source, params, ctes)?;
217            }
218            Ok(())
219        }
220    }
221}
222
223fn lock_relational_plan_relations<S: Clone + Send + Sync + 'static>(
224    context: RowLockContext<'_, S>,
225    plan: &RelationalPlan,
226    visible_ctes: &std::collections::BTreeSet<String>,
227    relations_bound: bool,
228    locked: &mut std::collections::BTreeSet<String>,
229    visiting_views: &mut std::collections::BTreeSet<String>,
230) -> Result<(), SQLError> {
231    match plan {
232        RelationalPlan::QueryBlock(block) => {
233            if let Some(source) = block.from.as_ref() {
234                lock_source_plan_relations(
235                    context,
236                    source,
237                    visible_ctes,
238                    relations_bound,
239                    locked,
240                    visiting_views,
241                )?;
242            }
243            for subquery in &block.subqueries {
244                lock_query_plan_relations(context, subquery, visible_ctes, locked, visiting_views)?;
245            }
246            Ok(())
247        }
248        RelationalPlan::SetOp {
249            left,
250            right,
251            subqueries,
252            ..
253        } => {
254            lock_query_plan_relations(context, left, visible_ctes, locked, visiting_views)?;
255            lock_query_plan_relations(context, right, visible_ctes, locked, visiting_views)?;
256            for subquery in subqueries {
257                lock_query_plan_relations(context, subquery, visible_ctes, locked, visiting_views)?;
258            }
259            Ok(())
260        }
261        RelationalPlan::Values { subqueries, .. } => {
262            for subquery in subqueries {
263                lock_query_plan_relations(context, subquery, visible_ctes, locked, visiting_views)?;
264            }
265            Ok(())
266        }
267    }
268}
269
270fn lock_source_plan_relations<S: Clone + Send + Sync + 'static>(
271    context: RowLockContext<'_, S>,
272    source: &SourcePlan,
273    visible_ctes: &std::collections::BTreeSet<String>,
274    relations_bound: bool,
275    locked: &mut std::collections::BTreeSet<String>,
276    visiting_views: &mut std::collections::BTreeSet<String>,
277) -> Result<(), SQLError> {
278    match source {
279        SourcePlan::Table {
280            name,
281            include_descendants,
282            ..
283        } => {
284            if uqa_sql::semantics::cte_reference_name(name)
285                .is_some_and(|name| visible_ctes.contains(&name))
286            {
287                return Ok(());
288            }
289            lock_named_query_relation(
290                context,
291                name,
292                relations_bound,
293                *include_descendants,
294                locked,
295                visiting_views,
296            )
297        }
298        SourcePlan::Join { left, right, .. } => {
299            lock_source_plan_relations(
300                context,
301                left,
302                visible_ctes,
303                relations_bound,
304                locked,
305                visiting_views,
306            )?;
307            lock_source_plan_relations(
308                context,
309                right,
310                visible_ctes,
311                relations_bound,
312                locked,
313                visiting_views,
314            )
315        }
316        SourcePlan::Subquery { body, .. } => {
317            lock_query_plan_relations(context, body, visible_ctes, locked, visiting_views)
318        }
319        SourcePlan::Function { relations, .. } => {
320            lock_table_function_relations(context, relations.as_ref(), relations_bound, locked)
321        }
322        SourcePlan::FunctionGroup { functions, .. } => {
323            for function in functions {
324                lock_table_function_relations(
325                    context,
326                    function.relations.as_ref(),
327                    relations_bound,
328                    locked,
329                )?;
330            }
331            Ok(())
332        }
333        SourcePlan::RetainedRows(_) | SourcePlan::Values { .. } => Ok(()),
334    }
335}
336
337fn lock_named_query_relation<S: Clone + Send + Sync + 'static>(
338    context: RowLockContext<'_, S>,
339    name: &str,
340    relations_bound: bool,
341    include_descendants: bool,
342    locked: &mut std::collections::BTreeSet<String>,
343    visiting_views: &mut std::collections::BTreeSet<String>,
344) -> Result<(), SQLError> {
345    let Some(binding) = bind_relation(
346        context.session,
347        crate::row_locks::RelationLockMode::AccessShare,
348        false,
349        || {
350            context
351                .catalog
352                .resolve_relation(name, relations_bound)?
353                .map(|(canonical, kind)| {
354                    let object_id = context.catalog.relation_object_id(&canonical)?;
355                    Ok(RelationBinding {
356                        name: canonical,
357                        object_id,
358                        value: kind,
359                    })
360                })
361                .transpose()
362        },
363        |_| Ok(()),
364    )?
365    else {
366        return Ok(());
367    };
368    let canonical = binding.name;
369    locked.insert(canonical.clone());
370    if let Some(relation) = uqa_sql::catalog::SystemRelation::from_qualified_name(&canonical) {
371        for source in relation.view_sources() {
372            lock_named_query_relation(
373                context,
374                &source.qualified_name(),
375                true,
376                false,
377                locked,
378                visiting_views,
379            )?;
380        }
381        return Ok(());
382    }
383    match binding.value {
384        "table" => lock_descendants(
385            context.catalog,
386            context.session,
387            context
388                .catalog
389                .hierarchy_scan_tables(&canonical, include_descendants)?
390                .into_iter()
391                .filter(|child| child != &canonical),
392            crate::row_locks::RelationLockMode::AccessShare,
393            false,
394        ),
395        "view" => {
396            let view_name = canonical;
397            let view = context.catalog.view_plan(&view_name)?.ok_or_else(|| {
398                SQLError::Internal(format!(
399                    "resolved query view `{view_name}` disappeared before locking"
400                ))
401            })?;
402            if !visiting_views.insert(view_name.clone()) {
403                return Err(SQLError::Internal(format!(
404                    "view `{view_name}` has a recursive relation dependency"
405                )));
406            }
407            let result = lock_query_plan_relations(
408                context,
409                &view,
410                &std::collections::BTreeSet::new(),
411                locked,
412                visiting_views,
413            );
414            visiting_views.remove(&view_name);
415            result
416        }
417        _ => Ok(()),
418    }
419}
420
421/// Resolve cursor row-lock targets without opening or pulling the query. `PostgreSQL` performs these declaration-time checks even though expression evaluation and tuple locking wait until FETCH.
422pub fn validate_query_row_locks<S: Clone + Send + Sync + 'static>(
423    context: RowLockContext<'_, S>,
424    query: &QueryPlan,
425    params: &[SQLParam],
426) -> Result<(), SQLError> {
427    let ctes = context.scopes.current_routine_scope();
428    validate_query_plan_row_locks(context, query, params, &ctes)
429}
430
431fn validate_query_plan_row_locks<S: Clone + Send + Sync + 'static>(
432    context: RowLockContext<'_, S>,
433    query: &QueryPlan,
434    params: &[SQLParam],
435    ctes: &CteScope<S>,
436) -> Result<(), SQLError> {
437    for cte in &query.ctes {
438        validate_cte_row_locks(context, &cte.body, params, ctes)?;
439    }
440    match &query.root {
441        RelationalPlan::QueryBlock(block) => {
442            for subquery in &block.subqueries {
443                validate_query_plan_row_locks(context, subquery, params, ctes)?;
444            }
445            if let Some(from) = block.from.as_ref() {
446                validate_source_row_locks(context, from, params, ctes)?;
447                resolve_row_locks(
448                    context,
449                    from,
450                    &block.locking,
451                    block.r#where.as_ref(),
452                    params,
453                    ctes,
454                )?;
455            }
456        }
457        RelationalPlan::SetOp { left, right, .. } => {
458            validate_query_plan_row_locks(context, left, params, ctes)?;
459            validate_query_plan_row_locks(context, right, params, ctes)?;
460        }
461        RelationalPlan::Values { subqueries, .. } => {
462            for subquery in subqueries {
463                validate_query_plan_row_locks(context, subquery, params, ctes)?;
464            }
465        }
466    }
467    Ok(())
468}
469
470fn validate_source_row_locks<S: Clone + Send + Sync + 'static>(
471    context: RowLockContext<'_, S>,
472    source: &SourcePlan,
473    params: &[SQLParam],
474    ctes: &CteScope<S>,
475) -> Result<(), SQLError> {
476    match source {
477        SourcePlan::Join { left, right, .. } => {
478            validate_source_row_locks(context, left, params, ctes)?;
479            validate_source_row_locks(context, right, params, ctes)
480        }
481        SourcePlan::Subquery { body, .. } => {
482            validate_query_plan_row_locks(context, body, params, ctes)
483        }
484        SourcePlan::RetainedRows(_)
485        | SourcePlan::Table { .. }
486        | SourcePlan::Values { .. }
487        | SourcePlan::Function { .. }
488        | SourcePlan::FunctionGroup { .. } => Ok(()),
489    }
490}
491
492use uqa_sql::semantics::locking::query_plan_has_row_locks;
493
494pub fn resolve_row_locks<S: Clone + Send + Sync + 'static>(
495    context: RowLockContext<'_, S>,
496    from: &SourcePlan,
497    locking: &[LockingClause],
498    predicate: Option<&ScalarExpr>,
499    params: &[SQLParam],
500    ctes: &CteScope<S>,
501) -> Result<Vec<ResolvedRowLock>, SQLError> {
502    if locking.is_empty() {
503        return Ok(Vec::new());
504    }
505    let mut effective_from = from.clone();
506    reduce_null_rejected_outer_joins_to_fixpoint(
507        context,
508        &mut effective_from,
509        predicate,
510        params,
511        ctes,
512    )?;
513    validate_lock_relation_aliases(&effective_from, locking)?;
514    let sources = collect_source_leaves(&effective_from, false, ctes)?;
515    let mut assigned: Vec<Option<(LockStrength, LockWait)>> = vec![None; sources.len()];
516    for clause in locking {
517        let selected = if clause.relations.is_empty() {
518            sources
519                .iter()
520                .enumerate()
521                .filter_map(|(index, source)| source.kind.implicitly_lockable().then_some(index))
522                .collect::<Vec<_>>()
523        } else {
524            let mut selected = vec![false; sources.len()];
525            for relation in &clause.relations {
526                let matches = sources
527                    .iter()
528                    .enumerate()
529                    .filter_map(|(index, source)| {
530                        source
531                            .names
532                            .iter()
533                            .any(|name| name == relation)
534                            .then_some(index)
535                    })
536                    .collect::<Vec<_>>();
537                if matches.is_empty() {
538                    return Err(SQLError::Routine {
539                        sqlstate: "42P01".into(),
540                        message: format!(
541                            "relation \"{relation}\" in FOR UPDATE/SHARE clause not found in FROM clause"
542                        ),
543                    });
544                }
545                for source_index in matches {
546                    selected[source_index] = true;
547                }
548            }
549            selected
550                .into_iter()
551                .enumerate()
552                .filter_map(|(index, selected)| selected.then_some(index))
553                .collect()
554        };
555        for source_index in selected {
556            assigned[source_index] = Some(match assigned[source_index] {
557                Some((strength, wait)) => (
558                    strength.max(clause.strength),
559                    merge_lock_wait(wait, clause.wait),
560                ),
561                None => (clause.strength, clause.wait),
562            });
563        }
564    }
565    let mut resolved = Vec::new();
566    for (source, assignment) in sources.iter().zip(assigned) {
567        let Some((strength, wait)) = assignment else {
568            continue;
569        };
570        reject_unusable_lock_leaf(context, source, strength)?;
571        if !source.kind.carries_row_identity() {
572            continue;
573        }
574        resolved.push(ResolvedRowLock {
575            qualifier: source.qualifier.clone(),
576            storage_name: source.storage_name.clone(),
577            display_name: source.display_name.clone(),
578            strength,
579            wait,
580            identity_source: source.kind.is_identity_source(),
581        });
582    }
583    if context.session.current_transaction_is_read_only()
584        && locks_non_temporary_relation(context, &resolved)?
585    {
586        return Err(SQLError::Routine {
587            sqlstate: "25006".into(),
588            message: "cannot execute SELECT in a read-only transaction".into(),
589        });
590    }
591    Ok(resolved)
592}
593
594fn locks_non_temporary_relation<S: Clone + Send + Sync + 'static>(
595    context: RowLockContext<'_, S>,
596    locks: &[ResolvedRowLock],
597) -> Result<bool, SQLError> {
598    for lock in locks {
599        let persistence = context
600            .catalog
601            .table_persistence(&lock.storage_name)
602            .map_err(|error| {
603                SQLError::Internal(format!(
604                    "resolve row-lock target `{}`: {error}",
605                    lock.storage_name
606                ))
607            })?;
608        if persistence != Some(RelationPersistence::Temporary) {
609            return Ok(true);
610        }
611    }
612    Ok(false)
613}
614
615fn source_contains_join_alias(source: &SourcePlan, target: &str) -> bool {
616    match source {
617        SourcePlan::Join {
618            left, right, alias, ..
619        } => {
620            alias.as_deref() == Some(target)
621                || source_contains_join_alias(left, target)
622                || source_contains_join_alias(right, target)
623        }
624        SourcePlan::RetainedRows(_)
625        | SourcePlan::Table { .. }
626        | SourcePlan::Values { .. }
627        | SourcePlan::Function { .. }
628        | SourcePlan::FunctionGroup { .. }
629        | SourcePlan::Subquery { .. } => false,
630    }
631}
632
633mod execution;
634mod null_rejection;
635mod targets;
636use null_rejection::reduce_null_rejected_outer_joins_to_fixpoint;
637use targets::lock_table_function_relations;
638
639fn merge_lock_wait(left: LockWait, right: LockWait) -> LockWait {
640    match (left, right) {
641        (LockWait::NoWait, _) | (_, LockWait::NoWait) => LockWait::NoWait,
642        (LockWait::SkipLocked, _) | (_, LockWait::SkipLocked) => LockWait::SkipLocked,
643        (LockWait::Block, LockWait::Block) => LockWait::Block,
644    }
645}
646
647pub use uqa_sql::semantics::locking::apply_propagated_view_lock;
648
649mod leaf_validation;
650use leaf_validation::{
651    collect_source_leaf_plans, collect_source_leaves, copy_recheck_source_row,
652    reject_unusable_lock_leaf, validate_locking_block_shape,
653};
654
655pub struct LockRows<'a, S: Clone> {
656    input: Box<dyn PhysicalOperator + 'a>,
657    context: RowLockContext<'a, S>,
658    params: &'a [SQLParam],
659    targets: Vec<ResolvedRowLock>,
660    max_rows: Option<u64>,
661    emitted: u64,
662    pending_rows: std::vec::IntoIter<PhysicalRow>,
663    discard_lock_origins: bool,
664    retry_cache: Option<std::sync::Arc<RowLockRetryCache>>,
665    recheck_source: Option<LockRowsRecheckSource<S>>,
666    schema: RowSchema,
667    /// Base relations that already hold this statement's `RowShare` lock. A view or derived-table target reveals its base relations only through row origins, so the relation lock is taken on first sight of each.
668    relation_locked: std::collections::BTreeSet<std::sync::Arc<str>>,
669}
670
671impl<'a, S: Clone> LockRows<'a, S> {
672    #[expect(
673        clippy::too_many_arguments,
674        reason = "keeps execution context inputs aligned"
675    )]
676    pub fn new(
677        input: Box<dyn PhysicalOperator + 'a>,
678        context: RowLockContext<'a, S>,
679        params: &'a [SQLParam],
680        targets: Vec<ResolvedRowLock>,
681        max_rows: Option<u64>,
682        discard_lock_origins: bool,
683        retry_cache: Option<std::sync::Arc<RowLockRetryCache>>,
684        recheck_source: Option<LockRowsRecheckSource<S>>,
685    ) -> Self {
686        let schema = input.row_schema().clone();
687        Self {
688            input,
689            context,
690            params,
691            targets,
692            max_rows,
693            emitted: 0,
694            pending_rows: Vec::new().into_iter(),
695            discard_lock_origins,
696            retry_cache,
697            recheck_source,
698            schema,
699            relation_locked: std::collections::BTreeSet::new(),
700        }
701    }
702}
703
704impl<S: Clone + Send + Sync + 'static> PhysicalOperator for LockRows<'_, S> {
705    fn row_schema(&self) -> &RowSchema {
706        &self.schema
707    }
708
709    fn estimated_cardinality(&self) -> Option<u64> {
710        match (self.input.estimated_cardinality(), self.max_rows) {
711            (Some(input), Some(max_rows)) => Some(input.min(max_rows)),
712            (estimate, None) | (None, estimate) => estimate,
713        }
714    }
715
716    fn output_ordering(&self) -> &[crate::PhysicalOrder] {
717        self.input.output_ordering()
718    }
719
720    fn open(&mut self) -> ExecResult<()> {
721        self.emitted = 0;
722        self.pending_rows = Vec::new().into_iter();
723        self.input.open()
724    }
725
726    // Keep the virtual pull boundary intact under `ThinLTO`; the acquisition and recheck state machines below are deliberately separate optimized functions.
727    #[inline(never)]
728    fn next(&mut self) -> ExecResult<Option<Batch>> {
729        if self
730            .max_rows
731            .is_some_and(|max_rows| self.emitted >= max_rows)
732        {
733            return Ok(None);
734        }
735        loop {
736            self.context.cancellation.check().map_err(SQLError::from)?;
737            if let Some(row) = self.pending_rows.next() {
738                if let Some(mut row) = self.lock_physical_row(row)? {
739                    if self.discard_lock_origins {
740                        row.discard_lock_origins_mut();
741                    }
742                    self.emitted = self.emitted.saturating_add(1);
743                    // One row per batch keeps locking demand-driven: an enclosing consumer such as an outer LIMIT over a locking derived table stops pulling after the rows it needs, so rows it never consumes are never locked (PostgreSQL 18 LockRows semantics). Batching ahead would lock rows the consumer discards.
744                    return Ok(Some(Batch::from_physical_rows(
745                        self.schema.clone(),
746                        vec![row],
747                    )));
748                }
749                continue;
750            }
751            let Some(batch) = self.input.next_with_demand(crate::physical::demand::ONE)? else {
752                return Ok(None);
753            };
754            self.pending_rows = batch.rows.into_iter();
755        }
756    }
757
758    fn close(&mut self) -> ExecResult<()> {
759        self.input.close()
760    }
761}
762
763pub fn attach_lock_rows<'a, S: Clone + Send + Sync + 'static>(
764    context: RowLockContext<'a, S>,
765    operator: Box<dyn PhysicalOperator + 'a>,
766    statement: &QueryBlockPlan,
767    params: &'a [SQLParam],
768    ctes: &CteScope<S>,
769    max_rows: Option<u64>,
770    recheck_source: Option<LockRowsRecheckSource<S>>,
771) -> Result<Box<dyn PhysicalOperator + 'a>, SQLError> {
772    crate::physical::construction::OperatorBuild::build(operator, |operator| {
773        let Some(first_clause) = statement.locking.first() else {
774            return Ok(());
775        };
776        if ctes.row_lock_recheck_active() {
777            // A tuple-local recheck re-executes the plan below its own LockRows boundary. Locks for the candidate are already held, so nested locking is suppressed while lock identities keep flowing.
778            return Ok(());
779        }
780        validate_locking_block_shape(statement, first_clause.strength)?;
781        let Some(from) = statement.from.as_ref() else {
782            return Ok(());
783        };
784        let targets = resolve_row_locks(
785            context,
786            from,
787            &statement.locking,
788            statement.r#where.as_ref(),
789            params,
790            ctes,
791        )?;
792        if targets.is_empty() {
793            return Ok(());
794        }
795        let mut locked_relations = std::collections::BTreeSet::new();
796        for target in targets.iter().filter(|target| !target.identity_source) {
797            if locked_relations.insert(target.storage_name.clone()) {
798                context.session.lock_relation(
799                    &target.storage_name,
800                    crate::row_locks::RelationLockMode::RowShare,
801                )?;
802            }
803        }
804        // The recheck context is shared per SQL statement through the context session, so every locking scope reaches it: top-level queries, DML sources, DML CTEs, CREATE TABLE AS, prepared execution, and EXPLAIN ANALYZE bodies.
805        let retry_cache = context.session.statement_row_lock_cache()?;
806        operator.wrap(|input| {
807            Box::new(LockRows::new(
808                input,
809                context,
810                params,
811                targets,
812                max_rows,
813                !ctes.lock_identities.retain_after_lock,
814                Some(retry_cache),
815                recheck_source,
816            ))
817        });
818        Ok(())
819    })
820}
821
822fn validate_lock_relation_aliases(
823    from: &SourcePlan,
824    locking: &[LockingClause],
825) -> Result<(), SQLError> {
826    for clause in locking {
827        if clause
828            .relations
829            .iter()
830            .any(|relation| source_contains_join_alias(from, relation))
831        {
832            return Err(SQLError::Unsupported(format!(
833                "{} cannot be applied to a join",
834                clause.strength.sql_name()
835            )));
836        }
837    }
838    Ok(())
839}