Skip to main content

uqa_sql/result/
text.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Typed `PostgreSQL` text output for result consumers.
8
9use crate::ast::ColumnType;
10use crate::expr::{
11    format_regtype_value_with_catalog_and_control, EngineHook, EngineValueCatalog, SQLValueCatalog,
12};
13use crate::SQLError;
14use uqa_core::{
15    memory::{Produced, ProductionControl, ProductionString},
16    Value,
17};
18
19/// Format a result with its live session output style and declared type.
20pub fn format_postgres_text(
21    value: &Value,
22    ty: &ColumnType,
23    engine: Option<&dyn EngineHook>,
24) -> Result<String, SQLError> {
25    let _interval_style = if crate::expr::interval_style::output_can_contain_interval(value) {
26        crate::expr::interval_style::live_scope(engine, &ProductionControl::uncontrolled())?
27    } else {
28        None
29    };
30    let catalog = engine.map(EngineValueCatalog);
31    format_postgres_text_with_catalog(
32        value,
33        ty,
34        catalog
35            .as_ref()
36            .map(|catalog| catalog as &dyn SQLValueCatalog),
37    )
38}
39
40/// Format an admitted value through borrowed type and output metadata, without requiring a stateful scalar execution hook.
41pub fn format_postgres_text_with_catalog(
42    value: &Value,
43    ty: &ColumnType,
44    catalog: Option<&dyn SQLValueCatalog>,
45) -> Result<String, SQLError> {
46    format_postgres_text_with_catalog_and_control(
47        value,
48        ty,
49        catalog,
50        &ProductionControl::uncontrolled(),
51    )?
52    .into_uncontrolled()
53    .map_err(|_| SQLError::Internal("ordinary typed output owner".into()))
54}
55
56/// Observe typed values into the caller's admitted output, including nested array and composite fields.
57pub fn format_postgres_text_with_catalog_and_control(
58    value: &Value,
59    ty: &ColumnType,
60    catalog: Option<&dyn SQLValueCatalog>,
61    control: &ProductionControl<'_>,
62) -> Result<Produced<String>, SQLError> {
63    control.check()?;
64    if let Value::Datum(datum) = value {
65        let mut base = ty;
66        while let ColumnType::Domain { base: inner, .. } = base {
67            base = inner;
68        }
69        let value = if matches!(
70            base,
71            ColumnType::Range(_)
72                | ColumnType::Multirange(_)
73                | ColumnType::DeclaredRange(_)
74                | ColumnType::DeclaredMultirange(_)
75        ) {
76            crate::expr::datums::read_range_with_type(datum, base, catalog, control)?
77        } else {
78            crate::expr::datums::read_with_value_catalog_and_control(datum, catalog, control)?
79        };
80        return format_postgres_text_with_catalog_and_control(&value, ty, catalog, control);
81    }
82    if let ColumnType::Domain { base, .. } = ty {
83        return format_postgres_text_with_catalog_and_control(value, base, catalog, control);
84    }
85    if matches!(ty, ColumnType::InternalChar) {
86        let byte = crate::expr::internal_char::value_byte(value)
87            .ok_or_else(|| SQLError::Internal("invalid internal char result carrier".into()))?;
88        return Ok(crate::expr::internal_char::output_with_control(
89            byte, control,
90        )?);
91    }
92    if let Some(text) = format_regtype_value_with_catalog_and_control(value, ty, catalog, control)?
93    {
94        return Ok(text);
95    }
96    if matches!(ty, ColumnType::Int2Vector | ColumnType::OidVector) {
97        return crate::expr::vector_value_to_string_with_control(value, control)?
98            .ok_or_else(|| SQLError::Internal("invalid catalog vector result carrier".into()));
99    }
100    if let ColumnType::Array(element) = ty {
101        return format_array(value, element, catalog, control);
102    }
103    if let (ColumnType::Composite(reference), Value::Record(fields)) = (ty, value) {
104        return format_record(
105            fields,
106            fields.type_oid().unwrap_or(reference.oid),
107            catalog,
108            control,
109        );
110    }
111    Ok(match value {
112        Value::Bool(value) => control.copy_text(if *value { "t" } else { "f" })?,
113        Value::FixedChar(value) => control.copy_text(value)?,
114        Value::Float(value) if matches!(ty, ColumnType::Real) => {
115            crate::expr::format_real_with_control(*value as f32, control)?
116        }
117        Value::Float(value) => uqa_core::format_float_pg_with_control(*value, control)?,
118        Value::Enum(label) => {
119            crate::expr::enums::enum_label_text_with_control(catalog, label, control)?
120        }
121        _ if crate::expr::enums::contains_enum_carrier(value) => {
122            // Untyped legacy containers retain their established conversion semantics.
123            let rendered =
124                crate::expr::enums::render_enum_labels_with_control(catalog, value, control)?;
125            crate::expr::value_to_string_with_control(&rendered, control)?
126        }
127        _ => crate::expr::value_to_string_with_control(value, control)?,
128    })
129}
130
131fn format_array(
132    value: &Value,
133    element: &ColumnType,
134    catalog: Option<&dyn SQLValueCatalog>,
135    control: &ProductionControl<'_>,
136) -> Result<Produced<String>, SQLError> {
137    let mut element = element;
138    while let ColumnType::Array(inner) = element {
139        control.check()?;
140        element = inner;
141    }
142    let catalog_element;
143    if let Value::Array(array) = value {
144        if let Some(oid) = array.element_type_oid() {
145            if let Some(actual) = crate::catalog::type_metadata::builtin_scalar_type(oid) {
146                element = actual;
147            } else if crate::catalog::type_metadata::pg_type_oid(element) != i64::from(oid) {
148                catalog_element = catalog
149                    .map(|catalog| catalog.value_type_by_oid(oid))
150                    .transpose()?
151                    .flatten()
152                    .ok_or_else(|| SQLError::Routine {
153                        sqlstate: "XX000".into(),
154                        message: format!("cache lookup failed for type {oid}"),
155                    })?
156                    .retain_external_with_control(control)?;
157                element = &catalog_element;
158            }
159        }
160    }
161    let mut text = ProductionString::new(*control);
162    let values = match value {
163        Value::Array(array) => array_parts(array, &mut text, control)?,
164        Value::LegacyVector(vector) => array_parts(vector.as_array(), &mut text, control)?,
165        Value::List(values) => values.as_slice(),
166        _ => return Err(SQLError::Internal("invalid array result carrier".into())),
167    };
168    text.push('{')?;
169    for (index, value) in values.iter().enumerate() {
170        control.check()?;
171        if index != 0 {
172            text.push(',')?;
173        }
174        match value {
175            Value::Null => text.push_str("NULL")?,
176            Value::List(_) | Value::Array(_) => {
177                text.push_str(&format_array(value, element, catalog, control)?)?;
178            }
179            _ => {
180                let rendered = format_postgres_text_with_catalog_and_control(
181                    value, element, catalog, control,
182                )?;
183                let quoted = rendered.is_empty()
184                    || rendered.eq_ignore_ascii_case("null")
185                    || rendered.chars().any(|c| {
186                        (c.is_ascii() && c.is_whitespace())
187                            || matches!(c, ',' | '{' | '}' | '"' | '\\')
188                    });
189                append_quoted(&mut text, &rendered, quoted, false)?;
190            }
191        }
192    }
193    text.push('}')?;
194    Ok(text.finish()?)
195}
196
197fn format_record(
198    fields: &[(String, Value)],
199    type_oid: u32,
200    catalog: Option<&dyn SQLValueCatalog>,
201    control: &ProductionControl<'_>,
202) -> Result<Produced<String>, SQLError> {
203    let descriptor = catalog
204        .ok_or_else(|| SQLError::Internal("composite type catalog is unavailable".into()))?
205        .value_composite_type(type_oid)?
206        .ok_or_else(|| SQLError::Routine {
207            sqlstate: "42704".into(),
208            message: format!("type with OID {type_oid} does not exist"),
209        })?;
210    let mut text = ProductionString::new(*control);
211    text.push('(')?;
212    for (index, (name, field)) in fields.iter().enumerate() {
213        control.check()?;
214        if index != 0 {
215            text.push(',')?;
216        }
217        if matches!(field, Value::Null) {
218            continue;
219        }
220        let rendered = match descriptor.attribute(name) {
221            Some((_, attribute)) => format_postgres_text_with_catalog_and_control(
222                field,
223                &attribute.ty,
224                catalog,
225                control,
226            )?,
227            None => format_postgres_text_with_catalog_and_control(
228                field,
229                &crate::type_resolution::value_type(field).unwrap_or(ColumnType::Text),
230                catalog,
231                control,
232            )?,
233        };
234        let quoted = rendered.is_empty()
235            || rendered
236                .chars()
237                .any(|c| c.is_ascii_whitespace() || matches!(c, ',' | '(' | ')' | '"' | '\\'));
238        append_quoted(&mut text, &rendered, quoted, true)?;
239    }
240    text.push(')')?;
241    Ok(text.finish()?)
242}
243
244fn append_quoted(
245    text: &mut ProductionString<'_>,
246    rendered: &str,
247    quoted: bool,
248    doubled: bool,
249) -> Result<(), SQLError> {
250    if quoted {
251        text.push('"')?;
252    }
253    for character in rendered.chars() {
254        if quoted && matches!(character, '"' | '\\') {
255            text.push(if doubled { character } else { '\\' })?;
256        }
257        text.push(character)?;
258    }
259    if quoted {
260        text.push('"')?;
261    }
262    Ok(())
263}
264
265fn array_parts<'a>(
266    array: &'a uqa_core::ArrayValue,
267    text: &mut ProductionString<'_>,
268    control: &ProductionControl<'_>,
269) -> Result<&'a [Value], SQLError> {
270    if !array.elements().is_empty() && array.lower_bounds().iter().any(|lower| *lower != 1) {
271        for (lower, length) in array.lower_bounds().iter().zip(array.dimensions()) {
272            let upper = i64::from(*lower) + *length as i64 - 1;
273            text.push_str(&control.format(format_args!("[{lower}:{upper}]"))?)?;
274        }
275        text.push('=')?;
276    }
277    Ok(array.elements())
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283    use std::cell::Cell;
284    use uqa_core::ArrayValue;
285
286    struct Catalog {
287        lookups: Cell<usize>,
288    }
289
290    fn domain() -> ColumnType {
291        ColumnType::Domain {
292            collation_oid: None,
293            schema: "public".into(),
294            name: "real_value".into(),
295            oid: 16_500,
296            array_oid: Some(16_501),
297            base: Box::new(ColumnType::Real),
298        }
299    }
300
301    impl EngineHook for Catalog {
302        fn nextval(&self, _: &str) -> Result<i64, SQLError> {
303            unreachable!()
304        }
305
306        fn currval(&self, _: &str) -> Result<i64, SQLError> {
307            unreachable!()
308        }
309
310        fn setval(&self, _: &str, _: i64, _: bool) -> Result<i64, SQLError> {
311            unreachable!()
312        }
313
314        fn resolve_type_oid(&self, oid: u32) -> Result<Option<ColumnType>, String> {
315            self.lookups.set(self.lookups.get() + 1);
316            Ok((oid == 16_500).then(domain))
317        }
318    }
319
320    #[test]
321    fn array_output_uses_original_catalog_element_and_reports_missing_identity() {
322        let catalog = Catalog {
323            lookups: Cell::new(0),
324        };
325        let value = Value::Array(
326            ArrayValue::try_new(vec![Value::Float(f64::from(0.1_f32)), Value::Null])
327                .unwrap()
328                .with_element_type_oid(Some(16_500)),
329        );
330        let changed = ColumnType::Array(Box::new(ColumnType::Text));
331        assert_eq!(
332            format_postgres_text(&value, &changed, Some(&catalog)).unwrap(),
333            "{0.1,NULL}"
334        );
335        assert_eq!(catalog.lookups.get(), 1);
336        assert_eq!(
337            format_postgres_text(
338                &value,
339                &ColumnType::Array(Box::new(domain())),
340                Some(&catalog),
341            )
342            .unwrap(),
343            "{0.1,NULL}"
344        );
345        assert_eq!(catalog.lookups.get(), 1);
346        let error = format_postgres_text(&value, &changed, None).unwrap_err();
347        assert_eq!(error.sqlstate(), Some("XX000"));
348        assert_eq!(error.to_string(), "cache lookup failed for type 16500");
349    }
350}