Skip to main content

sql_values/postgres/
const_expr.rs

1//! PostgreSQL's `get_const_expr` spelling of type-output text.
2
3use core::fmt::{self, Write};
4
5use super::BuiltinType;
6
7/// The `showtype` argument of PostgreSQL's `get_const_expr`.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum ShowType {
10    /// Omit the type and collation because the enclosing coercion supplies them.
11    Never,
12    /// Label constants whose literal syntax does not preserve their type and modifier.
13    IfNeeded,
14    /// Label every constant, including booleans and positive integers.
15    Always,
16}
17
18/// Session quoting and the caller-resolved nondefault collation of a `Const`.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct ConstExprContext<'a> {
21    /// Whether backslashes are literal characters in ordinary SQL strings.
22    pub standard_conforming_strings: bool,
23    /// An already SQL-quoted, optionally qualified collation name, only when nondefault for the type.
24    pub collation: Option<&'a str>,
25}
26
27impl Default for ConstExprContext<'_> {
28    fn default() -> Self {
29        Self {
30            standard_conforming_strings: true,
31            collation: None,
32        }
33    }
34}
35
36/// A borrowed, allocation-free `get_const_expr` writer over a type's output text.
37///
38/// The caller supplies output for the exact type and modifier under its session settings.
39/// [`super::PgValue::output`] supplies setting-independent output, while its `Display` uses
40/// `DateStyle` `ISO`, `TimeZone` `UTC` and `IntervalStyle` `postgres`.
41///
42/// ```
43/// use sql_values::postgres::{BuiltinType, ConstExpr, PgValue, ShowType};
44///
45/// let output = PgValue::Integer(-1).output().unwrap().to_string();
46/// let constant = ConstExpr::new(Some(&output), BuiltinType::Integer, ShowType::IfNeeded);
47/// assert_eq!(constant.to_string(), "'-1'::integer");
48/// assert_eq!(ConstExpr::new(None, BuiltinType::Text, ShowType::IfNeeded).to_string(), "NULL::text");
49/// ```
50#[derive(Debug, Clone, Copy)]
51pub struct ConstExpr<'a> {
52    output: Option<&'a str>,
53    target: BuiltinType,
54    show_type: ShowType,
55    context: ConstExprContext<'a>,
56}
57
58impl<'a> ConstExpr<'a> {
59    /// Wraps type-output text, or `None` for a typed `NULL`, with default session quoting.
60    #[must_use]
61    pub fn new(output: Option<&'a str>, target: BuiltinType, show_type: ShowType) -> Self {
62        Self {
63            output,
64            target,
65            show_type,
66            context: ConstExprContext::default(),
67        }
68    }
69
70    /// Supplies the session quoting and nondefault collation for this constant.
71    #[must_use]
72    pub const fn with_context(mut self, context: ConstExprContext<'a>) -> Self {
73        self.context = context;
74        self
75    }
76
77    /// Reports whether this constant's spelling includes a type label.
78    ///
79    /// ```
80    /// use sql_values::postgres::{BuiltinType, ConstExpr, ShowType};
81    ///
82    /// let positive = ConstExpr::new(Some("1"), BuiltinType::Integer, ShowType::IfNeeded);
83    /// let negative = ConstExpr::new(Some("-1"), BuiltinType::Integer, ShowType::IfNeeded);
84    /// assert!(!positive.needs_type_label());
85    /// assert!(negative.needs_type_label());
86    /// ```
87    #[must_use]
88    pub fn needs_type_label(&self) -> bool {
89        self.decoration().1
90    }
91
92    /// Returns whether the literal is quoted and whether its type is labelled.
93    fn decoration(&self) -> (bool, bool) {
94        let (quoted, needed) = match self.output {
95            Some(output) => match self.target {
96                BuiltinType::Boolean => (false, false),
97                BuiltinType::Integer if !output.starts_with('-') => (false, false),
98                BuiltinType::Numeric(modifier)
99                    if output.as_bytes().first().is_some_and(u8::is_ascii_digit)
100                        && output.contains(['e', 'E', '.']) =>
101                {
102                    (false, modifier.is_some())
103                }
104                _ => (true, self.target != BuiltinType::Unknown),
105            },
106            None => (false, true),
107        };
108        (
109            quoted,
110            match self.show_type {
111                ShowType::Never => false,
112                ShowType::IfNeeded => needed,
113                ShowType::Always => true,
114            },
115        )
116    }
117}
118
119impl fmt::Display for ConstExpr<'_> {
120    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
121        let (quoted, needs_label) = self.decoration();
122        if let Some(output) = self.output {
123            if quoted {
124                quote_literal(formatter, output, self.context.standard_conforming_strings)?;
125            } else if self.target == BuiltinType::Boolean {
126                formatter.write_str(if output == "t" { "true" } else { "false" })?;
127            } else {
128                formatter.write_str(output)?;
129            }
130        } else {
131            formatter.write_str("NULL")?;
132        }
133        if needs_label {
134            write!(formatter, "::{}", self.target)?;
135        }
136        if self.show_type != ShowType::Never
137            && let Some(collation) = self.context.collation
138        {
139            write!(formatter, " COLLATE {collation}")?;
140        }
141        Ok(())
142    }
143}
144
145/// Quotes text according to `standard_conforming_strings`, as `simple_quote_literal` does.
146fn quote_literal(
147    formatter: &mut fmt::Formatter<'_>,
148    output: &str,
149    standard_strings: bool,
150) -> fmt::Result {
151    formatter.write_char('\'')?;
152    let mut start = 0;
153    for (index, character) in output.char_indices() {
154        if character == '\'' || (character == '\\' && !standard_strings) {
155            formatter.write_str(&output[start..index])?;
156            formatter.write_char(character)?;
157            start = index;
158        }
159    }
160    formatter.write_str(&output[start..])?;
161    formatter.write_char('\'')
162}