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
19mod records;
20
21/// Format a result with its live session output style and declared type.
22pub fn format_postgres_text(
23    value: &Value,
24    ty: &ColumnType,
25    engine: Option<&dyn EngineHook>,
26) -> Result<String, SQLError> {
27    format_postgres_text_with_control(value, ty, engine, &ProductionControl::uncontrolled())?
28        .into_uncontrolled()
29        .map_err(|_| SQLError::Internal("ordinary typed output owner".into()))
30}
31
32/// Format through the live session while charging output and temporary payloads to the caller.
33pub fn format_postgres_text_with_control(
34    value: &Value,
35    ty: &ColumnType,
36    engine: Option<&dyn EngineHook>,
37    control: &ProductionControl<'_>,
38) -> Result<Produced<String>, SQLError> {
39    let _interval_style = if crate::expr::interval_style::output_can_contain_interval(value) {
40        crate::expr::interval_style::live_scope(engine, control)?
41    } else {
42        None
43    };
44    let catalog = engine.map(EngineValueCatalog);
45    format_postgres_text_with_catalog_and_control(
46        value,
47        ty,
48        catalog
49            .as_ref()
50            .map(|catalog| catalog as &dyn SQLValueCatalog),
51        control,
52    )
53}
54
55/// Format an admitted value through borrowed type and output metadata, without requiring a stateful scalar execution hook.
56pub fn format_postgres_text_with_catalog(
57    value: &Value,
58    ty: &ColumnType,
59    catalog: Option<&dyn SQLValueCatalog>,
60) -> Result<String, SQLError> {
61    format_postgres_text_with_catalog_and_control(
62        value,
63        ty,
64        catalog,
65        &ProductionControl::uncontrolled(),
66    )?
67    .into_uncontrolled()
68    .map_err(|_| SQLError::Internal("ordinary typed output owner".into()))
69}
70
71/// Observe typed values into the caller's admitted output, including nested array and composite fields.
72pub fn format_postgres_text_with_catalog_and_control(
73    value: &Value,
74    ty: &ColumnType,
75    catalog: Option<&dyn SQLValueCatalog>,
76    control: &ProductionControl<'_>,
77) -> Result<Produced<String>, SQLError> {
78    control.check()?;
79    if let Value::Datum(datum) = value {
80        let mut base = ty;
81        while let ColumnType::Domain { base: inner, .. } = base {
82            base = inner;
83        }
84        let value = if matches!(
85            base,
86            ColumnType::Range(_)
87                | ColumnType::Multirange(_)
88                | ColumnType::DeclaredRange(_)
89                | ColumnType::DeclaredMultirange(_)
90        ) {
91            crate::expr::datums::read_range_with_type(datum, base, catalog, control)?
92        } else {
93            crate::expr::datums::read_with_value_catalog_and_control(datum, catalog, control)?
94        };
95        return format_postgres_text_with_catalog_and_control(&value, ty, catalog, control);
96    }
97    if let ColumnType::Domain { base, .. } = ty {
98        return format_postgres_text_with_catalog_and_control(value, base, catalog, control);
99    }
100    if let (ColumnType::Xml, Value::Str(text)) = (ty, value) {
101        return crate::xml::output_with_control(text, control);
102    }
103    if matches!(ty, ColumnType::InternalChar) {
104        let byte = crate::expr::internal_char::value_byte(value)
105            .ok_or_else(|| SQLError::Internal("invalid internal char result carrier".into()))?;
106        return Ok(crate::expr::internal_char::output_with_control(
107            byte, control,
108        )?);
109    }
110    if let Some(text) = format_regtype_value_with_catalog_and_control(value, ty, catalog, control)?
111    {
112        return Ok(text);
113    }
114    if matches!(ty, ColumnType::Int2Vector | ColumnType::OidVector) {
115        return crate::expr::vector_value_to_string_with_control(value, control)?
116            .ok_or_else(|| SQLError::Internal("invalid catalog vector result carrier".into()));
117    }
118    if let ColumnType::Array(element) = ty {
119        return format_array(value, element, catalog, control);
120    }
121    if let Value::Row(row) = value {
122        return records::format_row(row, catalog, control);
123    }
124    if let Value::Record(fields) = value {
125        let oid = fields.type_oid().or(match ty {
126            ColumnType::Composite(reference) => Some(reference.oid),
127            _ => None,
128        });
129        if let Some(oid) = oid {
130            return format_record(fields, oid, catalog, control);
131        }
132    }
133    Ok(match value {
134        Value::Bool(value) => control.copy_text(if *value { "t" } else { "f" })?,
135        Value::FixedChar(value) => control.copy_text(value)?,
136        Value::Float(value) if matches!(ty, ColumnType::Real) => {
137            crate::expr::format_real_with_control(*value as f32, control)?
138        }
139        Value::Float(value) => uqa_core::format_float_pg_with_control(*value, control)?,
140        Value::Enum(label) => {
141            crate::expr::enums::enum_label_text_with_control(catalog, label, control)?
142        }
143        _ if crate::expr::enums::contains_enum_carrier(value) => {
144            // Untyped legacy containers retain their established conversion semantics.
145            let rendered =
146                crate::expr::enums::render_enum_labels_with_control(catalog, value, control)?;
147            crate::expr::value_to_string_with_control(&rendered, control)?
148        }
149        _ => crate::expr::value_to_string_with_control(value, control)?,
150    })
151}
152
153fn format_array(
154    value: &Value,
155    element: &ColumnType,
156    catalog: Option<&dyn SQLValueCatalog>,
157    control: &ProductionControl<'_>,
158) -> Result<Produced<String>, SQLError> {
159    let mut element = element;
160    while let ColumnType::Array(inner) = element {
161        control.check()?;
162        element = inner;
163    }
164    let catalog_element;
165    if let Value::Array(array) = value {
166        if let Some(oid) = array.element_type_oid() {
167            if let Some(actual) = crate::catalog::type_metadata::builtin_scalar_type(oid) {
168                element = actual;
169            } else if crate::catalog::type_metadata::pg_type_oid(element) != i64::from(oid) {
170                catalog_element = catalog
171                    .map(|catalog| catalog.value_type_by_oid(oid))
172                    .transpose()?
173                    .flatten()
174                    .ok_or_else(|| SQLError::Routine {
175                        sqlstate: "XX000".into(),
176                        message: format!("cache lookup failed for type {oid}"),
177                    })?
178                    .retain_external_with_control(control)?;
179                element = &catalog_element;
180            }
181        }
182    }
183    let mut text = ProductionString::new(*control);
184    let values = match value {
185        Value::Array(array) => array_parts(array, &mut text, control)?,
186        Value::LegacyVector(vector) => array_parts(vector.as_array(), &mut text, control)?,
187        Value::List(values) => values.as_slice(),
188        _ => return Err(SQLError::Internal("invalid array result carrier".into())),
189    };
190    text.push('{')?;
191    for (index, value) in values.iter().enumerate() {
192        control.check()?;
193        if index != 0 {
194            text.push(',')?;
195        }
196        match value {
197            Value::Null => text.push_str("NULL")?,
198            Value::List(_) => {
199                text.push_str(&format_array(value, element, catalog, control)?)?;
200            }
201            _ => {
202                let rendered = format_postgres_text_with_catalog_and_control(
203                    value, element, catalog, control,
204                )?;
205                let quoted = rendered.is_empty()
206                    || rendered.eq_ignore_ascii_case("null")
207                    || rendered.chars().any(|c| {
208                        (c.is_ascii() && c.is_whitespace())
209                            || matches!(c, ',' | '{' | '}' | '"' | '\\')
210                    });
211                append_quoted(&mut text, &rendered, quoted, false)?;
212            }
213        }
214    }
215    text.push('}')?;
216    Ok(text.finish()?)
217}
218
219fn format_record(
220    fields: &uqa_core::RecordValue,
221    type_oid: u32,
222    catalog: Option<&dyn SQLValueCatalog>,
223    control: &ProductionControl<'_>,
224) -> Result<Produced<String>, SQLError> {
225    let descriptor = catalog
226        .ok_or_else(|| SQLError::Internal("composite type catalog is unavailable".into()))?
227        .value_composite_type(type_oid)?
228        .ok_or_else(|| SQLError::Routine {
229            sqlstate: "42704".into(),
230            message: format!("type with OID {type_oid} does not exist"),
231        })?;
232    let mut text = ProductionString::new(*control);
233    text.push('(')?;
234    for (index, (name, field)) in fields.iter().enumerate() {
235        control.check()?;
236        if index != 0 {
237            text.push(',')?;
238        }
239        if matches!(field, Value::Null) {
240            continue;
241        }
242        let rendered = match descriptor.attribute(name) {
243            Some((_, attribute)) => format_postgres_text_with_catalog_and_control(
244                field,
245                &attribute.ty,
246                catalog,
247                control,
248            )?,
249            None => format_postgres_text_with_catalog_and_control(
250                field,
251                &crate::type_resolution::value_type(field).unwrap_or(ColumnType::Text),
252                catalog,
253                control,
254            )?,
255        };
256        let quoted = rendered.is_empty()
257            || rendered
258                .chars()
259                .any(|c| c.is_ascii_whitespace() || matches!(c, ',' | '(' | ')' | '"' | '\\'));
260        append_quoted(&mut text, &rendered, quoted, true)?;
261    }
262    text.push(')')?;
263    Ok(text.finish()?)
264}
265
266fn append_quoted(
267    text: &mut ProductionString<'_>,
268    rendered: &str,
269    quoted: bool,
270    doubled: bool,
271) -> Result<(), SQLError> {
272    if quoted {
273        text.push('"')?;
274    }
275    for character in rendered.chars() {
276        if quoted && matches!(character, '"' | '\\') {
277            text.push(if doubled { character } else { '\\' })?;
278        }
279        text.push(character)?;
280    }
281    if quoted {
282        text.push('"')?;
283    }
284    Ok(())
285}
286
287fn array_parts<'a>(
288    array: &'a uqa_core::ArrayValue,
289    text: &mut ProductionString<'_>,
290    control: &ProductionControl<'_>,
291) -> Result<&'a [Value], SQLError> {
292    if !array.elements().is_empty() && array.lower_bounds().iter().any(|lower| *lower != 1) {
293        for (lower, length) in array.lower_bounds().iter().zip(array.dimensions()) {
294            let upper = i64::from(*lower) + *length as i64 - 1;
295            text.push_str(&control.format(format_args!("[{lower}:{upper}]"))?)?;
296        }
297        text.push('=')?;
298    }
299    Ok(array.elements())
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305    use std::cell::Cell;
306    use uqa_core::ArrayValue;
307
308    struct Catalog {
309        lookups: Cell<usize>,
310    }
311
312    fn domain() -> ColumnType {
313        ColumnType::Domain {
314            collation_oid: None,
315            schema: "public".into(),
316            name: "real_value".into(),
317            oid: 16_500,
318            array_oid: Some(16_501),
319            base: Box::new(ColumnType::Real),
320        }
321    }
322
323    impl EngineHook for Catalog {
324        fn nextval(&self, _: &str) -> Result<i64, SQLError> {
325            unreachable!()
326        }
327
328        fn currval(&self, _: &str) -> Result<i64, SQLError> {
329            unreachable!()
330        }
331
332        fn setval(&self, _: &str, _: i64, _: bool) -> Result<i64, SQLError> {
333            unreachable!()
334        }
335
336        fn resolve_type_oid(&self, oid: u32) -> Result<Option<ColumnType>, String> {
337            self.lookups.set(self.lookups.get() + 1);
338            Ok((oid == 16_500).then(domain))
339        }
340
341        fn temporal_interval_style(
342            &self,
343        ) -> Result<Option<uqa_core::TemporalIntervalStyle>, SQLError> {
344            Ok(Some(uqa_core::TemporalIntervalStyle::Iso8601))
345        }
346    }
347
348    #[test]
349    fn controlled_session_output_keeps_live_style_and_releases_its_allowance() {
350        use uqa_core::{memory::MemoryBudget, CancellationToken, TemporalValue};
351        let catalog = Catalog {
352            lookups: Cell::new(0),
353        };
354        let memory = MemoryBudget::new(4096);
355        let cancellation = CancellationToken::new();
356        let control = ProductionControl::new(&memory, &cancellation, &cancellation);
357        let value = Value::Temporal(TemporalValue::Interval {
358            months: 0,
359            days: 1,
360            micros: 0,
361        });
362        let text = format_postgres_text_with_control(
363            &value,
364            &ColumnType::Interval,
365            Some(&catalog),
366            &control,
367        )
368        .unwrap();
369        assert_eq!(&**text, "P1D");
370        assert!(memory.used() > 0);
371        drop(text);
372        assert_eq!(memory.used(), 0);
373        cancellation.cancel();
374        let error = format_postgres_text_with_control(
375            &value,
376            &ColumnType::Interval,
377            Some(&catalog),
378            &control,
379        )
380        .unwrap_err();
381        assert_eq!(error.sqlstate(), Some("57014"));
382        assert_eq!(memory.used(), 0);
383    }
384
385    #[test]
386    fn array_output_uses_original_catalog_element_and_reports_missing_identity() {
387        let catalog = Catalog {
388            lookups: Cell::new(0),
389        };
390        let value = Value::Array(
391            ArrayValue::try_new(vec![Value::Float(f64::from(0.1_f32)), Value::Null])
392                .unwrap()
393                .with_element_type_oid(Some(16_500)),
394        );
395        let changed = ColumnType::Array(Box::new(ColumnType::Text));
396        assert_eq!(
397            format_postgres_text(&value, &changed, Some(&catalog)).unwrap(),
398            "{0.1,NULL}"
399        );
400        assert_eq!(catalog.lookups.get(), 1);
401        assert_eq!(
402            format_postgres_text(
403                &value,
404                &ColumnType::Array(Box::new(domain())),
405                Some(&catalog),
406            )
407            .unwrap(),
408            "{0.1,NULL}"
409        );
410        assert_eq!(catalog.lookups.get(), 1);
411        let error = format_postgres_text(&value, &changed, None).unwrap_err();
412        assert_eq!(error.sqlstate(), Some("XX000"));
413        assert_eq!(error.to_string(), "cache lookup failed for type 16500");
414    }
415
416    fn typed_row(fields: Vec<(Value, u32)>) -> Value {
417        use uqa_core::{RecordFieldType, RowValue};
418        let (values, types) = fields
419            .into_iter()
420            .map(|(value, oid)| {
421                (
422                    value,
423                    RecordFieldType {
424                        oid,
425                        type_modifier: -1,
426                        collation_oid: None,
427                    },
428                )
429            })
430            .unzip();
431        Value::Row(RowValue::typed(values, types).unwrap())
432    }
433
434    #[test]
435    fn anonymous_record_output_keeps_field_types_and_skips_null_type_lookup() {
436        let catalog = Catalog {
437            lookups: Cell::new(0),
438        };
439        let value = typed_row(vec![
440            (Value::Float(f64::from(0.1_f32)), 700),
441            (Value::Float(f64::from(0.1_f32)), 16_500),
442            (Value::Null, 65_000),
443        ]);
444        // PostgreSQL 18.4: ROW(0.1::real, 0.1::domain_over_real, NULL::integer)::text.
445        assert_eq!(
446            format_postgres_text(&value, &ColumnType::Record, Some(&catalog)).unwrap(),
447            "(0.1,0.1,)"
448        );
449        assert_eq!(catalog.lookups.get(), 1);
450        let error = format_postgres_text(&value, &ColumnType::Record, None).unwrap_err();
451        assert_eq!(error.sqlstate(), Some("XX000"));
452        assert_eq!(error.to_string(), "cache lookup failed for type 16500");
453
454        // PostgreSQL also outputs a retained NULL field after its enum type is dropped.
455        let null = typed_row(vec![(Value::Null, 65_000)]);
456        assert_eq!(
457            format_postgres_text(&null, &ColumnType::Record, None).unwrap(),
458            "()"
459        );
460    }
461
462    #[test]
463    fn anonymous_record_output_bounds_temporary_memory_and_observes_both_cancellations() {
464        use uqa_core::{memory::MemoryBudget, CancellationToken};
465        let payload = "a".repeat(8192);
466        let value = typed_row(vec![
467            (Value::Float(f64::from(0.1_f32)), 700),
468            (Value::Str(payload.clone()), 25),
469        ]);
470        for limit in [0, 64, 1024, 65_536] {
471            let memory = MemoryBudget::new(limit);
472            let original = CancellationToken::new();
473            let invoking = CancellationToken::new();
474            let control = ProductionControl::new(&memory, &original, &invoking);
475            let output =
476                format_postgres_text_with_control(&value, &ColumnType::Record, None, &control);
477            if limit == 65_536 {
478                let text = output.unwrap();
479                assert_eq!(&**text, format!("(0.1,{payload})"));
480                assert!(memory.used() >= text.len());
481            } else {
482                assert_eq!(output.unwrap_err().sqlstate(), Some("53200"));
483            }
484            assert_eq!(memory.used(), 0);
485            for token in [&original, &invoking] {
486                token.cancel();
487                let error =
488                    format_postgres_text_with_control(&value, &ColumnType::Record, None, &control)
489                        .unwrap_err();
490                assert_eq!(error.sqlstate(), Some("57014"));
491                token.reset();
492                assert_eq!(memory.used(), 0);
493            }
494        }
495    }
496}