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