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