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
30/// Preserve the public syntax-lowering API while constructing its physical models in execution.
31pub fn lower_where(expression: &ScalarExpr, params: &[SQLParam]) -> Option<OperatorTree> {
32    retrieval::lower_where(
33        expression,
34        &RetrievalConstants {
35            params,
36            evaluate: &evaluate_constant,
37            stores: &stores_nothing,
38        },
39    )
40    .and_then(|logical| instantiate(logical).ok())
41}
42
43pub struct RetrievalBinding<'a> {
44    pub hook: &'a dyn EngineHook,
45    pub graphs: &'a dyn GraphNameCatalog,
46}
47impl GraphNameCatalog for RetrievalBinding<'_> {
48    fn list_graphs(&self) -> Result<Vec<String>, SQLError> {
49        self.graphs.list_graphs()
50    }
51}
52impl RetrievalArguments for RetrievalBinding<'_> {
53    fn evaluate_argument(
54        &self,
55        expression: &ScalarExpr,
56        params: &[SQLParam],
57    ) -> Result<Value, SQLError> {
58        eval_scalar(
59            expression,
60            &ScalarEvalContext::new(None, params).with_function_hook(self.hook),
61        )
62    }
63}
64impl RetrievalBinding<'_> {
65    pub fn lower_where(
66        &self,
67        expression: &ScalarExpr,
68        params: &[SQLParam],
69    ) -> Result<Option<OperatorTree>, SQLError> {
70        self.lower_relation_where(&[], expression, params)
71    }
72
73    /// 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.
74    pub fn lower_relation_where(
75        &self,
76        columns: &[uqa_sql::ast::ColumnDef],
77        expression: &ScalarExpr,
78        params: &[SQLParam],
79    ) -> Result<Option<OperatorTree>, SQLError> {
80        let stores = |column: &str| columns.iter().any(|definition| definition.name == column);
81        retrieval::lower_where_bound(
82            self,
83            expression,
84            &RetrievalConstants {
85                params,
86                evaluate: &evaluate_constant,
87                stores: &stores,
88            },
89        )?
90        .map(instantiate)
91        .transpose()
92    }
93    pub fn lower_function(
94        &self,
95        name: &str,
96        args: &[ScalarExpr],
97        params: &[SQLParam],
98    ) -> Result<OperatorTree, SQLError> {
99        instantiate(retrieval::lower_sql_function_bound(
100            self,
101            name,
102            args,
103            &RetrievalConstants {
104                params,
105                evaluate: &evaluate_constant,
106                stores: &stores_nothing,
107            },
108        )?)
109    }
110    pub fn lower_join(
111        &self,
112        name: &str,
113        relations: Option<&OperatorJoinRelations>,
114        args: &[ScalarExpr],
115        params: &[SQLParam],
116    ) -> Result<(OperatorJoinRelations, OperatorTree), SQLError> {
117        let (relations, logical) = retrieval::lower_operator_join_table_function(
118            self,
119            name,
120            relations,
121            args,
122            &RetrievalConstants {
123                params,
124                evaluate: &evaluate_constant,
125                stores: &stores_nothing,
126            },
127        )?;
128        Ok((relations, instantiate(logical)?))
129    }
130}
131
132impl RetrievalBinding<'_> {
133    /// Describe a predicate that owns one bounded vector candidate pool across a relation hierarchy.
134    pub fn direct_vector_retrieval(
135        &self,
136        expression: &ScalarExpr,
137        params: &[SQLParam],
138    ) -> Result<Option<crate::query::table_sources::retrieval::DirectVectorRetrieval>, SQLError>
139    {
140        use crate::query::table_sources::retrieval::DirectVectorRetrieval;
141        let Some(tree) = self.lower_where(expression, params)? else {
142            return Ok(None);
143        };
144        Ok(match tree {
145            OperatorTree::KNN { k, .. } => Some(DirectVectorRetrieval::Knn { top_k: k }),
146            OperatorTree::CalibratedVectorMatch {
147                field,
148                query_vector,
149                k,
150                threshold,
151            } => Some(DirectVectorRetrieval::Calibrated {
152                field,
153                query_vector,
154                top_k: k,
155                threshold,
156            }),
157            _ => None,
158        })
159    }
160}
161
162#[cfg(test)]
163mod tests;