Skip to main content

sql_splitter/render/
sql_string.rs

1//! Borrowed, allocation-free SQL string-literal rendering.
2
3use std::fmt::{self, Display, Formatter, Write};
4
5use crate::parser::SqlDialect;
6
7/// A borrowed value that renders as a dialect-correct, quoted SQL string
8/// literal via [`Display`], without allocating an intermediate escaped
9/// [`String`].
10pub struct SqlString<'a> {
11    dialect: SqlDialect,
12    value: &'a str,
13}
14
15impl<'a> SqlString<'a> {
16    /// Borrow `value` for rendering as a `dialect`-correct quoted literal.
17    pub fn new(dialect: SqlDialect, value: &'a str) -> Self {
18        Self { dialect, value }
19    }
20}
21
22impl Display for SqlString<'_> {
23    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
24        // In PostgreSQL a backslash is only a literal character under
25        // `standard_conforming_strings = on`; with it off, `\'` escapes the
26        // quote and a value ending in a backslash breaks out of the literal.
27        // Render any backslash-bearing value as an `E'...'` escape string with
28        // doubled backslashes so it is unambiguous regardless of that server
29        // setting. (SQLite/MSSQL never treat a backslash specially; MySQL's
30        // default mode already backslash-escapes.)
31        if self.dialect == SqlDialect::Postgres && self.value.contains('\\') {
32            f.write_str("E'")?;
33            for ch in self.value.chars() {
34                match ch {
35                    '\\' => f.write_str("\\\\")?,
36                    '\'' => f.write_str("''")?,
37                    ch => f.write_char(ch)?,
38                }
39            }
40            return f.write_str("'");
41        }
42        if self.dialect == SqlDialect::Mssql {
43            f.write_str("N")?;
44        }
45        f.write_str("'")?;
46        for ch in self.value.chars() {
47            match (self.dialect, ch) {
48                (SqlDialect::MySql, '\\') => f.write_str("\\\\")?,
49                (SqlDialect::MySql, '\'') => f.write_str("\\'")?,
50                (SqlDialect::MySql, '\n') => f.write_str("\\n")?,
51                (SqlDialect::MySql, '\r') => f.write_str("\\r")?,
52                (SqlDialect::MySql, '\t') => f.write_str("\\t")?,
53                (_, '\'') => f.write_str("''")?,
54                (_, ch) => f.write_char(ch)?,
55            }
56        }
57        f.write_str("'")
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn sql_string_escapes_each_dialect_without_intermediate_contract_changes() {
67        let input = "a'b\\c\n\r\t";
68        assert_eq!(
69            SqlString::new(SqlDialect::MySql, input).to_string(),
70            "'a\\'b\\\\c\\n\\r\\t'"
71        );
72        // The backslash forces an E'' escape string with a doubled backslash.
73        assert_eq!(
74            SqlString::new(SqlDialect::Postgres, input).to_string(),
75            "E'a''b\\\\c\n\r\t'"
76        );
77        assert_eq!(
78            SqlString::new(SqlDialect::Sqlite, input).to_string(),
79            "'a''b\\c\n\r\t'"
80        );
81        assert_eq!(
82            SqlString::new(SqlDialect::Mssql, input).to_string(),
83            "N'a''b\\c\n\r\t'"
84        );
85    }
86
87    #[test]
88    fn postgres_backslash_values_are_standard_conforming_independent() {
89        // A value ending in a backslash must not render as the ambiguous `'a\'`,
90        // which breaks out of the literal when standard_conforming_strings is
91        // off. Use an E'' escape string with a doubled backslash instead.
92        assert_eq!(
93            SqlString::new(SqlDialect::Postgres, "a\\").to_string(),
94            "E'a\\\\'"
95        );
96        assert_eq!(
97            SqlString::new(SqlDialect::Postgres, "x'y\\z").to_string(),
98            "E'x''y\\\\z'"
99        );
100        // No backslash: unchanged plain literal.
101        assert_eq!(
102            SqlString::new(SqlDialect::Postgres, "x'y").to_string(),
103            "'x''y'"
104        );
105    }
106
107    #[test]
108    fn sql_string_leaves_plain_text_untouched() {
109        assert_eq!(
110            SqlString::new(SqlDialect::MySql, "plain").to_string(),
111            "'plain'"
112        );
113    }
114}