Skip to main content

uqa_sql/catalog/
expression_text.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Stable SQL text rendering for cataloged expressions.
8
9use std::fmt::Write as _;
10
11use crate::ast::Expr;
12use crate::SQLError;
13use uqa_core::Value;
14
15pub fn default_expr_text(expr: Option<&Expr>) -> Result<Value, SQLError> {
16    expr.map_or(Ok(Value::Null), |expr| {
17        schema_expr_text(expr).map(Value::Str)
18    })
19}
20
21#[expect(
22    clippy::too_many_lines,
23    reason = "preserves catalog column and OID order"
24)]
25pub fn schema_expr_text(expr: &Expr) -> Result<String, SQLError> {
26    if let Some(clause) = crate::catalog::collations::expression::ast_clause(expr)? {
27        return Ok(format!(
28            "({} COLLATE {})",
29            schema_expr_text(clause.argument)?,
30            clause.executable_name()?
31        ));
32    }
33    Ok(match expr {
34        Expr::Star => "*".into(),
35        Expr::QualifiedStar(qualifier) => format!("{qualifier}.*"),
36        Expr::Default => "DEFAULT".into(),
37        Expr::Column(name) => name.to_string(),
38        Expr::QualifiedColumn {
39            qualifier, column, ..
40        } => format!("{qualifier}.{column}"),
41        Expr::InternalColumn(column) => {
42            unreachable!("executor-only column {column:?} reached catalog SQL rendering")
43        }
44        Expr::Literal(value) => schema_literal_text(value)?,
45        Expr::TypedLiteral { value, ty, .. } => format!("({})::{ty}", schema_literal_text(value)?),
46        Expr::RetainedLiteral(literal) => schema_expr_text(&literal.materialize()?)?,
47        Expr::Param(index) => format!("${index}"),
48        Expr::Func {
49            name,
50            binding,
51            args,
52            distinct,
53            order_by,
54            order_syntax,
55            filter,
56            ..
57        } => {
58            if let Some(crate::ast::FunctionDispatch::Pattern { operator, .. }) =
59                binding.as_ref().and_then(|binding| binding.dispatch)
60            {
61                return crate::render::pattern_sql(operator, args, schema_expr_text);
62            }
63            if binding
64                .as_ref()
65                .and_then(|binding| binding.dispatch)
66                .is_some_and(crate::ast::FunctionDispatch::is_concatenation)
67            {
68                let [left, right] = args.as_slice() else {
69                    return Err(SQLError::Internal("invalid concatenation operands".into()));
70                };
71                return Ok(format!(
72                    "({} || {})",
73                    schema_expr_text(left)?,
74                    schema_expr_text(right)?
75                ));
76            }
77            if *order_syntax == crate::ast::FunctionCallSyntax::Extract {
78                let (field, source) = crate::render::function_syntax::extract_fields(args)?;
79                return Ok(format!(
80                    "EXTRACT({field} FROM {})",
81                    schema_expr_text(source)?
82                ));
83            }
84            if let Some(crate::ast::FunctionDispatch::NumericOperator(operator)) =
85                binding.as_ref().and_then(|binding| binding.dispatch)
86            {
87                match args.as_slice() {
88                    [argument] if operator.arity() == 1 => {
89                        return Ok(format!(
90                            "({} {})",
91                            operator.symbol(),
92                            schema_expr_text(argument)?
93                        ))
94                    }
95                    [left, right] if operator.arity() == 2 => {
96                        return Ok(format!(
97                            "({} {} {})",
98                            schema_expr_text(left)?,
99                            operator.symbol(),
100                            schema_expr_text(right)?
101                        ))
102                    }
103                    _ => {}
104                }
105            }
106            let mut rendered_args = args
107                .iter()
108                .map(schema_expr_text)
109                .collect::<Result<Vec<_>, SQLError>>()?
110                .join(", ");
111            if *distinct {
112                rendered_args = format!("DISTINCT {rendered_args}");
113            }
114            let name = crate::render::function_syntax::ordinary_function_name(name);
115            let mut rendered = format!("{name}({rendered_args})");
116            if !order_by.is_empty() {
117                let order = order_by
118                    .iter()
119                    .map(|order| {
120                        let direction = if order.descending { " DESC" } else { "" };
121                        let nulls = match order.nulls {
122                            Some(crate::ast::NullsOrder::First) => " NULLS FIRST",
123                            Some(crate::ast::NullsOrder::Last) => " NULLS LAST",
124                            None => "",
125                        };
126                        Ok(format!(
127                            "{}{direction}{nulls}",
128                            schema_expr_text(&order.expr)?
129                        ))
130                    })
131                    .collect::<Result<Vec<_>, SQLError>>()?
132                    .join(", ");
133                if *order_syntax == crate::ast::FunctionOrderSyntax::WithinGroup {
134                    write!(&mut rendered, " WITHIN GROUP (ORDER BY {order})")
135                        .expect("writing to a String cannot fail");
136                } else {
137                    rendered.pop();
138                    if !rendered_args.is_empty() {
139                        rendered.push(' ');
140                    }
141                    write!(&mut rendered, "ORDER BY {order})")
142                        .expect("writing to a String cannot fail");
143                }
144            }
145            if let Some(filter) = filter {
146                write!(
147                    &mut rendered,
148                    " FILTER (WHERE {})",
149                    schema_expr_text(filter)?
150                )
151                .expect("writing to a String cannot fail");
152            }
153            rendered
154        }
155        Expr::Array(items) => format!(
156            "ARRAY[{}]",
157            items
158                .iter()
159                .map(schema_expr_text)
160                .collect::<Result<Vec<_>, SQLError>>()?
161                .join(", ")
162        ),
163        Expr::CompositeRow { items, binding } => format!(
164            "ROW({})::{}",
165            items
166                .iter()
167                .map(schema_expr_text)
168                .collect::<Result<Vec<_>, SQLError>>()?
169                .join(", "),
170            binding.ty
171        ),
172        Expr::Row(items) => format!(
173            "ROW({})",
174            items
175                .iter()
176                .map(schema_expr_text)
177                .collect::<Result<Vec<_>, SQLError>>()?
178                .join(", ")
179        ),
180        Expr::Binary { op, lhs, rhs } => format!(
181            "({} {} {})",
182            schema_expr_text(lhs)?,
183            match op {
184                crate::ast::BinaryOp::Equal => "=",
185                crate::ast::BinaryOp::NotEqual => "<>",
186                crate::ast::BinaryOp::Less => "<",
187                crate::ast::BinaryOp::LessEqual => "<=",
188                crate::ast::BinaryOp::Greater => ">",
189                crate::ast::BinaryOp::GreaterEqual => ">=",
190                crate::ast::BinaryOp::Add => "+",
191                crate::ast::BinaryOp::Subtract => "-",
192                crate::ast::BinaryOp::Multiply => "*",
193                crate::ast::BinaryOp::Divide => "/",
194            },
195            schema_expr_text(rhs)?
196        ),
197        Expr::Not(inner) => format!("(NOT {})", schema_expr_text(inner)?),
198        Expr::UnaryMinus(inner) => format!("(-{})", schema_expr_text(inner)?),
199        Expr::And(items) => format!(
200            "({})",
201            items
202                .iter()
203                .map(schema_expr_text)
204                .collect::<Result<Vec<_>, SQLError>>()?
205                .join(" AND ")
206        ),
207        Expr::Or(items) => format!(
208            "({})",
209            items
210                .iter()
211                .map(schema_expr_text)
212                .collect::<Result<Vec<_>, SQLError>>()?
213                .join(" OR ")
214        ),
215        Expr::IsNull { expr, negated } => format!(
216            "({} IS {}NULL)",
217            schema_expr_text(expr)?,
218            if *negated { "NOT " } else { "" }
219        ),
220        Expr::Between { expr, low, high } => format!(
221            "({} BETWEEN {} AND {})",
222            schema_expr_text(expr)?,
223            schema_expr_text(low)?,
224            schema_expr_text(high)?
225        ),
226        Expr::InList {
227            expr,
228            list,
229            negated,
230        } => format!(
231            "({} {}IN ({}))",
232            schema_expr_text(expr)?,
233            if *negated { "NOT " } else { "" },
234            list.iter()
235                .map(schema_expr_text)
236                .collect::<Result<Vec<_>, SQLError>>()?
237                .join(", ")
238        ),
239        Expr::WindowCall {
240            name, args, filter, ..
241        } => format!(
242            "{}({}){} OVER (...)",
243            name,
244            args.iter()
245                .map(schema_expr_text)
246                .collect::<Result<Vec<_>, SQLError>>()?
247                .join(", "),
248            filter
249                .as_deref()
250                .map(schema_expr_text)
251                .transpose()?
252                .map(|filter| format!(" FILTER (WHERE {filter})"))
253                .unwrap_or_default()
254        ),
255        Expr::Case {
256            base,
257            when,
258            else_branch,
259        } => {
260            let mut rendered = "CASE".to_string();
261            if let Some(base) = base {
262                rendered.push(' ');
263                rendered.push_str(&schema_expr_text(base)?);
264            }
265            for (condition, result) in when {
266                write!(
267                    &mut rendered,
268                    " WHEN {} THEN {}",
269                    schema_expr_text(condition)?,
270                    schema_expr_text(result)?
271                )
272                .expect("writing to a String cannot fail");
273            }
274            if let Some(else_branch) = else_branch {
275                write!(&mut rendered, " ELSE {}", schema_expr_text(else_branch)?)
276                    .expect("writing to a String cannot fail");
277            }
278            rendered.push_str(" END");
279            rendered
280        }
281        Expr::Cast { expr, ty, .. } => format!("({})::{ty}", schema_expr_text(expr)?),
282        Expr::ScalarSubquery(body) => format!("({body:?})"),
283        Expr::Exists { body, negated } => {
284            format!("{}EXISTS ({body:?})", if *negated { "NOT " } else { "" })
285        }
286        Expr::InSubquery {
287            expr,
288            body,
289            negated,
290        } => format!(
291            "({} {}IN ({body:?}))",
292            schema_expr_text(expr)?,
293            if *negated { "NOT " } else { "" }
294        ),
295    })
296}
297
298fn schema_literal_text(value: &Value) -> Result<String, SQLError> {
299    Ok(match value {
300        Value::Null => "NULL".into(),
301        Value::Void => "''::void".into(),
302        Value::Bool(value) => if *value { "true" } else { "false" }.into(),
303        Value::Int(value) => value.to_string(),
304        Value::Float(value) if value.is_finite() => value.to_string(),
305        Value::Float(value) => format!("'{value}'::double precision"),
306        Value::Str(value) | Value::FixedChar(value) => {
307            format!("'{}'", value.replace('\'', "''"))
308        }
309        Value::BitString(_) => format!("B'{}'", crate::expr::value_to_string(value)?),
310        Value::Bytes(value) => {
311            let mut hex = String::new();
312            for byte in value {
313                write!(&mut hex, "{byte:02x}").expect("writing to a String cannot fail");
314            }
315            format!("'\\x{hex}'::bytea")
316        }
317        Value::Temporal(value) => format!("'{value:?}'"),
318        Value::Decimal(value) => format!("{value:?}"),
319        Value::Json(value) => format!("'{}'::json", value.replace('\'', "''")),
320        Value::JsonB(value) => format!("'{}'::jsonb", value.replace('\'', "''")),
321        Value::Enum(value) => return Err(crate::expr::catalog_output_required(value)),
322        Value::Datum(value) => return schema_literal_text(&crate::expr::datums::read(value)?),
323        Value::LegacyVector(vector) => crate::render::legacy_vector_expression(vector)
324            .expect("stored SQL vector has SQL-produced bounds"),
325        Value::Array(array)
326            if array
327                .lower_bounds()
328                .iter()
329                .any(|lower_bound| *lower_bound != 1) =>
330        {
331            format!(
332                "'{}'",
333                crate::expr::array_value_to_string(array)?.replace('\'', "''")
334            )
335        }
336        Value::Array(array) => format!(
337            "ARRAY[{}]",
338            array
339                .elements()
340                .iter()
341                .map(schema_literal_text)
342                .collect::<Result<Vec<_>, SQLError>>()?
343                .join(", ")
344        ),
345        Value::List(values) => format!(
346            "ARRAY[{}]",
347            values
348                .iter()
349                .map(schema_literal_text)
350                .collect::<Result<Vec<_>, SQLError>>()?
351                .join(", ")
352        ),
353        Value::Row(values) => format!(
354            "ROW({})",
355            values
356                .iter()
357                .map(schema_literal_text)
358                .collect::<Result<Vec<_>, SQLError>>()?
359                .join(", ")
360        ),
361        Value::Record(fields) => format!(
362            "ROW({})",
363            fields
364                .iter()
365                .map(|(_, value)| schema_literal_text(value))
366                .collect::<Result<Vec<_>, SQLError>>()?
367                .join(", ")
368        ),
369        Value::Map(value) => format!(
370            "'{}'::jsonb",
371            serde_json::to_string(value)
372                .expect("serializing an in-memory Value map cannot fail")
373                .replace('\'', "''")
374        ),
375    })
376}