Skip to main content

uqa_sql/catalog/
node_tree.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! `PostgreSQL` node-tree text used by stored catalog expressions.
8
9use std::fmt;
10
11use crate::SQLError;
12
13mod read;
14pub use read::parse;
15pub mod deparse;
16pub mod expressions;
17mod values;
18pub use values::constant_with_source as constant;
19#[cfg(test)]
20pub(crate) use values::numeric::encode as encode_numeric_datum;
21pub(crate) use values::numeric::{
22    decode_with_control as decode_numeric_datum_with_control,
23    encode_with_control as encode_numeric_datum_with_control,
24};
25pub(crate) use values::temporal::{
26    decode as decode_temporal_datum, encode_inline as encode_temporal_datum_inline,
27};
28
29#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
30#[serde(deny_unknown_fields)]
31pub struct Node {
32    pub kind: String,
33    pub fields: Vec<(String, Field)>,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37#[serde(deny_unknown_fields)]
38pub enum Field {
39    Null,
40    Atom(String),
41    String(String),
42    /// A quoted `PostgreSQL` String value in a node list, rather than a bare field token.
43    StringValue(String),
44    Node(Node),
45    List(Vec<Field>),
46    /// `PostgreSQL` writes by-value Datums at machine-word width even when the declared type is narrower.
47    Datum {
48        length: usize,
49        bytes: Vec<u8>,
50    },
51}
52
53impl Node {
54    pub fn new(
55        kind: impl Into<String>,
56        fields: impl IntoIterator<Item = (&'static str, Field)>,
57    ) -> Self {
58        Self {
59            kind: kind.into(),
60            fields: fields
61                .into_iter()
62                .map(|(name, value)| (name.into(), value))
63                .collect(),
64        }
65    }
66
67    pub fn field(&self, name: &str) -> Result<&Field, SQLError> {
68        self.fields
69            .iter()
70            .find_map(|(field, value)| (field == name).then_some(value))
71            .ok_or_else(|| invalid(format!("missing {name} in {} node", self.kind)))
72    }
73
74    pub fn integer(&self, name: &str) -> Result<i64, SQLError> {
75        match self.field(name)? {
76            Field::Atom(value) => value
77                .parse()
78                .map_err(|_| invalid(format!("invalid integer field {name}"))),
79            _ => Err(invalid(format!("invalid integer field {name}"))),
80        }
81    }
82
83    pub fn boolean(&self, name: &str) -> Result<bool, SQLError> {
84        match self.field(name)? {
85            Field::Atom(value) if value == "true" => Ok(true),
86            Field::Atom(value) if value == "false" => Ok(false),
87            _ => Err(invalid(format!("invalid boolean field {name}"))),
88        }
89    }
90}
91
92impl From<i64> for Field {
93    fn from(value: i64) -> Self {
94        Self::Atom(value.to_string())
95    }
96}
97
98impl From<bool> for Field {
99    fn from(value: bool) -> Self {
100        Self::Atom(value.to_string())
101    }
102}
103
104impl From<Node> for Field {
105    fn from(value: Node) -> Self {
106        Self::Node(value)
107    }
108}
109
110impl fmt::Display for Node {
111    fn fmt(&self, output: &mut fmt::Formatter<'_>) -> fmt::Result {
112        write!(output, "{{{}", self.kind)?;
113        for (name, value) in &self.fields {
114            write!(output, " :{name} {value}")?;
115        }
116        output.write_str("}")
117    }
118}
119
120impl fmt::Display for Field {
121    fn fmt(&self, output: &mut fmt::Formatter<'_>) -> fmt::Result {
122        match self {
123            Self::Null => output.write_str("<>"),
124            Self::Atom(value) => output.write_str(value),
125            Self::String(value) => write_token(output, value),
126            Self::StringValue(value) => {
127                output.write_str("\"")?;
128                if !value.is_empty() {
129                    write_token(output, value)?;
130                }
131                output.write_str("\"")
132            }
133            Self::Node(node) => node.fmt(output),
134            Self::List(values) => {
135                output.write_str("(")?;
136                for (index, value) in values.iter().enumerate() {
137                    if index != 0 {
138                        output.write_str(" ")?;
139                    }
140                    value.fmt(output)?;
141                }
142                output.write_str(")")
143            }
144            Self::Datum { length, bytes } => {
145                write!(output, "{length} [")?;
146                for byte in bytes {
147                    // PostgreSQL promotes native C char, whose signedness is platform-specific.
148                    write!(output, " {}", std::ffi::c_char::from_ne_bytes([*byte]))?;
149                }
150                output.write_str(" ]")
151            }
152        }
153    }
154}
155
156fn write_token(output: &mut fmt::Formatter<'_>, value: &str) -> fmt::Result {
157    if value.is_empty() {
158        return output.write_str("\"\"");
159    }
160    let mut bytes = value.bytes();
161    let first = bytes.next().expect("nonempty token");
162    if matches!(first, b'<' | b'"')
163        || first.is_ascii_digit()
164        || (matches!(first, b'+' | b'-')
165            && bytes
166                .next()
167                .is_some_and(|byte| byte.is_ascii_digit() || byte == b'.'))
168    {
169        output.write_str("\\")?;
170    }
171    for character in value.chars() {
172        if matches!(character, ' ' | '\n' | '\t' | '(' | ')' | '{' | '}' | '\\') {
173            output.write_str("\\")?;
174        }
175        write!(output, "{character}")?;
176    }
177    Ok(())
178}
179
180pub(super) fn invalid(message: impl Into<String>) -> SQLError {
181    SQLError::Routine {
182        sqlstate: "XX000".into(),
183        message: message.into(),
184    }
185}
186
187#[cfg(test)]
188mod tests;