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