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_parts(
349            fields
350                .iter()
351                .map(|(name, element)| Ok((name.clone(), map_enum_values(element, convert)?)))
352                .collect::<Result<_>>()?,
353            fields.type_oid(),
354        )),
355        Value::Map(fields) => Value::Map(
356            fields
357                .iter()
358                .map(|(name, element)| Ok((name.clone(), map_enum_values(element, convert)?)))
359                .collect::<Result<_>>()?,
360        ),
361        other => other.clone(),
362    })
363}
364
365/// Rebuild an array with the same bounds after converting every leaf element; nested dimensions are `List` elements.
366fn map_array(
367    array: &ArrayValue,
368    mut convert: impl FnMut(&Value) -> Result<Value>,
369) -> Result<ArrayValue> {
370    fn leaves(
371        values: &[Value],
372        convert: &mut dyn FnMut(&Value) -> Result<Value>,
373    ) -> Result<Vec<Value>> {
374        values
375            .iter()
376            .map(|value| match value {
377                Value::List(values) => leaves(values, convert).map(Value::List),
378                value => convert(value),
379            })
380            .collect()
381    }
382    let elements = leaves(array.elements(), &mut convert)?;
383    ArrayValue::with_lower_bounds(elements, array.lower_bounds().to_vec())
384        .filter(|converted| converted.dimensions() == array.dimensions())
385        .map(|converted| converted.with_element_type_oid(array.element_type_oid()))
386        .ok_or_else(|| SQLError::Internal("enum array conversion changed array dimensions".into()))
387}
388
389/// Whether a value contains an enum carrier anywhere.
390pub fn contains_enum_carrier(value: &Value) -> bool {
391    enum_carrier_matches(value, &|_| true)
392}
393
394pub(crate) fn has_missing_enum_oid(value: &Value) -> bool {
395    enum_carrier_matches(value, &|label| label.label_oid().is_none())
396}
397
398fn enum_carrier_matches(value: &Value, predicate: &dyn Fn(&EnumValue) -> bool) -> bool {
399    match value {
400        Value::Enum(label) => predicate(label),
401        Value::Array(array) => array
402            .elements()
403            .iter()
404            .any(|value| enum_carrier_matches(value, predicate)),
405        Value::List(values) => values
406            .iter()
407            .any(|value| enum_carrier_matches(value, predicate)),
408        Value::Row(values) => values
409            .iter()
410            .any(|value| enum_carrier_matches(value, predicate)),
411        Value::Record(fields) => fields
412            .iter()
413            .any(|(_, value)| enum_carrier_matches(value, predicate)),
414        Value::Map(fields) => fields
415            .values()
416            .any(|value| enum_carrier_matches(value, predicate)),
417        _ => false,
418    }
419}
420
421/// 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.
422#[must_use]
423pub fn call_applies_output_functions(name: &str, arguments: &[(Option<String>, Value)]) -> bool {
424    match name {
425        "concat_op" => !arguments
426            .iter()
427            .any(|(_, value)| matches!(value, Value::Array(_) | Value::List(_))),
428        "concat" | "concat_ws" | "format" | "quote_literal" | "quote_nullable" | "to_json"
429        | "to_jsonb" | "row_to_json" | "array_to_json" | "json_build_object"
430        | "json_build_array" | "jsonb_build_object" | "jsonb_build_array" | "array_to_string" => {
431            true
432        }
433        _ => false,
434    }
435}
436
437/// Render the enum carriers of an output-function call's arguments as their labels.
438pub fn render_call_arguments(
439    catalog: Option<&dyn EnumLabelCatalog>,
440    arguments: Vec<(Option<String>, Value)>,
441) -> Result<Vec<(Option<String>, Value)>> {
442    arguments
443        .into_iter()
444        .map(|(name, value)| {
445            if contains_enum_carrier(&value) {
446                Ok((name, render_enum_labels(catalog, &value)?))
447            } else {
448                Ok((name, value))
449            }
450        })
451        .collect()
452}
453
454/// Arguments handed to host-registered functions: enum values become their labels, as procedural languages receive them through the type's output function.
455pub fn render_host_arguments(
456    catalog: Option<&dyn EnumLabelCatalog>,
457    arguments: &[Value],
458) -> Result<Vec<Value>> {
459    arguments
460        .iter()
461        .map(|value| {
462            if contains_enum_carrier(value) {
463                render_enum_labels(catalog, value)
464            } else {
465                Ok(value.clone())
466            }
467        })
468        .collect()
469}
470
471/// Whether a declared type is an enum or an array whose leaf is an enum.
472#[must_use]
473pub fn is_enum_bearing(ty: &ColumnType) -> bool {
474    match ty {
475        ColumnType::Enum(_) => true,
476        ColumnType::Array(element) => is_enum_bearing(element),
477        _ => false,
478    }
479}
480
481/// 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.
482pub fn fold_unknown_literal(
483    catalog: Option<&dyn EnumLabelCatalog>,
484    value: &Value,
485    target: &ColumnType,
486) -> Result<Option<Value>> {
487    match (target, value) {
488        (ColumnType::Enum(_) | ColumnType::Array(_), Value::Null) if is_enum_bearing(target) => {
489            Ok(Some(Value::Null))
490        }
491        (ColumnType::Enum(reference), Value::Str(text)) => {
492            enum_value_from_text(catalog, reference.oid, text).map(Some)
493        }
494        (ColumnType::Array(element), Value::Str(text)) if is_enum_bearing(element) => {
495            let mut leaf = element.as_ref();
496            while let ColumnType::Array(inner) = leaf {
497                leaf = inner;
498            }
499            let ColumnType::Enum(reference) = leaf else {
500                return Ok(None);
501            };
502            let parsed = super::casting::parse_pg_array_literal(text)?;
503            map_array(&parsed, |element| match element {
504                Value::Null => Ok(Value::Null),
505                Value::Str(text) => enum_value_from_text(catalog, reference.oid, text),
506                other => Err(SQLError::Internal(format!(
507                    "array literal parsing produced a non-text element {other:?}"
508                ))),
509            })
510            .map(|array| {
511                Some(Value::Array(
512                    array.with_element_type_oid(Some(reference.oid)),
513                ))
514            })
515        }
516        _ => Ok(None),
517    }
518}
519
520/// The string category accepted by automatic I/O conversion casts.
521fn string_category(ty: &ColumnType) -> bool {
522    match ty {
523        ColumnType::Text
524        | ColumnType::Varchar(_)
525        | ColumnType::Bpchar
526        | ColumnType::Character(_)
527        | ColumnType::Name => true,
528        ColumnType::Domain { base, .. } => string_category(base),
529        _ => false,
530    }
531}
532
533fn cannot_cast(source: &str, target: &str) -> SQLError {
534    SQLError::Routine {
535        sqlstate: "42846".into(),
536        message: format!("cannot cast type {source} to {target}"),
537    }
538}
539
540/// 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.
541pub fn cast_to_enum(
542    catalog: Option<&dyn EnumLabelCatalog>,
543    value: &Value,
544    source: Option<&ColumnType>,
545    target: &ColumnType,
546) -> Result<Option<Value>> {
547    Ok(cast_to_enum_with_control(
548        catalog,
549        value,
550        source,
551        target,
552        &ProductionControl::uncontrolled(),
553    )?
554    .map(|value| value.into_uncontrolled().expect("ordinary enum cast")))
555}
556
557/// Apply enum input or retain an identity cast under the original allowance and both cancellation owners.
558pub fn cast_to_enum_with_control(
559    catalog: Option<&dyn EnumLabelCatalog>,
560    value: &Value,
561    source: Option<&ColumnType>,
562    target: &ColumnType,
563    control: &ProductionControl<'_>,
564) -> Result<Option<Produced<Value>>> {
565    control.check()?;
566    let ColumnType::Enum(reference) = target else {
567        return Ok(None);
568    };
569    let source_name = |source: Option<&ColumnType>| -> Result<String> {
570        Ok(match (value, source) {
571            (Value::Enum(label), _) => type_name(catalog, label.type_oid())?,
572            (_, Some(ColumnType::Enum(source))) => type_name(catalog, source.oid)?,
573            (_, Some(source)) => source.sql_name(),
574            (_, None) => "unknown".into(),
575        })
576    };
577    match value {
578        Value::Null => Ok(Some(
579            control.finish(Value::Null, control.empty_reservation())?,
580        )),
581        Value::Enum(label) if label.type_oid() == reference.oid => {
582            Ok(Some(control.copy_value(value)?))
583        }
584        Value::Datum(datum) if datum.type_oid() == reference.oid => {
585            Ok(Some(control.copy_value(value)?))
586        }
587        Value::Str(text) | Value::FixedChar(text) if source.is_none_or(string_category) => {
588            enum_value_from_text_with_control(catalog, reference.oid, text, control).map(Some)
589        }
590        _ => Err(cannot_cast(
591            &source_name(source)?,
592            &type_name(catalog, reference.oid)?,
593        )),
594    }
595}
596
597/// Cast an enum value to a string-category type through its label; any other target has no cast.
598pub fn enum_output_for_cast(
599    catalog: Option<&dyn EnumLabelCatalog>,
600    label: &EnumValue,
601    target: &ColumnType,
602) -> Result<Value> {
603    if string_category(target) {
604        return enum_label_text(catalog, label).map(Value::Str);
605    }
606    Err(cannot_cast(
607        &type_name(catalog, label.type_oid())?,
608        &match target {
609            ColumnType::Enum(reference) => type_name(catalog, reference.oid)?,
610            other => other.sql_name(),
611        },
612    ))
613}