Skip to main content

uqa_engine/
operator_tree_bridge.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Public Engine retrieval entry points and statement-boundary composition.
8//!
9//! SQL binds predicates and retrieval calls into its runtime-independent retrieval algebra.
10//! Execution evaluates scalar arguments and instantiates physical models. The public
11//! [`lower_where`] re-export and [`EngineDriver`] preserve existing Rust entry points.
12//! The driver enters the active statement and transaction before physical execution.
13
14use uqa_execution::operator_tree::{OperatorOutput, OperatorTreeDriver};
15use uqa_execution::parallel::ParallelExecutor;
16use uqa_execution::ScalarExpr;
17use uqa_operators::OperatorTree;
18use uqa_planner::retrieval_planning::{
19    estimate_cross_relation_operator_join, estimate_operator_tree_access, query_optimizer,
20};
21use uqa_sql::ast::OperatorJoinRelations;
22use uqa_sql::SQLParam;
23
24use crate::{Engine, ScoredEntry};
25use uqa_sql::SQLError;
26
27pub use uqa_execution::operator_tree::binding::lower_where;
28
29type DriverResult<T> = Result<T, SQLError>;
30
31fn operator_execution_error(operator: &str, error: impl std::fmt::Display) -> SQLError {
32    SQLError::Internal(format!("execute {operator}: {error}"))
33}
34
35/// Bind a physical retrieval driver to the Engine statement and transaction boundary.
36pub struct EngineDriver<'a> {
37    pub engine: &'a Engine,
38    pub table: &'a str,
39    pub params: &'a [SQLParam],
40    pub parallel: ParallelExecutor,
41}
42
43impl<'a> EngineDriver<'a> {
44    #[must_use]
45    pub fn new(engine: &'a Engine, table: &'a str, params: &'a [SQLParam]) -> Self {
46        Self {
47            engine,
48            table,
49            params,
50            parallel: ParallelExecutor::default(),
51        }
52    }
53    #[must_use]
54    pub fn with_parallel(mut self, parallel: ParallelExecutor) -> Self {
55        self.parallel = parallel;
56        self
57    }
58}
59
60impl OperatorTreeDriver for EngineDriver<'_> {
61    type Error = SQLError;
62    fn execute_node(&self, tree: &OperatorTree) -> DriverResult<OperatorOutput> {
63        execution::execute_public_physical_node(self, tree)
64    }
65}
66
67/// Lower a WHERE expression and run [`uqa_planner::query_optimizer::QueryOptimizer`] over the
68/// resulting tree without executing it. Useful for tests and
69/// `EXPLAIN`-style diagnostics that want to inspect the rewritten
70/// shape before any posting list is materialised.
71pub fn optimised_tree_for(
72    engine: &Engine,
73    table: &str,
74    where_expr: &ScalarExpr,
75    params: &[SQLParam],
76) -> DriverResult<Option<OperatorTree>> {
77    engine.with_direct_query_snapshot(
78        false,
79        |engine| {
80            let Some(tree) = lower_relation_where(engine, table, where_expr, params)? else {
81                return Ok(None);
82            };
83            Ok(Some(query_optimizer(engine, table, &tree)?.optimize(tree)))
84        },
85        std::convert::identity,
86    )
87}
88
89/// Cost a relation-local SQL predicate through the same lowering and
90/// optimizer configuration used by execution.
91pub(crate) fn estimate_local_access(
92    engine: &Engine,
93    table: &str,
94    where_expr: &ScalarExpr,
95    params: &[SQLParam],
96) -> DriverResult<Option<uqa_planner::LocalAccessEstimate>> {
97    let Some(tree) = lower_relation_where(engine, table, where_expr, params)? else {
98        return Ok(None);
99    };
100    estimate_operator_tree_access(engine, table, tree, true).map(Some)
101}
102
103/// Lower `where_expr` on `table` as execution does: the table's declared columns decide how a predicate on an engine pseudo column lowers, and are read only for an expression that names one.
104fn lower_relation_where(
105    engine: &Engine,
106    table: &str,
107    where_expr: &ScalarExpr,
108    params: &[SQLParam],
109) -> DriverResult<Option<OperatorTree>> {
110    let columns = if uqa_sql::retrieval::names_engine_pseudo_column(where_expr) {
111        engine
112            .try_describe_query_table(table)
113            .map_err(|error| {
114                SQLError::Internal(format!("resolve retrieval table `{table}`: {error}"))
115            })?
116            .unwrap_or_default()
117    } else {
118        Vec::new()
119    };
120    engine
121        .retrieval_binding()
122        .lower_relation_where(&columns, where_expr, params)
123}
124
125mod execution;
126pub(crate) use execution::execute_scored_tree;
127pub use execution::run_optimised;
128
129use uqa_execution::operator_tree::driver::posting::posting_list_to_scored;
130
131pub(crate) fn estimate_operator_join_table_function(
132    engine: &Engine,
133    name: &str,
134    relations: Option<&OperatorJoinRelations>,
135    args: &[ScalarExpr],
136    params: &[SQLParam],
137) -> DriverResult<uqa_planner::LocalAccessEstimate> {
138    let (relations, tree) = engine
139        .retrieval_binding()
140        .lower_join(name, relations, args, params)?;
141    estimate_cross_relation_operator_join(engine, &relations, tree)
142}