Skip to main content

uqa_execution/query/relational/
context.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Physical relational assembly with independent expression and lock construction services.
8
9use crate::query::recheck_source::LockRowsRecheckInput;
10use crate::query::runtime::QueryRuntimeView;
11use crate::query::set_projection::{SetFunctionRuntime, SetProjectionOutput};
12use crate::query::CteScope;
13use crate::{PhysicalOperator, ScalarExpr, SharedExpressionEvaluator, SharedRowPredicate};
14use std::sync::Arc;
15use uqa_sql::{plan::QueryBlockPlan, semantics::sets::SetFunctionCatalog, SQLError, SQLParam};
16
17/// Bind scoped expression services without exposing the owning session or storage state.
18pub trait QueryExpressionFactory<S: Clone + 'static>: Sync {
19    fn production_resources(&self) -> Result<uqa_core::memory::OwnedProductionControl, SQLError>;
20    fn bind_scope(&self, scope: &CteScope<S>)
21        -> Result<Arc<dyn SetFunctionRuntime + '_>, SQLError>;
22    /// Apply the owning planner to a validated schema/procedural execution copy.
23    fn optimize_catalog_scalar(&self, expression: &mut ScalarExpr) -> Result<(), SQLError>;
24    fn optimize_owned_catalog_scalar(
25        &self,
26        expression: uqa_sql::plan::OwnedScalarExpr,
27        control: &uqa_core::memory::ProductionControl<'_>,
28    ) -> Result<uqa_sql::plan::OwnedScalarExpr, SQLError>;
29    fn prepare_predicate<'a>(
30        &'a self,
31        expression: &ScalarExpr,
32        params: &'a [SQLParam],
33        scope: &CteScope<S>,
34    ) -> Result<Option<SharedRowPredicate<'a>>, SQLError>;
35}
36
37/// Attach the locking boundary using the caller's relation and transaction lock services.
38pub trait RowLockOperatorFactory<S: Clone + 'static>: Sync {
39    /// Accept ownership of the input, including closing it before returning a
40    /// construction error. Successful construction transfers it to the result.
41    fn attach_lock_rows<'a>(
42        &'a self,
43        operator: Box<dyn PhysicalOperator + 'a>,
44        statement: &QueryBlockPlan,
45        params: &'a [SQLParam],
46        scope: &CteScope<S>,
47        max_rows: Option<u64>,
48        recheck: Option<LockRowsRecheckInput<'_, S>>,
49    ) -> Result<Box<dyn PhysicalOperator + 'a>, SQLError>;
50}
51
52#[derive(Clone)]
53pub struct RelationalContext<'a, S: Clone + 'static> {
54    pub catalog: &'a dyn SetFunctionCatalog,
55    pub expressions: &'a dyn QueryExpressionFactory<S>,
56    pub row_locks: &'a dyn RowLockOperatorFactory<S>,
57    pub runtime: QueryRuntimeView<'a>,
58}
59
60impl<S: Clone + 'static> Copy for RelationalContext<'_, S> {}
61
62impl<'a, S: Clone + 'static> RelationalContext<'a, S> {
63    pub fn expression_scope(
64        self,
65        scope: &CteScope<S>,
66    ) -> Result<Arc<dyn SetFunctionRuntime + 'a>, SQLError> {
67        self.expressions.bind_scope(scope)
68    }
69
70    pub fn evaluator(
71        self,
72        params: &'a [SQLParam],
73        scope: &CteScope<S>,
74    ) -> Result<SharedExpressionEvaluator<'a>, SQLError> {
75        let resources = self.expressions.production_resources()?;
76        crate::query::expression::ScopedExpressionEvaluator::shared_with_control(
77            self.expression_scope(scope)?,
78            params,
79            self.runtime.cancellation_token(),
80            &resources.control(),
81        )
82    }
83}
84
85pub fn build_set_projection<'a, S: Clone + 'static>(
86    operator: Box<dyn PhysicalOperator + 'a>,
87    context: RelationalContext<'a, S>,
88    params: &'a [SQLParam],
89    ctes: &CteScope<S>,
90    evaluator: SharedExpressionEvaluator<'a>,
91    output: SetProjectionOutput,
92) -> Result<Box<dyn PhysicalOperator + 'a>, SQLError> {
93    let (operator, (work_mem, scope)) =
94        crate::physical::construction::OperatorBuild::run(operator, |_| {
95            Ok((
96                context.runtime.work_mem_bytes()?,
97                context.expression_scope(ctes)?,
98            ))
99        })?;
100    crate::query::set_projection::build_set_projection(
101        operator,
102        context.catalog,
103        scope,
104        params,
105        evaluator,
106        work_mem,
107        output,
108    )
109}
110
111pub fn attach_lock_rows<'a, S: Clone + 'static>(
112    context: RelationalContext<'a, S>,
113    operator: Box<dyn PhysicalOperator + 'a>,
114    statement: &QueryBlockPlan,
115    params: &'a [SQLParam],
116    ctes: &CteScope<S>,
117    max_rows: Option<u64>,
118    recheck: Option<LockRowsRecheckInput<'_, S>>,
119) -> Result<Box<dyn PhysicalOperator + 'a>, SQLError> {
120    context
121        .row_locks
122        .attach_lock_rows(operator, statement, params, ctes, max_rows, recheck)
123}