sql-values 0.8.0

SQL values, with PostgreSQL's value rules beside readers of the text PostgreSQL, MySQL and SQLite emit
Documentation
//! PostgreSQL's `get_const_expr` spelling of type-output text.

use core::fmt::{self, Write};

use super::BuiltinType;

/// The `showtype` argument of PostgreSQL's `get_const_expr`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShowType {
    /// Omit the type and collation because the enclosing coercion supplies them.
    Never,
    /// Label constants whose literal syntax does not preserve their type and modifier.
    IfNeeded,
    /// Label every constant, including booleans and positive integers.
    Always,
}

/// Session quoting and the caller-resolved nondefault collation of a `Const`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConstExprContext<'a> {
    /// Whether backslashes are literal characters in ordinary SQL strings.
    pub standard_conforming_strings: bool,
    /// An already SQL-quoted, optionally qualified collation name, only when nondefault for the type.
    pub collation: Option<&'a str>,
}

impl Default for ConstExprContext<'_> {
    fn default() -> Self {
        Self {
            standard_conforming_strings: true,
            collation: None,
        }
    }
}

/// A borrowed, allocation-free `get_const_expr` writer over a type's output text.
///
/// The caller supplies output for the exact type and modifier under its session settings.
/// [`super::PgValue::output`] supplies setting-independent output, while its `Display` uses
/// `DateStyle` `ISO`, `TimeZone` `UTC` and `IntervalStyle` `postgres`.
///
/// ```
/// use sql_values::postgres::{BuiltinType, ConstExpr, PgValue, ShowType};
///
/// let output = PgValue::Integer(-1).output().unwrap().to_string();
/// let constant = ConstExpr::new(Some(&output), BuiltinType::Integer, ShowType::IfNeeded);
/// assert_eq!(constant.to_string(), "'-1'::integer");
/// assert_eq!(ConstExpr::new(None, BuiltinType::Text, ShowType::IfNeeded).to_string(), "NULL::text");
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ConstExpr<'a> {
    output: Option<&'a str>,
    target: BuiltinType,
    show_type: ShowType,
    context: ConstExprContext<'a>,
}

impl<'a> ConstExpr<'a> {
    /// Wraps type-output text, or `None` for a typed `NULL`, with default session quoting.
    #[must_use]
    pub fn new(output: Option<&'a str>, target: BuiltinType, show_type: ShowType) -> Self {
        Self {
            output,
            target,
            show_type,
            context: ConstExprContext::default(),
        }
    }

    /// Supplies the session quoting and nondefault collation for this constant.
    #[must_use]
    pub const fn with_context(mut self, context: ConstExprContext<'a>) -> Self {
        self.context = context;
        self
    }

    /// Reports whether this constant's spelling includes a type label.
    ///
    /// ```
    /// use sql_values::postgres::{BuiltinType, ConstExpr, ShowType};
    ///
    /// let positive = ConstExpr::new(Some("1"), BuiltinType::Integer, ShowType::IfNeeded);
    /// let negative = ConstExpr::new(Some("-1"), BuiltinType::Integer, ShowType::IfNeeded);
    /// assert!(!positive.needs_type_label());
    /// assert!(negative.needs_type_label());
    /// ```
    #[must_use]
    pub fn needs_type_label(&self) -> bool {
        self.decoration().1
    }

    /// Returns whether the literal is quoted and whether its type is labelled.
    fn decoration(&self) -> (bool, bool) {
        let (quoted, needed) = match self.output {
            Some(output) => match self.target {
                BuiltinType::Boolean => (false, false),
                BuiltinType::Integer if !output.starts_with('-') => (false, false),
                BuiltinType::Numeric(modifier)
                    if output.as_bytes().first().is_some_and(u8::is_ascii_digit)
                        && output.contains(['e', 'E', '.']) =>
                {
                    (false, modifier.is_some())
                }
                _ => (true, self.target != BuiltinType::Unknown),
            },
            None => (false, true),
        };
        (
            quoted,
            match self.show_type {
                ShowType::Never => false,
                ShowType::IfNeeded => needed,
                ShowType::Always => true,
            },
        )
    }
}

impl fmt::Display for ConstExpr<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (quoted, needs_label) = self.decoration();
        if let Some(output) = self.output {
            if quoted {
                quote_literal(formatter, output, self.context.standard_conforming_strings)?;
            } else if self.target == BuiltinType::Boolean {
                formatter.write_str(if output == "t" { "true" } else { "false" })?;
            } else {
                formatter.write_str(output)?;
            }
        } else {
            formatter.write_str("NULL")?;
        }
        if needs_label {
            write!(formatter, "::{}", self.target)?;
        }
        if self.show_type != ShowType::Never
            && let Some(collation) = self.context.collation
        {
            write!(formatter, " COLLATE {collation}")?;
        }
        Ok(())
    }
}

/// Quotes text according to `standard_conforming_strings`, as `simple_quote_literal` does.
fn quote_literal(
    formatter: &mut fmt::Formatter<'_>,
    output: &str,
    standard_strings: bool,
) -> fmt::Result {
    formatter.write_char('\'')?;
    let mut start = 0;
    for (index, character) in output.char_indices() {
        if character == '\'' || (character == '\\' && !standard_strings) {
            formatter.write_str(&output[start..index])?;
            formatter.write_char(character)?;
            start = index;
        }
    }
    formatter.write_str(&output[start..])?;
    formatter.write_char('\'')
}