Skip to main content

uqa_sql/expr/
context.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Evaluation context, row lookup, and engine-backed type resolution.
8
9use uqa_core::{
10    memory::{Produced, ProductionControl},
11    Value,
12};
13
14use crate::ast::{ColumnType, InternalColumnRef};
15use crate::error::{Result, SQLError};
16use crate::params::SQLParam;
17use crate::result::ResultRow;
18
19mod casting;
20mod regtype;
21pub use casting::{
22    cast_value_with_type_resolution, cast_value_with_type_resolution_with_control,
23    coercion_type_name, read_catalog_array_input, read_catalog_input, CatalogInputFunctions,
24};
25pub(crate) use casting::{requires_catalog_constant_input, requires_domain_array_input};
26pub(crate) use regtype::format_regtype_value_with_catalog_and_control;
27pub use regtype::{
28    format_regtype_elements_with_control, format_regtype_value, format_regtype_value_with_control,
29};
30
31/// Engine-side hook that scalar function evaluation calls for stateful
32/// sequence and user-defined functions. Query-valued expressions are not
33/// accepted here: lowering assigns them physical query-plan slots executed by
34/// `uqa-execution::ScalarSubqueryRunner`.
35pub trait EngineHook {
36    /// Enforce EXECUTE on a selected built-in at an execution boundary. Catalog-free embedders have no mutable routine ACLs.
37    fn require_builtin_execute(&self, _binding: &crate::ast::FunctionBinding) -> Result<()> {
38        Ok(())
39    }
40
41    /// Start of the current SQL transaction, in Unix microseconds.
42    fn transaction_timestamp_micros(&self) -> Option<i64> {
43        None
44    }
45
46    /// Start of the current frontend SQL message, in Unix microseconds.
47    fn statement_timestamp_micros(&self) -> Option<i64> {
48        None
49    }
50
51    fn nextval(&self, name: &str) -> Result<i64>;
52    fn currval(&self, name: &str) -> Result<i64>;
53    fn lastval(&self) -> Result<i64> {
54        Err(SQLError::Unsupported(
55            "lastval requires an engine hook implementation".into(),
56        ))
57    }
58    fn setval(&self, name: &str, value: i64, is_called: bool) -> Result<i64>;
59
60    fn call_scalar_function(&self, _name: &str, _args: &[Value]) -> Option<Result<Value>> {
61        None
62    }
63
64    /// Invoke an engine-backed built-in after an exact catalog binding has
65    /// selected it. Unlike `call_scalar_function`, this path is also available
66    /// when dynamic dispatch is disabled, so runtime callbacks cannot override
67    /// the stored built-in identity.
68    fn call_bound_builtin_function(
69        &self,
70        _binding: &crate::ast::FunctionBinding,
71        _args: &[(Option<String>, Value)],
72    ) -> Option<Result<Value>> {
73        None
74    }
75
76    fn has_scalar_functions(&self) -> bool {
77        true
78    }
79
80    /// Enum labels of the statement's catalog. Embedders without catalog enum types keep the default, so enum input and output fail as an unavailable type.
81    fn enum_labels(&self) -> Option<&dyn super::enums::EnumLabelCatalog> {
82        None
83    }
84
85    /// Composite type attributes of the statement's catalog. Embedders without catalog composite types keep the default, so composite input and coercion fail as an unavailable type.
86    fn composite_types(&self) -> Option<&dyn super::composites::CompositeTypeCatalog> {
87        None
88    }
89
90    /// Invoke the retained declaration's input and optional canonical support. Read-only value catalogs never execute these effects.
91    fn read_range_input(
92        &self,
93        oid: u32,
94        _text: &str,
95        _control: &ProductionControl<'_>,
96    ) -> Result<Produced<Value>> {
97        Err(SQLError::Internal(format!(
98            "cache lookup failed for range type {oid}"
99        )))
100    }
101
102    /// Resolve a catalog-owned SQL type name for casts evaluated with an engine context.
103    fn resolve_type_name(&self, _name: &str) -> std::result::Result<Option<ColumnType>, String> {
104        Ok(None)
105    }
106
107    /// Resolve an already admitted catalog type identity without name lookup or input privileges.
108    fn resolve_type_oid(&self, _oid: u32) -> std::result::Result<Option<ColumnType>, String> {
109        Ok(None)
110    }
111
112    /// Observe whether a physical type OID remains in the current catalog, including types without a scalar value carrier.
113    fn type_oid_exists(&self, oid: u32) -> std::result::Result<bool, String> {
114        self.resolve_type_oid(oid).map(|ty| ty.is_some())
115    }
116
117    /// Apply catalog-owned domain conversion and constraints. A missing implementation leaves built-in catalog domains on their base-type conversion path.
118    fn cast_domain(
119        &self,
120        _value: &Value,
121        _source: Option<&str>,
122        _target: &ColumnType,
123    ) -> Result<Option<Value>> {
124        Ok(None)
125    }
126
127    /// Resolve a regtype cast to its OID carrier when a complete type catalog is available.
128    fn resolve_regtype_input(&self, _name: &str) -> Result<Option<i64>> {
129        Ok(None)
130    }
131
132    /// Resolve a relation name to the OID carrier used by `regclass`.
133    fn resolve_regclass(&self, _name: &str) -> std::result::Result<Option<i64>, String> {
134        Ok(None)
135    }
136
137    /// Resolve `regclass` input while preserving typed SQL errors. Embedders that implement the historical string-error hook retain its previous behavior; engines with catalog privilege checks override this method directly.
138    fn resolve_regclass_input(&self, name: &str) -> Result<Option<i64>> {
139        self.resolve_regclass(name).map_err(SQLError::Internal)
140    }
141
142    /// Resolve a routine name that must name exactly one routine, as `regproc` input does.
143    fn resolve_regproc(&self, _name: &str) -> Result<Option<i64>> {
144        Ok(None)
145    }
146
147    /// Resolve an exact routine signature to the OID carrier used by `regprocedure`.
148    fn resolve_regprocedure(&self, _name: &str) -> std::result::Result<Option<i64>, String> {
149        Ok(None)
150    }
151
152    /// Resolve `regprocedure` input while preserving the typed errors `regprocedurein` reports. Embedders that implement only the historical lookup hook keep its behavior.
153    fn resolve_regprocedure_input(&self, name: &str) -> Result<Option<i64>> {
154        self.resolve_regprocedure(name).map_err(SQLError::Internal)
155    }
156
157    /// Resolve a `regrole` input while preserving hard input errors for direct casts.
158    fn resolve_regrole(&self, _name: &str) -> Result<Option<i64>> {
159        Ok(None)
160    }
161
162    /// Resolve a `regnamespace` input while preserving hard input errors for direct casts.
163    fn resolve_regnamespace(&self, name: &str) -> Result<Option<i64>> {
164        self.resolve_regobject(&ColumnType::Regnamespace, name)
165    }
166
167    /// Resolve `regcollation` input with the direct input function's diagnostics.
168    fn resolve_regcollation(&self, name: &str) -> Result<Option<i64>> {
169        self.resolve_regobject(&ColumnType::Regcollation, name)
170    }
171
172    /// Resolve the text argument of one `PostgreSQL` `to_reg*` lookup function. The engine override owns catalog visibility and the lookup function's NULL-versus-error boundary; the default preserves the two historical hooks for embedders that only implement `regclass` or `regprocedure`.
173    fn resolve_regobject(&self, ty: &ColumnType, name: &str) -> Result<Option<i64>> {
174        match ty {
175            ColumnType::Regclass => self.resolve_regclass_input(name),
176            ColumnType::Regprocedure => self.resolve_regprocedure(name).map_err(SQLError::Internal),
177            ColumnType::Regrole => self.resolve_regrole(name),
178            ColumnType::Regproc
179            | ColumnType::Regcollation
180            | ColumnType::Regnamespace
181            | ColumnType::Regtype => Ok(None),
182            _ => Err(SQLError::Internal(format!(
183                "unsupported regobject lookup type `{}`",
184                ty.sql_name()
185            ))),
186        }
187    }
188
189    /// Resolve one OID-backed alias type to its `PostgreSQL` text output.
190    fn resolve_regtype_output(
191        &self,
192        _ty: &ColumnType,
193        _oid: i64,
194    ) -> std::result::Result<Option<String>, String> {
195        Ok(None)
196    }
197
198    /// The first schema of the session's search path that exists and that the role may use, or `None` when there is none, which `current_schema()` reports as NULL. A hook without a session reports `public`, the first schema of the default search path.
199    fn current_schema(&self) -> std::result::Result<Option<String>, String> {
200        Ok(Some("public".into()))
201    }
202
203    fn current_user(&self) -> std::result::Result<Option<String>, crate::SQLError> {
204        Ok(None)
205    }
206
207    fn session_user(&self) -> std::result::Result<Option<String>, crate::SQLError> {
208        Ok(None)
209    }
210
211    /// Read a session setting. `None` means the parameter is unknown; errors must remain visible even for `current_setting(..., true)`.
212    fn runtime_parameter(&self, _name: &str) -> Result<Option<String>> {
213        Err(SQLError::Unsupported(
214            "engine hook does not provide session settings".into(),
215        ))
216    }
217
218    /// The live interval input/output convention. A catalog-only hook leaves the calling statement's captured style in force.
219    fn temporal_interval_style(&self) -> Result<Option<uqa_core::TemporalIntervalStyle>> {
220        Ok(None)
221    }
222
223    /// The validated zone of a live session. Detached value evaluation uses UTC.
224    fn temporal_time_zone(&self) -> Result<Option<uqa_core::TemporalTimeZone>> {
225        Ok(None)
226    }
227
228    /// Sleep in the session for `duration`, ending at once when the statement is canceled or times out (`pg_sleep`).
229    fn sleep(&self, _duration: std::time::Duration) -> Result<()> {
230        Err(SQLError::Unsupported(
231            "engine hook does not provide session sleeps".into(),
232        ))
233    }
234
235    /// Assign a session setting as `set_config(name, value, is_local)` does, restoring the reset setting for `None`, and return the new value as `SHOW` reports it.
236    fn set_runtime_parameter(
237        &self,
238        _name: &str,
239        _value: Option<&str>,
240        _local: bool,
241    ) -> Result<String> {
242        Err(SQLError::Unsupported(
243            "engine hook does not provide session settings".into(),
244        ))
245    }
246
247    /// Resolve the existing schemas visible to the logical session.
248    fn current_schemas(
249        &self,
250        _include_implicit: bool,
251    ) -> std::result::Result<Option<Vec<String>>, String> {
252        Ok(None)
253    }
254
255    /// Draw from an engine-owned logical-session PRNG. `None` keeps pure,
256    /// engine-free expression evaluation available for library callers.
257    fn random_value(&self) -> std::result::Result<Option<f64>, String> {
258        Ok(None)
259    }
260
261    /// Draw every bit of one engine-owned logical-session PRNG word. Range
262    /// functions use this instead of a floating-point sample so `bigint` and
263    /// arbitrary-precision `numeric` bounds remain uniform.
264    fn random_u64(&self) -> std::result::Result<Option<u64>, String> {
265        Ok(None)
266    }
267
268    /// Reseed the logical-session PRNG. `false` means the hook does not own a
269    /// mutable random stream and the caller must report the unsupported call.
270    fn set_random_seed(&self, _seed: f64) -> std::result::Result<bool, String> {
271        Ok(false)
272    }
273
274    /// Invoke a user-defined SQL / `PL/pgSQL` function. Consulted
275    /// after built-in dispatch misses (and immediately for calls with
276    /// named arguments, which built-ins never accept). `None` means
277    /// no user-defined function with this name exists.
278    fn call_user_function(
279        &self,
280        _name: &str,
281        _args: &[(Option<String>, Value)],
282    ) -> Option<Result<Value>> {
283        None
284    }
285
286    fn call_bound_user_function(
287        &self,
288        _binding: &crate::ast::FunctionBinding,
289        _args: &[(Option<String>, Value)],
290    ) -> Option<Result<Value>> {
291        None
292    }
293}
294
295/// Read-only row interface used by the expression evaluator. Most callers
296/// use a materialised [`ResultRow`], while hot execution paths can expose a
297/// projected value slice without rebuilding a string-keyed map for every row.
298pub trait RowLookup {
299    fn column(&self, name: &str) -> Option<&Value>;
300
301    /// Whether an unqualified name identifies more than one visible input
302    /// column. Callers must report SQLSTATE 42702 instead of selecting an
303    /// arbitrary suffix match.
304    fn column_is_ambiguous(&self, _name: &str) -> bool {
305        false
306    }
307
308    fn qualified_column(&self, qualifier: &str, column: &str) -> Option<&Value>;
309
310    /// Whether a qualified identity names more than one visible input column.
311    fn qualified_column_is_ambiguous(&self, _qualifier: &str, _column: &str) -> bool {
312        false
313    }
314
315    /// Return a value by the physical schema position used to construct this
316    /// row view. Materialized named rows do not expose positional access;
317    /// projected execution sources override it so compiled hot paths can avoid
318    /// repeating string lookup for every expression and row.
319    fn positional_column(&self, _index: usize) -> Option<&Value> {
320        None
321    }
322
323    /// Resolve an executor-only relation attribute. Materialized SQL rows do
324    /// not expose these structural slots.
325    fn internal_column(&self, _column: InternalColumnRef) -> Option<&Value> {
326        None
327    }
328
329    /// Read the structurally carried retrieval score for one relation. The qualifier selects a score-bearing source without exposing an executor field in the SQL column namespace.
330    fn score_source(&self, _qualifier: Option<&str>) -> Option<&Value> {
331        None
332    }
333
334    /// Whether the requested score source resolves to more than one retrieval relation.
335    fn score_source_is_ambiguous(&self, _qualifier: Option<&str>) -> bool {
336        false
337    }
338
339    /// Visit every logical column in schema order. Named rows use their map
340    /// order; positional execution rows override this without materializing a
341    /// map. The default keeps narrow projected lookup implementations source
342    /// compatible when they deliberately do not expose whole-row semantics.
343    fn visit_columns(&self, _visitor: &mut dyn FnMut(&str, &Value)) {}
344}
345
346impl RowLookup for ResultRow {
347    fn column(&self, name: &str) -> Option<&Value> {
348        self.get(name)
349    }
350
351    fn qualified_column(&self, _qualifier: &str, _column: &str) -> Option<&Value> {
352        None
353    }
354
355    fn visit_columns(&self, visitor: &mut dyn FnMut(&str, &Value)) {
356        for (column, value) in self {
357            visitor(column, value);
358        }
359    }
360}
361
362pub struct EvalContext<'a> {
363    pub row: Option<&'a ResultRow>,
364    row_lookup: Option<&'a dyn RowLookup>,
365    pub params: &'a [SQLParam],
366    pub engine: Option<&'a dyn EngineHook>,
367    enum_comparison_states: [Option<&'a super::enums::EnumComparisonState>; 4],
368}
369
370impl<'a> EvalContext<'a> {
371    pub fn new(row: Option<&'a ResultRow>, params: &'a [SQLParam]) -> Self {
372        Self {
373            row,
374            row_lookup: row.map(|row| row as &dyn RowLookup),
375            params,
376            engine: None,
377            enum_comparison_states: [None; 4],
378        }
379    }
380
381    pub fn from_row_lookup(row: &'a dyn RowLookup, params: &'a [SQLParam]) -> Self {
382        Self {
383            // Whole-row materialization is needed only by correlated
384            // subqueries. Ordinary scalar evaluation must remain on the
385            // lookup/slot path.
386            row: None,
387            row_lookup: Some(row),
388            params,
389            engine: None,
390            enum_comparison_states: [None; 4],
391        }
392    }
393
394    pub fn with_engine(mut self, engine: &'a dyn EngineHook) -> Self {
395        self.engine = Some(engine);
396        self
397    }
398
399    /// The state of the current bound enum call, supplied by its prepared execution owner.
400    pub fn with_enum_comparison_state(
401        mut self,
402        state: Option<&'a super::enums::EnumComparisonState>,
403    ) -> Self {
404        self.enum_comparison_states[0] = state;
405        self
406    }
407
408    /// Independent comparisons within one prepared expression, including the
409    /// four operators of BETWEEN SYMMETRIC, retain separate type caches.
410    pub fn with_enum_comparison_states(
411        mut self,
412        states: [Option<&'a super::enums::EnumComparisonState>; 4],
413    ) -> Self {
414        self.enum_comparison_states = states;
415        self
416    }
417
418    pub(super) fn enum_comparison_state(&self) -> Option<&super::enums::EnumComparisonState> {
419        self.enum_comparison_states[0]
420    }
421
422    pub(super) fn enum_comparison_state_at(
423        &self,
424        slot: usize,
425    ) -> Option<&super::enums::EnumComparisonState> {
426        self.enum_comparison_states[slot]
427    }
428
429    pub(super) fn row_lookup(&self) -> Result<&'a dyn RowLookup> {
430        self.row_lookup
431            .ok_or_else(|| SQLError::Internal("column reference without row context".into()))
432    }
433
434    /// Resolve an unqualified column through the same row semantics used by
435    /// the AST evaluator. Physical scalar IR evaluators call this instead of
436    /// reconstructing an [`Expr::Column`](crate::ast::Expr::Column) carrier.
437    pub fn column_value(&self, name: &str) -> Result<Value> {
438        self.column_value_with_control(name, &ProductionControl::uncontrolled())
439            .map(|value| value.into_uncontrolled().expect("ordinary column value"))
440    }
441
442    /// Resolve the same row slot while its copied payload retains the caller's allowance and cancellation scopes.
443    pub fn column_value_with_control(
444        &self,
445        name: &str,
446        control: &ProductionControl<'_>,
447    ) -> Result<Produced<Value>> {
448        control.check()?;
449        let row = self.row_lookup()?;
450        if row.column_is_ambiguous(name) {
451            return Err(SQLError::AmbiguousColumn(name.to_string()));
452        }
453        Ok(control.copy_value(row.column(name).unwrap_or(&Value::Null))?)
454    }
455
456    /// Resolve a qualified column without constructing an AST expression.
457    pub fn qualified_column_value(&self, qualifier: &str, column: &str) -> Result<Value> {
458        self.qualified_column_value_with_control(
459            qualifier,
460            column,
461            &ProductionControl::uncontrolled(),
462        )
463        .map(|value| {
464            value
465                .into_uncontrolled()
466                .expect("ordinary qualified column value")
467        })
468    }
469
470    /// Resolve a qualified slot with the same ambiguity and missing-value behavior under a retained output owner.
471    pub fn qualified_column_value_with_control(
472        &self,
473        qualifier: &str,
474        column: &str,
475        control: &ProductionControl<'_>,
476    ) -> Result<Produced<Value>> {
477        control.check()?;
478        let row = self.row_lookup()?;
479        if row.qualified_column_is_ambiguous(qualifier, column) {
480            return Err(SQLError::AmbiguousColumn(format!("{qualifier}.{column}")));
481        }
482        Ok(control.copy_value(
483            row.qualified_column(qualifier, column)
484                .unwrap_or(&Value::Null),
485        )?)
486    }
487}
488
489#[cfg(test)]
490mod production_tests;