Skip to main content

uqa_sql/expr/
enums.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Enum label input and output, ordered label functions and I/O casts through the statement's catalog.
8//!
9//! Values carry an immutable label key; the catalog supplies the current label text, so
10//! `ALTER TYPE ... RENAME VALUE` never rewrites stored values. Native comparisons use key order;
11//! physical enum support functions observe raw OIDs and consult catalog order only when needed.
12
13use std::sync::Arc;
14
15use uqa_core::memory::{Produced, ProductionControl, ProductionVec};
16use uqa_core::{ArrayValue, EnumLabelKey, EnumValue, Value};
17
18use super::{Result, SQLError};
19use crate::ast::ColumnType;
20
21mod functions;
22mod output;
23mod physical;
24pub(crate) use output::label_text_with_control as enum_label_text_with_control;
25pub(crate) use output::render_with_control as render_enum_labels_with_control;
26#[cfg(test)]
27mod tests;
28pub use functions::{
29    enum_function_value, enum_function_value_with_control, enum_function_value_with_state,
30};
31pub(in crate::expr) use physical::comparison_order;
32pub use physical::{
33    comparison_identity, eval_comparison, EnumComparisonState, EnumTypeComparisonStates,
34};
35
36/// One label of an enum type.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct EnumTypeLabel {
39    pub oid: u32,
40    pub key: EnumLabelKey,
41    pub label: String,
42}
43
44/// The labels of one enum type in ascending key order, which is declaration order.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct EnumTypeLabels {
47    pub type_oid: u32,
48    pub labels: Vec<EnumTypeLabel>,
49}
50
51impl EnumTypeLabels {
52    pub fn by_key(&self, key: &EnumLabelKey) -> Option<&EnumTypeLabel> {
53        self.labels
54            .binary_search_by(|label| label.key.cmp(key))
55            .ok()
56            .map(|index| &self.labels[index])
57    }
58
59    pub fn by_text(&self, text: &str) -> Option<&EnumTypeLabel> {
60        self.labels.iter().find(|label| label.label == text)
61    }
62
63    fn value(&self, label: &EnumTypeLabel) -> Value {
64        Value::Enum(
65            EnumValue::new(self.type_oid, label.key.clone()).with_label_oid(Some(label.oid)),
66        )
67    }
68
69    fn value_with_control(
70        &self,
71        label: &EnumTypeLabel,
72        control: &ProductionControl<'_>,
73    ) -> Result<Produced<Value>> {
74        let memory =
75            control.reserve(EnumValue::retained_header_bytes() + label.key.as_bytes().len())?;
76        Ok(control.finish(self.value(label), memory)?)
77    }
78}
79
80/// The enum-facing name of the shared SQL value catalog.
81pub use super::SQLValueCatalog as EnumLabelCatalog;
82
83pub(crate) fn enum_value_from_oid(
84    catalog: Option<&dyn EnumLabelCatalog>,
85    label_oid: u32,
86) -> Result<Value> {
87    catalog
88        .map(|catalog| catalog.enum_value_by_oid(label_oid))
89        .transpose()?
90        .flatten()
91        .map(Value::Enum)
92        .ok_or_else(|| SQLError::Routine {
93            sqlstate: "22P03".into(),
94            message: format!("invalid internal value for enum: {label_oid}"),
95        })
96}
97
98fn catalog_unavailable(type_oid: u32) -> SQLError {
99    SQLError::Internal(format!(
100        "enum type OID {type_oid} is not available in the statement catalog"
101    ))
102}
103
104pub(crate) fn labels(
105    catalog: Option<&dyn EnumLabelCatalog>,
106    type_oid: u32,
107) -> Result<Arc<EnumTypeLabels>> {
108    catalog
109        .ok_or_else(|| catalog_unavailable(type_oid))?
110        .enum_type_labels(type_oid)?
111        .ok_or_else(|| catalog_unavailable(type_oid))
112}
113
114pub(crate) fn type_name(catalog: Option<&dyn EnumLabelCatalog>, type_oid: u32) -> Result<String> {
115    catalog
116        .ok_or_else(|| catalog_unavailable(type_oid))?
117        .enum_type_name(type_oid)?
118        .ok_or_else(|| catalog_unavailable(type_oid))
119}
120
121/// `check_safe_enum_use`: a label added by the current transaction to a type it did not create is unusable until commit.
122fn check_safe(
123    catalog: Option<&dyn EnumLabelCatalog>,
124    labels: &EnumTypeLabels,
125    label: &EnumTypeLabel,
126) -> Result<()> {
127    if catalog.is_some_and(|catalog| catalog.enum_label_uncommitted(label.oid)) {
128        return Err(SQLError::Diagnostic {
129            sqlstate: "55P04".into(),
130            message: format!(
131                "unsafe use of new value \"{}\" of enum type {}",
132                label.label,
133                type_name(catalog, labels.type_oid)?
134            ),
135            detail: None,
136            hint: Some("New enum values must be committed before they can be used.".into()),
137        });
138    }
139    Ok(())
140}
141
142fn invalid_internal_value(value: &EnumValue) -> SQLError {
143    SQLError::Internal(format!(
144        "invalid internal value for enum type OID {}",
145        value.type_oid()
146    ))
147}
148
149/// The catalog label of a value, which carries the label OID and current text.
150pub(crate) fn enum_label(
151    catalog: Option<&dyn EnumLabelCatalog>,
152    value: &EnumValue,
153) -> Result<EnumTypeLabel> {
154    labels(catalog, value.type_oid())?
155        .by_key(value.key())
156        .cloned()
157        .ok_or_else(|| invalid_internal_value(value))
158}
159
160/// `enum_out`: the current label of a value.
161pub fn enum_label_text(
162    catalog: Option<&dyn EnumLabelCatalog>,
163    value: &EnumValue,
164) -> Result<String> {
165    enum_label(catalog, value).map(|label| label.label)
166}
167
168/// Catalog OID of an enum value's label, the datum `PostgreSQL` stores for the value.
169pub fn enum_label_oid(catalog: Option<&dyn EnumLabelCatalog>, value: &EnumValue) -> Result<u32> {
170    enum_label(catalog, value).map(|label| label.oid)
171}
172
173/// `enum_in`: the label with exactly this text. Case and surrounding spaces are significant.
174pub fn enum_value_from_text(
175    catalog: Option<&dyn EnumLabelCatalog>,
176    type_oid: u32,
177    text: &str,
178) -> Result<Value> {
179    enum_value_from_text_with_control(catalog, type_oid, text, &ProductionControl::uncontrolled())
180        .map(|value| value.into_uncontrolled().expect("ordinary enum input"))
181}
182
183/// Resolve the selected label, then admit its key and metadata before constructing the value.
184pub fn enum_value_from_text_with_control(
185    catalog: Option<&dyn EnumLabelCatalog>,
186    type_oid: u32,
187    text: &str,
188    control: &ProductionControl<'_>,
189) -> Result<Produced<Value>> {
190    control.check()?;
191    let labels = labels(catalog, type_oid)?;
192    control.check()?;
193    let Some(label) = labels.by_text(text) else {
194        return Err(SQLError::Routine {
195            sqlstate: "22P02".into(),
196            message: format!(
197                "invalid input value for enum {}: \"{text}\"",
198                type_name(catalog, type_oid)?
199            ),
200        });
201    };
202    check_safe(catalog, &labels, label)?;
203    labels.value_with_control(label, control)
204}
205
206/// `enum_first` and `enum_last` read only the argument's type; the returned label must be usable.
207pub fn enum_endpoint(
208    catalog: Option<&dyn EnumLabelCatalog>,
209    type_oid: u32,
210    last: bool,
211) -> Result<Value> {
212    enum_endpoint_with_control(catalog, type_oid, last, &ProductionControl::uncontrolled())
213        .map(|value| value.into_uncontrolled().expect("ordinary enum endpoint"))
214}
215
216fn enum_endpoint_with_control(
217    catalog: Option<&dyn EnumLabelCatalog>,
218    type_oid: u32,
219    last: bool,
220    control: &ProductionControl<'_>,
221) -> Result<Produced<Value>> {
222    control.check()?;
223    let labels = labels(catalog, type_oid)?;
224    let label = if last {
225        labels.labels.last()
226    } else {
227        labels.labels.first()
228    };
229    let Some(label) = label else {
230        return Err(SQLError::Routine {
231            sqlstate: "55000".into(),
232            message: format!("enum {} contains no values", type_name(catalog, type_oid)?),
233        });
234    };
235    check_safe(catalog, &labels, label)?;
236    labels.value_with_control(label, control)
237}
238
239/// `enum_range(lower, upper)`: labels from `lower` through `upper` inclusive, where a missing bound is open. A lower bound after the upper bound yields an empty array. Every returned label must be usable.
240pub fn enum_range(
241    catalog: Option<&dyn EnumLabelCatalog>,
242    type_oid: u32,
243    lower: Option<&EnumValue>,
244    upper: Option<&EnumValue>,
245) -> Result<Value> {
246    let lower = lower
247        .map(|value| enum_label_oid(catalog, value))
248        .transpose()?;
249    let upper = upper
250        .map(|value| enum_label_oid(catalog, value))
251        .transpose()?;
252    range_by_oid(catalog, type_oid, lower, upper)
253}
254
255fn range_by_oid(
256    catalog: Option<&dyn EnumLabelCatalog>,
257    type_oid: u32,
258    lower: Option<u32>,
259    upper: Option<u32>,
260) -> Result<Value> {
261    range_by_oid_with_control(
262        catalog,
263        type_oid,
264        lower,
265        upper,
266        &ProductionControl::uncontrolled(),
267    )
268    .map(|value| value.into_uncontrolled().expect("ordinary enum range"))
269}
270
271fn range_by_oid_with_control(
272    catalog: Option<&dyn EnumLabelCatalog>,
273    type_oid: u32,
274    lower: Option<u32>,
275    upper: Option<u32>,
276    control: &ProductionControl<'_>,
277) -> Result<Produced<Value>> {
278    control.check()?;
279    let labels = labels(catalog, type_oid)?;
280    let mut elements = ProductionVec::new(*control);
281    let mut include = lower.is_none_or(|oid| oid == 0);
282    for label in &labels.labels {
283        control.check()?;
284        if lower == Some(label.oid) {
285            include = true;
286        }
287        if include {
288            check_safe(catalog, &labels, label)?;
289            elements.push_produced(labels.value_with_control(label, control)?)?;
290        }
291        if upper == Some(label.oid) {
292            break;
293        }
294    }
295    let array = ArrayValue::try_new_with_control(elements.finish()?, control)?
296        .ok_or_else(|| SQLError::Internal("enum range array has invalid dimensions".into()))?;
297    let (array, memory) = array.into_parts();
298    Ok(control.finish(
299        Value::Array(array.with_element_type_oid(Some(type_oid))),
300        memory,
301    )?)
302}
303
304/// Replace every enum carrier inside a value by its label text, as the output functions of containers do.
305pub fn render_enum_labels(catalog: Option<&dyn EnumLabelCatalog>, value: &Value) -> Result<Value> {
306    map_enum_values(value, &mut |label| {
307        enum_label_text(catalog, label).map(Value::Str)
308    })
309}
310
311/// Retain physical identities without repeating enum input checks or changing admitted values. Legacy carriers resolve their missing OID once; existing identities remain usable after catalog changes.
312pub(crate) fn retain_enum_oids(
313    catalog: Option<&dyn EnumLabelCatalog>,
314    value: &Value,
315) -> Result<Value> {
316    map_enum_values(value, &mut |label| {
317        let oid = match label.label_oid() {
318            Some(oid) => oid,
319            None => enum_label_oid(catalog, label)?,
320        };
321        Ok(Value::Enum(label.clone().with_label_oid(Some(oid))))
322    })
323}
324
325fn map_enum_values(
326    value: &Value,
327    convert: &mut dyn FnMut(&EnumValue) -> Result<Value>,
328) -> Result<Value> {
329    Ok(match value {
330        Value::Enum(label) => convert(label)?,
331        Value::Array(array) => Value::Array(map_array(array, |element| {
332            map_enum_values(element, convert)
333        })?),
334        Value::List(values) => Value::List(
335            values
336                .iter()
337                .map(|element| map_enum_values(element, convert))
338                .collect::<Result<_>>()?,
339        ),
340        Value::Row(values) => Value::Row(
341            values.clone().with_values(
342                values
343                    .iter()
344                    .map(|element| map_enum_values(element, convert))
345                    .collect::<Result<_>>()?,
346            )?,
347        ),
348        Value::Record(fields) => Value::Record(uqa_core::RecordValue::from_shared_parts(
349            fields
350                .values()
351                .iter()
352                .map(|value| map_enum_values(value, convert))
353                .collect::<Result<_>>()?,
354            fields.descriptor().clone(),
355        )?),
356        Value::Map(fields) => Value::Map(
357            fields
358                .iter()
359                .map(|(name, element)| Ok((name.clone(), map_enum_values(element, convert)?)))
360                .collect::<Result<_>>()?,
361        ),
362        other => other.clone(),
363    })
364}
365
366/// Rebuild an array with the same bounds after converting every leaf element; nested dimensions are `List` elements.
367fn map_array(
368    array: &ArrayValue,
369    mut convert: impl FnMut(&Value) -> Result<Value>,
370) -> Result<ArrayValue> {
371    fn leaves(
372        values: &[Value],
373        convert: &mut dyn FnMut(&Value) -> Result<Value>,
374    ) -> Result<Vec<Value>> {
375        values
376            .iter()
377            .map(|value| match value {
378                Value::List(values) => leaves(values, convert).map(Value::List),
379                value => convert(value),
380            })
381            .collect()
382    }
383    let elements = leaves(array.elements(), &mut convert)?;
384    ArrayValue::with_lower_bounds(elements, array.lower_bounds().to_vec())
385        .filter(|converted| converted.dimensions() == array.dimensions())
386        .map(|converted| converted.with_element_type_oid(array.element_type_oid()))
387        .ok_or_else(|| SQLError::Internal("enum array conversion changed array dimensions".into()))
388}
389
390/// Whether a value contains an enum carrier anywhere.
391pub fn contains_enum_carrier(value: &Value) -> bool {
392    enum_carrier_matches(value, &|_| true)
393}
394
395pub(crate) fn has_missing_enum_oid(value: &Value) -> bool {
396    enum_carrier_matches(value, &|label| label.label_oid().is_none())
397}
398
399fn enum_carrier_matches(value: &Value, predicate: &dyn Fn(&EnumValue) -> bool) -> bool {
400    super::observations::any_nested_value(
401        value,
402        &mut |value| matches!(value, Value::Enum(label) if predicate(label)),
403    )
404}
405
406/// Whether a built-in call converts its arguments with their types' output functions, so enum arguments contribute their current labels. `||` concatenates text only when neither operand is an array; with an array operand it appends or prepends the enum value itself.
407#[must_use]
408pub fn call_applies_output_functions(name: &str, arguments: &[(Option<String>, Value)]) -> bool {
409    match name {
410        "concat_op" => !arguments
411            .iter()
412            .any(|(_, value)| matches!(value, Value::Array(_) | Value::List(_))),
413        "concat" | "concat_ws" | "format" | "quote_literal" | "quote_nullable" | "to_json"
414        | "to_jsonb" | "row_to_json" | "array_to_json" | "json_build_object"
415        | "json_build_array" | "jsonb_build_object" | "jsonb_build_array" | "array_to_string" => {
416            true
417        }
418        _ => false,
419    }
420}
421
422/// Render the enum carriers of an output-function call's arguments as their labels.
423pub fn render_call_arguments(
424    catalog: Option<&dyn EnumLabelCatalog>,
425    arguments: Vec<(Option<String>, Value)>,
426) -> Result<Vec<(Option<String>, Value)>> {
427    arguments
428        .into_iter()
429        .map(|(name, value)| {
430            if contains_enum_carrier(&value) {
431                Ok((name, render_enum_labels(catalog, &value)?))
432            } else {
433                Ok((name, value))
434            }
435        })
436        .collect()
437}
438
439/// Arguments handed to host-registered functions: enum values become their labels, as procedural languages receive them through the type's output function.
440pub fn render_host_arguments(
441    catalog: Option<&dyn EnumLabelCatalog>,
442    arguments: &[Value],
443) -> Result<Vec<Value>> {
444    arguments
445        .iter()
446        .map(|value| {
447            if contains_enum_carrier(value) {
448                render_enum_labels(catalog, value)
449            } else {
450                Ok(value.clone())
451            }
452        })
453        .collect()
454}
455
456/// Whether a declared type is an enum or an array whose leaf is an enum.
457#[must_use]
458pub fn is_enum_bearing(ty: &ColumnType) -> bool {
459    match ty {
460        ColumnType::Enum(_) => true,
461        ColumnType::Array(element) => is_enum_bearing(element),
462        _ => false,
463    }
464}
465
466/// Convert an `unknown` literal to an enum or enum-array type with the type's input function, as `PostgreSQL` does when it coerces an untyped constant during parse analysis. Returns `None` for any other target.
467pub fn fold_unknown_literal(
468    catalog: Option<&dyn EnumLabelCatalog>,
469    value: &Value,
470    target: &ColumnType,
471) -> Result<Option<Value>> {
472    match (target, value) {
473        (ColumnType::Enum(_) | ColumnType::Array(_), Value::Null) if is_enum_bearing(target) => {
474            Ok(Some(Value::Null))
475        }
476        (ColumnType::Enum(reference), Value::Str(text)) => {
477            enum_value_from_text(catalog, reference.oid, text).map(Some)
478        }
479        (ColumnType::Array(element), Value::Str(text)) if is_enum_bearing(element) => {
480            let mut leaf = element.as_ref();
481            while let ColumnType::Array(inner) = leaf {
482                leaf = inner;
483            }
484            let ColumnType::Enum(reference) = leaf else {
485                return Ok(None);
486            };
487            let parsed = super::casting::parse_pg_array_literal(text)?;
488            map_array(&parsed, |element| match element {
489                Value::Null => Ok(Value::Null),
490                Value::Str(text) => enum_value_from_text(catalog, reference.oid, text),
491                other => Err(SQLError::Internal(format!(
492                    "array literal parsing produced a non-text element {other:?}"
493                ))),
494            })
495            .map(|array| {
496                Some(Value::Array(
497                    array.with_element_type_oid(Some(reference.oid)),
498                ))
499            })
500        }
501        _ => Ok(None),
502    }
503}
504
505/// The string category accepted by automatic I/O conversion casts.
506fn string_category(ty: &ColumnType) -> bool {
507    match ty {
508        ColumnType::Text
509        | ColumnType::Varchar(_)
510        | ColumnType::Bpchar
511        | ColumnType::Character(_)
512        | ColumnType::Name => true,
513        ColumnType::Domain { base, .. } => string_category(base),
514        _ => false,
515    }
516}
517
518fn cannot_cast(source: &str, target: &str) -> SQLError {
519    SQLError::Routine {
520        sqlstate: "42846".into(),
521        message: format!("cannot cast type {source} to {target}"),
522    }
523}
524
525/// Cast a value to an enum type: identity for the same type, `enum_in` for unknown literals and string-category sources, and 42846 otherwise. Returns `None` when the target is not an enum.
526pub fn cast_to_enum(
527    catalog: Option<&dyn EnumLabelCatalog>,
528    value: &Value,
529    source: Option<&ColumnType>,
530    target: &ColumnType,
531) -> Result<Option<Value>> {
532    Ok(cast_to_enum_with_control(
533        catalog,
534        value,
535        source,
536        target,
537        &ProductionControl::uncontrolled(),
538    )?
539    .map(|value| value.into_uncontrolled().expect("ordinary enum cast")))
540}
541
542/// Apply enum input or retain an identity cast under the original allowance and both cancellation owners.
543pub fn cast_to_enum_with_control(
544    catalog: Option<&dyn EnumLabelCatalog>,
545    value: &Value,
546    source: Option<&ColumnType>,
547    target: &ColumnType,
548    control: &ProductionControl<'_>,
549) -> Result<Option<Produced<Value>>> {
550    control.check()?;
551    let ColumnType::Enum(reference) = target else {
552        return Ok(None);
553    };
554    let source_name = |source: Option<&ColumnType>| -> Result<String> {
555        Ok(match (value, source) {
556            (Value::Enum(label), _) => type_name(catalog, label.type_oid())?,
557            (_, Some(ColumnType::Enum(source))) => type_name(catalog, source.oid)?,
558            (_, Some(source)) => source.sql_name(),
559            (_, None) => "unknown".into(),
560        })
561    };
562    match value {
563        Value::Null => Ok(Some(
564            control.finish(Value::Null, control.empty_reservation())?,
565        )),
566        Value::Enum(label) if label.type_oid() == reference.oid => {
567            Ok(Some(control.copy_value(value)?))
568        }
569        Value::Datum(datum) if datum.type_oid() == reference.oid => {
570            Ok(Some(control.copy_value(value)?))
571        }
572        Value::Str(text) | Value::FixedChar(text) if source.is_none_or(string_category) => {
573            enum_value_from_text_with_control(catalog, reference.oid, text, control).map(Some)
574        }
575        _ => Err(cannot_cast(
576            &source_name(source)?,
577            &type_name(catalog, reference.oid)?,
578        )),
579    }
580}
581
582/// Cast an enum value to a string-category type through its label; any other target has no cast.
583pub fn enum_output_for_cast(
584    catalog: Option<&dyn EnumLabelCatalog>,
585    label: &EnumValue,
586    target: &ColumnType,
587) -> Result<Value> {
588    if string_category(target) {
589        return enum_label_text(catalog, label).map(Value::Str);
590    }
591    Err(cannot_cast(
592        &type_name(catalog, label.type_oid())?,
593        &match target {
594            ColumnType::Enum(reference) => type_name(catalog, reference.oid)?,
595            other => other.sql_name(),
596        },
597    ))
598}