1use 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
19pub 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
40pub 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
56pub 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 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_whitespace() || matches!(c, ',' | '{' | '}' | '"' | '\\')
187 });
188 append_quoted(&mut text, &rendered, quoted, false)?;
189 }
190 }
191 }
192 text.push('}')?;
193 Ok(text.finish()?)
194}
195
196fn format_record(
197 fields: &[(String, Value)],
198 type_oid: u32,
199 catalog: Option<&dyn SQLValueCatalog>,
200 control: &ProductionControl<'_>,
201) -> Result<Produced<String>, SQLError> {
202 let descriptor = catalog
203 .ok_or_else(|| SQLError::Internal("composite type catalog is unavailable".into()))?
204 .value_composite_type(type_oid)?
205 .ok_or_else(|| SQLError::Routine {
206 sqlstate: "42704".into(),
207 message: format!("type with OID {type_oid} does not exist"),
208 })?;
209 let mut text = ProductionString::new(*control);
210 text.push('(')?;
211 for (index, (name, field)) in fields.iter().enumerate() {
212 control.check()?;
213 if index != 0 {
214 text.push(',')?;
215 }
216 if matches!(field, Value::Null) {
217 continue;
218 }
219 let rendered = match descriptor.attribute(name) {
220 Some((_, attribute)) => format_postgres_text_with_catalog_and_control(
221 field,
222 &attribute.ty,
223 catalog,
224 control,
225 )?,
226 None => format_postgres_text_with_catalog_and_control(
227 field,
228 &crate::type_resolution::value_type(field).unwrap_or(ColumnType::Text),
229 catalog,
230 control,
231 )?,
232 };
233 let quoted = rendered.is_empty()
234 || rendered
235 .chars()
236 .any(|c| c.is_ascii_whitespace() || matches!(c, ',' | '(' | ')' | '"' | '\\'));
237 append_quoted(&mut text, &rendered, quoted, true)?;
238 }
239 text.push(')')?;
240 Ok(text.finish()?)
241}
242
243fn append_quoted(
244 text: &mut ProductionString<'_>,
245 rendered: &str,
246 quoted: bool,
247 doubled: bool,
248) -> Result<(), SQLError> {
249 if quoted {
250 text.push('"')?;
251 }
252 for character in rendered.chars() {
253 if quoted && matches!(character, '"' | '\\') {
254 text.push(if doubled { character } else { '\\' })?;
255 }
256 text.push(character)?;
257 }
258 if quoted {
259 text.push('"')?;
260 }
261 Ok(())
262}
263
264fn array_parts<'a>(
265 array: &'a uqa_core::ArrayValue,
266 text: &mut ProductionString<'_>,
267 control: &ProductionControl<'_>,
268) -> Result<&'a [Value], SQLError> {
269 if !array.elements().is_empty() && array.lower_bounds().iter().any(|lower| *lower != 1) {
270 for (lower, length) in array.lower_bounds().iter().zip(array.dimensions()) {
271 let upper = i64::from(*lower) + *length as i64 - 1;
272 text.push_str(&control.format(format_args!("[{lower}:{upper}]"))?)?;
273 }
274 text.push('=')?;
275 }
276 Ok(array.elements())
277}
278
279#[cfg(test)]
280mod tests {
281 use super::*;
282 use std::cell::Cell;
283 use uqa_core::ArrayValue;
284
285 struct Catalog {
286 lookups: Cell<usize>,
287 }
288
289 fn domain() -> ColumnType {
290 ColumnType::Domain {
291 collation_oid: None,
292 schema: "public".into(),
293 name: "real_value".into(),
294 oid: 16_500,
295 array_oid: Some(16_501),
296 base: Box::new(ColumnType::Real),
297 }
298 }
299
300 impl EngineHook for Catalog {
301 fn nextval(&self, _: &str) -> Result<i64, SQLError> {
302 unreachable!()
303 }
304
305 fn currval(&self, _: &str) -> Result<i64, SQLError> {
306 unreachable!()
307 }
308
309 fn setval(&self, _: &str, _: i64, _: bool) -> Result<i64, SQLError> {
310 unreachable!()
311 }
312
313 fn resolve_type_oid(&self, oid: u32) -> Result<Option<ColumnType>, String> {
314 self.lookups.set(self.lookups.get() + 1);
315 Ok((oid == 16_500).then(domain))
316 }
317 }
318
319 #[test]
320 fn array_output_uses_original_catalog_element_and_reports_missing_identity() {
321 let catalog = Catalog {
322 lookups: Cell::new(0),
323 };
324 let value = Value::Array(
325 ArrayValue::try_new(vec![Value::Float(f64::from(0.1_f32)), Value::Null])
326 .unwrap()
327 .with_element_type_oid(Some(16_500)),
328 );
329 let changed = ColumnType::Array(Box::new(ColumnType::Text));
330 assert_eq!(
331 format_postgres_text(&value, &changed, Some(&catalog)).unwrap(),
332 "{0.1,NULL}"
333 );
334 assert_eq!(catalog.lookups.get(), 1);
335 assert_eq!(
336 format_postgres_text(
337 &value,
338 &ColumnType::Array(Box::new(domain())),
339 Some(&catalog),
340 )
341 .unwrap(),
342 "{0.1,NULL}"
343 );
344 assert_eq!(catalog.lookups.get(), 1);
345 let error = format_postgres_text(&value, &changed, None).unwrap_err();
346 assert_eq!(error.sqlstate(), Some("XX000"));
347 assert_eq!(error.to_string(), "cache lookup failed for type 16500");
348 }
349}