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::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::Table { .. }
485        | SourcePlan::Values { .. }
486        | SourcePlan::Function { .. }
487        | SourcePlan::FunctionGroup { .. } => Ok(()),
488    }
489}
490
491use uqa_sql::semantics::locking::query_plan_has_row_locks;
492
493pub fn resolve_row_locks<S: Clone + Send + Sync + 'static>(
494    context: RowLockContext<'_, S>,
495    from: &SourcePlan,
496    locking: &[LockingClause],
497    predicate: Option<&ScalarExpr>,
498    params: &[SQLParam],
499    ctes: &CteScope<S>,
500) -> Result<Vec<ResolvedRowLock>, SQLError> {
501    if locking.is_empty() {
502        return Ok(Vec::new());
503    }
504    let mut effective_from = from.clone();
505    reduce_null_rejected_outer_joins_to_fixpoint(
506        context,
507        &mut effective_from,
508        predicate,
509        params,
510        ctes,
511    )?;
512    validate_lock_relation_aliases(&effective_from, locking)?;
513    let sources = collect_source_leaves(&effective_from, false, ctes)?;
514    let mut assigned: Vec<Option<(LockStrength, LockWait)>> = vec![None; sources.len()];
515    for clause in locking {
516        let selected = if clause.relations.is_empty() {
517            sources
518                .iter()
519                .enumerate()
520                .filter_map(|(index, source)| source.kind.implicitly_lockable().then_some(index))
521                .collect::<Vec<_>>()
522        } else {
523            let mut selected = vec![false; sources.len()];
524            for relation in &clause.relations {
525                let matches = sources
526                    .iter()
527                    .enumerate()
528                    .filter_map(|(index, source)| {
529                        source
530                            .names
531                            .iter()
532                            .any(|name| name == relation)
533                            .then_some(index)
534                    })
535                    .collect::<Vec<_>>();
536                if matches.is_empty() {
537                    return Err(SQLError::Routine {
538                        sqlstate: "42P01".into(),
539                        message: format!(
540                            "relation \"{relation}\" in FOR UPDATE/SHARE clause not found in FROM clause"
541                        ),
542                    });
543                }
544                for source_index in matches {
545                    selected[source_index] = true;
546                }
547            }
548            selected
549                .into_iter()
550                .enumerate()
551                .filter_map(|(index, selected)| selected.then_some(index))
552                .collect()
553        };
554        for source_index in selected {
555            assigned[source_index] = Some(match assigned[source_index] {
556                Some((strength, wait)) => (
557                    strength.max(clause.strength),
558                    merge_lock_wait(wait, clause.wait),
559                ),
560                None => (clause.strength, clause.wait),
561            });
562        }
563    }
564    let mut resolved = Vec::new();
565    for (source, assignment) in sources.iter().zip(assigned) {
566        let Some((strength, wait)) = assignment else {
567            continue;
568        };
569        reject_unusable_lock_leaf(context, source, strength)?;
570        if !source.kind.carries_row_identity() {
571            continue;
572        }
573        resolved.push(ResolvedRowLock {
574            qualifier: source.qualifier.clone(),
575            storage_name: source.storage_name.clone(),
576            display_name: source.display_name.clone(),
577            strength,
578            wait,
579            identity_source: source.kind.is_identity_source(),
580        });
581    }
582    if context.session.current_transaction_is_read_only()
583        && locks_non_temporary_relation(context, &resolved)?
584    {
585        return Err(SQLError::Routine {
586            sqlstate: "25006".into(),
587            message: "cannot execute SELECT in a read-only transaction".into(),
588        });
589    }
590    Ok(resolved)
591}
592
593fn locks_non_temporary_relation<S: Clone + Send + Sync + 'static>(
594    context: RowLockContext<'_, S>,
595    locks: &[ResolvedRowLock],
596) -> Result<bool, SQLError> {
597    for lock in locks {
598        let persistence = context
599            .catalog
600            .table_persistence(&lock.storage_name)
601            .map_err(|error| {
602                SQLError::Internal(format!(
603                    "resolve row-lock target `{}`: {error}",
604                    lock.storage_name
605                ))
606            })?;
607        if persistence != Some(RelationPersistence::Temporary) {
608            return Ok(true);
609        }
610    }
611    Ok(false)
612}
613
614fn source_contains_join_alias(source: &SourcePlan, target: &str) -> bool {
615    match source {
616        SourcePlan::Join {
617            left, right, alias, ..
618        } => {
619            alias.as_deref() == Some(target)
620                || source_contains_join_alias(left, target)
621                || source_contains_join_alias(right, target)
622        }
623        SourcePlan::Table { .. }
624        | SourcePlan::Values { .. }
625        | SourcePlan::Function { .. }
626        | SourcePlan::FunctionGroup { .. }
627        | SourcePlan::Subquery { .. } => false,
628    }
629}
630
631mod execution;
632mod null_rejection;
633mod targets;
634use null_rejection::reduce_null_rejected_outer_joins_to_fixpoint;
635use targets::lock_table_function_relations;
636
637fn merge_lock_wait(left: LockWait, right: LockWait) -> LockWait {
638    match (left, right) {
639        (LockWait::NoWait, _) | (_, LockWait::NoWait) => LockWait::NoWait,
640        (LockWait::SkipLocked, _) | (_, LockWait::SkipLocked) => LockWait::SkipLocked,
641        (LockWait::Block, LockWait::Block) => LockWait::Block,
642    }
643}
644
645pub use uqa_sql::semantics::locking::apply_propagated_view_lock;
646
647mod leaf_validation;
648use leaf_validation::{
649    collect_source_leaf_plans, collect_source_leaves, copy_recheck_source_row,
650    reject_unusable_lock_leaf, validate_locking_block_shape,
651};
652
653pub struct LockRows<'a, S: Clone> {
654    input: Box<dyn PhysicalOperator + 'a>,
655    context: RowLockContext<'a, S>,
656    params: &'a [SQLParam],
657    targets: Vec<ResolvedRowLock>,
658    max_rows: Option<u64>,
659    emitted: u64,
660    pending_rows: std::vec::IntoIter<PhysicalRow>,
661    discard_lock_origins: bool,
662    retry_cache: Option<std::sync::Arc<RowLockRetryCache>>,
663    recheck_source: Option<LockRowsRecheckSource<S>>,
664    schema: RowSchema,
665    /// 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.
666    relation_locked: std::collections::BTreeSet<std::sync::Arc<str>>,
667}
668
669impl<'a, S: Clone> LockRows<'a, S> {
670    #[expect(
671        clippy::too_many_arguments,
672        reason = "keeps execution context inputs aligned"
673    )]
674    pub fn new(
675        input: Box<dyn PhysicalOperator + 'a>,
676        context: RowLockContext<'a, S>,
677        params: &'a [SQLParam],
678        targets: Vec<ResolvedRowLock>,
679        max_rows: Option<u64>,
680        discard_lock_origins: bool,
681        retry_cache: Option<std::sync::Arc<RowLockRetryCache>>,
682        recheck_source: Option<LockRowsRecheckSource<S>>,
683    ) -> Self {
684        let schema = input.row_schema().clone();
685        Self {
686            input,
687            context,
688            params,
689            targets,
690            max_rows,
691            emitted: 0,
692            pending_rows: Vec::new().into_iter(),
693            discard_lock_origins,
694            retry_cache,
695            recheck_source,
696            schema,
697            relation_locked: std::collections::BTreeSet::new(),
698        }
699    }
700}
701
702impl<S: Clone + Send + Sync + 'static> PhysicalOperator for LockRows<'_, S> {
703    fn row_schema(&self) -> &RowSchema {
704        &self.schema
705    }
706
707    fn estimated_cardinality(&self) -> Option<u64> {
708        match (self.input.estimated_cardinality(), self.max_rows) {
709            (Some(input), Some(max_rows)) => Some(input.min(max_rows)),
710            (estimate, None) | (None, estimate) => estimate,
711        }
712    }
713
714    fn output_ordering(&self) -> &[crate::PhysicalOrder] {
715        self.input.output_ordering()
716    }
717
718    fn open(&mut self) -> ExecResult<()> {
719        self.emitted = 0;
720        self.pending_rows = Vec::new().into_iter();
721        self.input.open()
722    }
723
724    // Keep the virtual pull boundary intact under `ThinLTO`; the acquisition and recheck state machines below are deliberately separate optimized functions.
725    #[inline(never)]
726    fn next(&mut self) -> ExecResult<Option<Batch>> {
727        if self
728            .max_rows
729            .is_some_and(|max_rows| self.emitted >= max_rows)
730        {
731            return Ok(None);
732        }
733        loop {
734            self.context.cancellation.check().map_err(SQLError::from)?;
735            if let Some(row) = self.pending_rows.next() {
736                if let Some(mut row) = self.lock_physical_row(row)? {
737                    if self.discard_lock_origins {
738                        row.discard_lock_origins_mut();
739                    }
740                    self.emitted = self.emitted.saturating_add(1);
741                    // 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.
742                    return Ok(Some(Batch::from_physical_rows(
743                        self.schema.clone(),
744                        vec![row],
745                    )));
746                }
747                continue;
748            }
749            let Some(batch) = self.input.next()? else {
750                return Ok(None);
751            };
752            self.pending_rows = batch.rows.into_iter();
753        }
754    }
755
756    fn close(&mut self) -> ExecResult<()> {
757        self.input.close()
758    }
759}
760
761pub fn attach_lock_rows<'a, S: Clone + Send + Sync + 'static>(
762    context: RowLockContext<'a, S>,
763    operator: Box<dyn PhysicalOperator + 'a>,
764    statement: &QueryBlockPlan,
765    params: &'a [SQLParam],
766    ctes: &CteScope<S>,
767    max_rows: Option<u64>,
768    recheck_source: Option<LockRowsRecheckSource<S>>,
769) -> Result<Box<dyn PhysicalOperator + 'a>, SQLError> {
770    let Some(first_clause) = statement.locking.first() else {
771        return Ok(operator);
772    };
773    if ctes.row_lock_recheck_active() {
774        // 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.
775        return Ok(operator);
776    }
777    validate_locking_block_shape(statement, first_clause.strength)?;
778    let Some(from) = statement.from.as_ref() else {
779        return Ok(operator);
780    };
781    let targets = resolve_row_locks(
782        context,
783        from,
784        &statement.locking,
785        statement.r#where.as_ref(),
786        params,
787        ctes,
788    )?;
789    if targets.is_empty() {
790        return Ok(operator);
791    }
792    let mut locked_relations = std::collections::BTreeSet::new();
793    for target in targets.iter().filter(|target| !target.identity_source) {
794        if locked_relations.insert(target.storage_name.clone()) {
795            context.session.lock_relation(
796                &target.storage_name,
797                crate::row_locks::RelationLockMode::RowShare,
798            )?;
799        }
800    }
801    // 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.
802    let retry_cache = context.session.statement_row_lock_cache()?;
803    Ok(Box::new(LockRows::new(
804        operator,
805        context,
806        params,
807        targets,
808        max_rows,
809        !ctes.lock_identities.retain_after_lock,
810        Some(retry_cache),
811        recheck_source,
812    )))
813}
814
815fn validate_lock_relation_aliases(
816    from: &SourcePlan,
817    locking: &[LockingClause],
818) -> Result<(), SQLError> {
819    for clause in locking {
820        if clause
821            .relations
822            .iter()
823            .any(|relation| source_contains_join_alias(from, relation))
824        {
825            return Err(SQLError::Unsupported(format!(
826                "{} cannot be applied to a join",
827                clause.strength.sql_name()
828            )));
829        }
830    }
831    Ok(())
832}