1use 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#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct EnumTypeLabel {
39 pub oid: u32,
40 pub key: EnumLabelKey,
41 pub label: String,
42}
43
44#[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
80pub 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
121fn 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
149pub(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
160pub 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
168pub fn enum_label_oid(catalog: Option<&dyn EnumLabelCatalog>, value: &EnumValue) -> Result<u32> {
170 enum_label(catalog, value).map(|label| label.oid)
171}
172
173pub 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
183pub 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
206pub 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
239pub 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
304pub 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
311pub(crate) fn retain_enum_oids(
313 catalog: Option<&dyn EnumLabelCatalog>,
314 value: &Value,
315) -> Result<Value> {
316 retain_enum_oids_with_control(catalog, value, &ProductionControl::uncontrolled()).map(|value| {
317 value
318 .into_uncontrolled()
319 .expect("ordinary retained enum value")
320 })
321}
322
323pub(crate) fn retain_enum_oids_with_control(
324 catalog: Option<&dyn EnumLabelCatalog>,
325 value: &Value,
326 control: &ProductionControl<'_>,
327) -> Result<Produced<Value>> {
328 output::map_with_control(value, control, &mut |label| {
329 control.check()?;
330 let oid = match label.label_oid() {
331 Some(oid) => oid,
332 None => enum_label_oid(catalog, label)?,
333 };
334 let memory =
335 control.reserve(EnumValue::retained_header_bytes() + label.key().as_bytes().len())?;
336 Ok(control.finish(Value::Enum(label.clone().with_label_oid(Some(oid))), memory)?)
337 })
338}
339
340fn map_enum_values(
341 value: &Value,
342 convert: &mut dyn FnMut(&EnumValue) -> Result<Value>,
343) -> Result<Value> {
344 Ok(match value {
345 Value::Enum(label) => convert(label)?,
346 Value::Array(array) => Value::Array(map_array(array, |element| {
347 map_enum_values(element, convert)
348 })?),
349 Value::List(values) => Value::List(
350 values
351 .iter()
352 .map(|element| map_enum_values(element, convert))
353 .collect::<Result<_>>()?,
354 ),
355 Value::Row(values) => Value::Row(
356 values.clone().with_values(
357 values
358 .iter()
359 .map(|element| map_enum_values(element, convert))
360 .collect::<Result<_>>()?,
361 )?,
362 ),
363 Value::Record(fields) => Value::Record(uqa_core::RecordValue::from_shared_parts(
364 fields
365 .values()
366 .iter()
367 .map(|value| map_enum_values(value, convert))
368 .collect::<Result<_>>()?,
369 fields.descriptor().clone(),
370 )?),
371 Value::Map(fields) => Value::Map(
372 fields
373 .iter()
374 .map(|(name, element)| Ok((name.clone(), map_enum_values(element, convert)?)))
375 .collect::<Result<_>>()?,
376 ),
377 other => other.clone(),
378 })
379}
380
381fn map_array(
383 array: &ArrayValue,
384 mut convert: impl FnMut(&Value) -> Result<Value>,
385) -> Result<ArrayValue> {
386 fn leaves(
387 values: &[Value],
388 convert: &mut dyn FnMut(&Value) -> Result<Value>,
389 ) -> Result<Vec<Value>> {
390 values
391 .iter()
392 .map(|value| match value {
393 Value::List(values) => leaves(values, convert).map(Value::List),
394 value => convert(value),
395 })
396 .collect()
397 }
398 let elements = leaves(array.elements(), &mut convert)?;
399 ArrayValue::with_lower_bounds(elements, array.lower_bounds().to_vec())
400 .filter(|converted| converted.dimensions() == array.dimensions())
401 .map(|converted| converted.with_element_type_oid(array.element_type_oid()))
402 .ok_or_else(|| SQLError::Internal("enum array conversion changed array dimensions".into()))
403}
404
405pub fn contains_enum_carrier(value: &Value) -> bool {
407 enum_carrier_matches(value, &|_| true)
408}
409
410pub(crate) fn has_missing_enum_oid(value: &Value) -> bool {
411 enum_carrier_matches(value, &|label| label.label_oid().is_none())
412}
413
414fn enum_carrier_matches(value: &Value, predicate: &dyn Fn(&EnumValue) -> bool) -> bool {
415 super::observations::any_nested_value(
416 value,
417 &mut |value| matches!(value, Value::Enum(label) if predicate(label)),
418 )
419}
420
421#[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
437pub 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
454pub 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#[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
481pub fn fold_unknown_literal(
483 catalog: Option<&dyn EnumLabelCatalog>,
484 value: &Value,
485 target: &ColumnType,
486) -> Result<Option<Value>> {
487 Ok(fold_unknown_literal_with_control(
488 catalog,
489 value,
490 target,
491 &ProductionControl::uncontrolled(),
492 )?
493 .map(|value| value.into_uncontrolled().expect("ordinary enum literal")))
494}
495
496pub fn fold_unknown_literal_with_control(
498 catalog: Option<&dyn EnumLabelCatalog>,
499 value: &Value,
500 target: &ColumnType,
501 control: &ProductionControl<'_>,
502) -> Result<Option<Produced<Value>>> {
503 control.check()?;
504 match (target, value) {
505 (ColumnType::Enum(_) | ColumnType::Array(_), Value::Null) if is_enum_bearing(target) => Ok(
506 Some(control.finish(Value::Null, control.empty_reservation())?),
507 ),
508 (ColumnType::Enum(reference), Value::Str(text)) => {
509 enum_value_from_text_with_control(catalog, reference.oid, text, control).map(Some)
510 }
511 (ColumnType::Array(element), Value::Str(text)) if is_enum_bearing(element) => {
512 let mut leaf = element.as_ref();
513 while let ColumnType::Array(inner) = leaf {
514 control.check()?;
515 leaf = inner;
516 }
517 let ColumnType::Enum(reference) = leaf else {
518 return Ok(None);
519 };
520 let parsed = super::casting::parse_pg_array_literal_with_control(text, control)?;
521 let elements =
522 enum_literal_elements(parsed.elements(), catalog, reference.oid, control)?;
523 let mut bounds = ProductionVec::new(*control);
524 bounds.extend_from_slice(parsed.lower_bounds())?;
525 let array =
526 ArrayValue::with_lower_bounds_with_control(elements, bounds.finish()?, control)?
527 .filter(|array| array.dimensions() == parsed.dimensions())
528 .ok_or_else(|| {
529 SQLError::Internal("enum array conversion changed array dimensions".into())
530 })?;
531 let (array, memory) = array.into_parts();
532 Ok(Some(control.finish(
533 Value::Array(array.with_element_type_oid(Some(reference.oid))),
534 memory,
535 )?))
536 }
537 _ => Ok(None),
538 }
539}
540
541fn enum_literal_elements(
542 values: &[Value],
543 catalog: Option<&dyn EnumLabelCatalog>,
544 type_oid: u32,
545 control: &ProductionControl<'_>,
546) -> Result<Produced<Vec<Value>>> {
547 let mut output = ProductionVec::new(*control);
548 output.reserve(values.len())?;
549 for value in values {
550 control.check()?;
551 let value = match value {
552 Value::List(values) => {
553 let (values, memory) =
554 enum_literal_elements(values, catalog, type_oid, control)?.into_parts();
555 control.finish(Value::List(values), memory)?
556 }
557 Value::Null => control.finish(Value::Null, control.empty_reservation())?,
558 Value::Str(text) => {
559 enum_value_from_text_with_control(catalog, type_oid, text, control)?
560 }
561 other => {
562 return Err(SQLError::Internal(format!(
563 "array literal parsing produced a non-text element {other:?}"
564 )))
565 }
566 };
567 output.push_produced(value)?;
568 }
569 Ok(output.finish()?)
570}
571
572fn string_category(ty: &ColumnType) -> bool {
574 match ty {
575 ColumnType::Text
576 | ColumnType::Varchar(_)
577 | ColumnType::Bpchar
578 | ColumnType::Character(_)
579 | ColumnType::Name => true,
580 ColumnType::Domain { base, .. } => string_category(base),
581 _ => false,
582 }
583}
584
585fn cannot_cast(source: &str, target: &str) -> SQLError {
586 SQLError::Routine {
587 sqlstate: "42846".into(),
588 message: format!("cannot cast type {source} to {target}"),
589 }
590}
591
592pub fn cast_to_enum(
594 catalog: Option<&dyn EnumLabelCatalog>,
595 value: &Value,
596 source: Option<&ColumnType>,
597 target: &ColumnType,
598) -> Result<Option<Value>> {
599 Ok(cast_to_enum_with_control(
600 catalog,
601 value,
602 source,
603 target,
604 &ProductionControl::uncontrolled(),
605 )?
606 .map(|value| value.into_uncontrolled().expect("ordinary enum cast")))
607}
608
609pub fn cast_to_enum_with_control(
611 catalog: Option<&dyn EnumLabelCatalog>,
612 value: &Value,
613 source: Option<&ColumnType>,
614 target: &ColumnType,
615 control: &ProductionControl<'_>,
616) -> Result<Option<Produced<Value>>> {
617 control.check()?;
618 let ColumnType::Enum(reference) = target else {
619 return Ok(None);
620 };
621 let source_name = |source: Option<&ColumnType>| -> Result<String> {
622 Ok(match (value, source) {
623 (Value::Enum(label), _) => type_name(catalog, label.type_oid())?,
624 (_, Some(ColumnType::Enum(source))) => type_name(catalog, source.oid)?,
625 (_, Some(source)) => source.sql_name(),
626 (_, None) => "unknown".into(),
627 })
628 };
629 match value {
630 Value::Null => Ok(Some(
631 control.finish(Value::Null, control.empty_reservation())?,
632 )),
633 Value::Enum(label) if label.type_oid() == reference.oid => {
634 Ok(Some(control.copy_value(value)?))
635 }
636 Value::Datum(datum) if datum.type_oid() == reference.oid => {
637 Ok(Some(control.copy_value(value)?))
638 }
639 Value::Str(text) | Value::FixedChar(text) if source.is_none_or(string_category) => {
640 enum_value_from_text_with_control(catalog, reference.oid, text, control).map(Some)
641 }
642 _ => Err(cannot_cast(
643 &source_name(source)?,
644 &type_name(catalog, reference.oid)?,
645 )),
646 }
647}
648
649pub fn enum_output_for_cast(
651 catalog: Option<&dyn EnumLabelCatalog>,
652 label: &EnumValue,
653 target: &ColumnType,
654) -> Result<Value> {
655 if string_category(target) {
656 return enum_label_text(catalog, label).map(Value::Str);
657 }
658 Err(cannot_cast(
659 &type_name(catalog, label.type_oid())?,
660 &match target {
661 ColumnType::Enum(reference) => type_name(catalog, reference.oid)?,
662 other => other.sql_name(),
663 },
664 ))
665}