Skip to main content

uqa_execution/operator_tree/
binding.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Scalar evaluation and physical retrieval construction at the execution boundary.
8
9use super::instantiate::instantiate;
10use crate::{eval_scalar, ScalarEvalContext};
11use uqa_core::Value;
12use uqa_operators::OperatorTree;
13use uqa_sql::{
14    ast::OperatorJoinRelations,
15    expr::EngineHook,
16    retrieval::{self, RetrievalArguments, RetrievalConstants},
17    semantics::graph_functions::GraphNameCatalog,
18    SQLError, SQLParam, ScalarExpr,
19};
20
21fn evaluate_constant(expression: &ScalarExpr, params: &[SQLParam]) -> Result<Value, SQLError> {
22    eval_scalar(expression, &ScalarEvalContext::new(None, params))
23}
24
25/// A predicate lowered without its relation stores no engine pseudo column.
26fn stores_nothing(_: &str) -> bool {
27    false
28}
29
30pub(super) fn has_column_null_test(expression: &ScalarExpr) -> bool {
31    let mut found = false;
32    expression.visit(&mut |expression| {
33        found |= matches!(expression, ScalarExpr::IsNull { expr, .. }
34            if matches!(&**expr, ScalarExpr::Column(_) | ScalarExpr::QualifiedColumn { .. }));
35    });
36    found
37}
38
39fn requires_catalog_null_test(
40    columns: &[uqa_sql::ast::ColumnDef],
41    expression: &ScalarExpr,
42) -> bool {
43    let mut required = false;
44    expression.visit(&mut |expression| {
45        let ScalarExpr::IsNull { expr, .. } = expression else {
46            return;
47        };
48        let (ScalarExpr::Column(name) | ScalarExpr::QualifiedColumn { column: name, .. }) = &**expr
49        else {
50            return;
51        };
52        if let Some(column) = columns.iter().find(|column| column.name == *name) {
53            let mut ty = &column.ty;
54            while let uqa_sql::ColumnType::Domain { base, .. } = ty {
55                ty = base;
56            }
57            required |= matches!(
58                ty,
59                uqa_sql::ColumnType::Composite(_) | uqa_sql::ColumnType::Record
60            );
61        }
62    });
63    required
64}
65
66/// Preserve the public syntax-lowering API while constructing its physical models in execution.
67pub fn lower_where(expression: &ScalarExpr, params: &[SQLParam]) -> Option<OperatorTree> {
68    retrieval::lower_where(
69        expression,
70        &RetrievalConstants {
71            params,
72            evaluate: &evaluate_constant,
73            stores: &stores_nothing,
74        },
75    )
76    .and_then(|logical| instantiate(logical).ok())
77}
78
79pub struct RetrievalBinding<'a> {
80    pub hook: &'a dyn EngineHook,
81    pub graphs: &'a dyn GraphNameCatalog,
82}
83impl GraphNameCatalog for RetrievalBinding<'_> {
84    fn list_graphs(&self) -> Result<Vec<String>, SQLError> {
85        self.graphs.list_graphs()
86    }
87}
88impl RetrievalArguments for RetrievalBinding<'_> {
89    fn evaluate_argument(
90        &self,
91        expression: &ScalarExpr,
92        params: &[SQLParam],
93    ) -> Result<Value, SQLError> {
94        eval_scalar(
95            expression,
96            &ScalarEvalContext::new(None, params).with_function_hook(self.hook),
97        )
98    }
99}
100impl RetrievalBinding<'_> {
101    pub fn lower_where(
102        &self,
103        expression: &ScalarExpr,
104        params: &[SQLParam],
105    ) -> Result<Option<OperatorTree>, SQLError> {
106        self.lower_relation_where(&[], expression, params)
107    }
108
109    /// Lower a predicate on the relation that declares `columns`. A predicate on an engine pseudo column such as `_doc_id` filters the stored column of that name where the relation declares one, and otherwise stays relational.
110    pub fn lower_relation_where(
111        &self,
112        columns: &[uqa_sql::ast::ColumnDef],
113        expression: &ScalarExpr,
114        params: &[SQLParam],
115    ) -> Result<Option<OperatorTree>, SQLError> {
116        // Scalar null postings cannot answer a composite's current live-field null test. Preserve that operation for SQL's catalog-aware row evaluator.
117        if requires_catalog_null_test(columns, expression) {
118            return Ok(None);
119        }
120        let stores = |column: &str| columns.iter().any(|definition| definition.name == column);
121        retrieval::lower_where_bound(
122            self,
123            expression,
124            &RetrievalConstants {
125                params,
126                evaluate: &evaluate_constant,
127                stores: &stores,
128            },
129        )?
130        .map(instantiate)
131        .transpose()
132    }
133    pub fn lower_function(
134        &self,
135        name: &str,
136        args: &[ScalarExpr],
137        params: &[SQLParam],
138    ) -> Result<OperatorTree, SQLError> {
139        instantiate(retrieval::lower_sql_function_bound(
140            self,
141            name,
142            args,
143            &RetrievalConstants {
144                params,
145                evaluate: &evaluate_constant,
146                stores: &stores_nothing,
147            },
148        )?)
149    }
150    pub fn lower_join(
151        &self,
152        name: &str,
153        relations: Option<&OperatorJoinRelations>,
154        args: &[ScalarExpr],
155        params: &[SQLParam],
156    ) -> Result<(OperatorJoinRelations, OperatorTree), SQLError> {
157        let (relations, logical) = retrieval::lower_operator_join_table_function(
158            self,
159            name,
160            relations,
161            args,
162            &RetrievalConstants {
163                params,
164                evaluate: &evaluate_constant,
165                stores: &stores_nothing,
166            },
167        )?;
168        Ok((relations, instantiate(logical)?))
169    }
170}
171
172impl RetrievalBinding<'_> {
173    /// Describe a predicate that owns one bounded vector candidate pool across a relation hierarchy.
174    pub fn direct_vector_retrieval(
175        &self,
176        expression: &ScalarExpr,
177        params: &[SQLParam],
178    ) -> Result<Option<crate::query::table_sources::retrieval::DirectVectorRetrieval>, SQLError>
179    {
180        use crate::query::table_sources::retrieval::DirectVectorRetrieval;
181        let Some(tree) = self.lower_where(expression, params)? else {
182            return Ok(None);
183        };
184        Ok(match tree {
185            OperatorTree::KNN { k, .. } => Some(DirectVectorRetrieval::Knn { top_k: k }),
186            OperatorTree::CalibratedVectorMatch {
187                field,
188                query_vector,
189                k,
190                threshold,
191            } => Some(DirectVectorRetrieval::Calibrated {
192                field,
193                query_vector,
194                top_k: k,
195                threshold,
196            }),
197            _ => None,
198        })
199    }
200}
201
202#[cfg(test)]
203mod tests;