Skip to main content

mariadb_cli/sql/
ident.rs

1//! Safe quoting of an object name.
2//!
3//! Introspection builds statements around names the caller supplies: a schema,
4//! a table, a column. A name is not a value and cannot travel as a parameter,
5//! so it is pasted into the text. This module is the only sanctioned way to do
6//! that, and it refuses a name it cannot quote instead of producing text that
7//! would change what the statement means.
8
9use crate::error::{Failure, Result};
10use std::fmt::Write as _;
11
12/// The longest object name this server accepts, in characters.
13pub const MAX_IDENTIFIER_CHARS: usize = 64;
14
15/// The delimiter this server uses around an object name.
16const DELIMITER: char = '`';
17
18/// Quotes one object name.
19///
20/// The delimiter inside the name is doubled, which is how this server escapes
21/// it. The result always begins and ends with the delimiter, so it is a single
22/// name whatever it contains.
23///
24/// # Examples
25///
26/// An ordinary name comes back wrapped, and one carrying the delimiter comes
27/// back with it doubled, which is what keeps it a single name:
28///
29/// ```
30/// use mariadb_cli::sql::ident::quote;
31///
32/// assert_eq!(quote("pedidos")?, "`pedidos`");
33/// assert_eq!(quote("a`b")?, "`a``b`");
34/// # Ok::<(), mariadb_cli::error::Failure>(())
35/// ```
36///
37/// A name that cannot be quoted is refused rather than mangled:
38///
39/// ```
40/// use mariadb_cli::sql::ident::quote;
41///
42/// assert!(quote("").is_err());
43/// assert!(quote("linha\nnova").is_err());
44/// ```
45///
46/// # Errors
47///
48/// Returns a validation failure when the name is empty, longer than the server
49/// accepts, or carries a control character. A control character is refused
50/// rather than escaped because it has no escaped form here and would travel to
51/// the server as itself.
52pub fn quote(name: &str) -> Result<String> {
53    refuse_unquotable(name)?;
54
55    let mut quoted = String::with_capacity(name.len() + 2);
56    quoted.push(DELIMITER);
57    for character in name.chars() {
58        if character == DELIMITER {
59            quoted.push(DELIMITER);
60        }
61        quoted.push(character);
62    }
63    quoted.push(DELIMITER);
64    Ok(quoted)
65}
66
67/// Quotes a name made of several parts, such as a schema and a table.
68///
69/// Each part is quoted on its own and the parts are joined by a dot, so a dot
70/// inside a part stays inside that part.
71///
72/// # Examples
73///
74/// A schema and a table join with a dot between them, and a dot written inside
75/// one part stays inside that part instead of splitting it:
76///
77/// ```
78/// use mariadb_cli::sql::ident::quote_qualified;
79///
80/// assert_eq!(quote_qualified(&["loja", "pedidos"])?, "`loja`.`pedidos`");
81/// assert_eq!(quote_qualified(&["um.dois"])?, "`um.dois`");
82/// # Ok::<(), mariadb_cli::error::Failure>(())
83/// ```
84///
85/// # Errors
86///
87/// Returns a validation failure when the list is empty or any part is refused
88/// by [`quote`].
89pub fn quote_qualified<S: AsRef<str>>(parts: &[S]) -> Result<String> {
90    if parts.is_empty() {
91        return Err(
92            Failure::validation("ident.empty_path", "the object name has no parts")
93                .with_hint("give at least one name part"),
94        );
95    }
96
97    let mut joined = String::new();
98    for (position, part) in parts.iter().enumerate() {
99        if position > 0 {
100            joined.push('.');
101        }
102        // The buffer is a String, whose write never fails; the result is
103        // consumed so no failure path is discarded silently.
104        let quoted = quote(part.as_ref())?;
105        let _ = write!(joined, "{quoted}");
106    }
107    Ok(joined)
108}
109
110/// Refuses a name that cannot be quoted safely.
111fn refuse_unquotable(name: &str) -> Result<()> {
112    if name.is_empty() {
113        return Err(
114            Failure::validation("ident.empty", "the object name is empty")
115                .with_hint("give a name with at least one character"),
116        );
117    }
118
119    if let Some(offset) = name
120        .char_indices()
121        .find_map(|(offset, character)| character.is_control().then_some(offset))
122    {
123        return Err(Failure::validation(
124            "ident.control_character",
125            format!("the object name carries a control character at byte {offset}"),
126        )
127        .with_detail("detail", offset.to_string())
128        .with_hint("remove the control character from the name"));
129    }
130
131    let length = name.chars().count();
132    if length > MAX_IDENTIFIER_CHARS {
133        return Err(Failure::validation(
134            "ident.too_long",
135            format!(
136                "the object name has {length} characters and this server accepts {MAX_IDENTIFIER_CHARS}"
137            ),
138        )
139        .with_detail("detail", format!("{length} > {MAX_IDENTIFIER_CHARS}"))
140        .with_hint("shorten the name"));
141    }
142
143    Ok(())
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn a_plain_name_is_wrapped_in_the_delimiter() {
152        assert_eq!(quote("users").expect("plain name"), "`users`");
153    }
154
155    #[test]
156    fn a_reserved_word_is_a_usable_name_once_quoted() {
157        assert_eq!(quote("select").expect("reserved word"), "`select`");
158        assert_eq!(quote("order").expect("reserved word"), "`order`");
159    }
160
161    /// FR-075. A name carrying the delimiter never alters the structure of the
162    /// statement it is pasted into: the delimiter is doubled, so what looks
163    /// like an escape lands inside the quoted name and stays a name.
164    ///
165    /// A name carrying the delimiter is the whole point of this module: without
166    /// doubling it, the name would close early and the rest would become code.
167    #[test]
168    fn the_delimiter_inside_the_name_is_doubled() {
169        assert_eq!(quote("a`b").expect("delimiter inside"), "`a``b`");
170        assert_eq!(
171            quote("t` ; DROP TABLE users; -- ").expect("delimiter inside"),
172            "`t`` ; DROP TABLE users; -- `"
173        );
174    }
175
176    #[test]
177    fn a_name_with_a_separator_or_a_quote_stays_one_name() {
178        assert_eq!(quote("a;b").expect("separator"), "`a;b`");
179        assert_eq!(quote("a'b").expect("quote"), "`a'b`");
180        assert_eq!(quote("a\"b").expect("quote"), "`a\"b`");
181    }
182
183    #[test]
184    fn a_name_with_a_dot_stays_one_name() {
185        assert_eq!(quote("a.b").expect("dot"), "`a.b`");
186    }
187
188    /// FR-075. A name that has no quoted form is refused rather than sent, and
189    /// the refusal is the published validation number.
190    #[test]
191    fn a_name_with_a_control_character_is_refused() {
192        for name in ["a\0b", "a\nb", "a\rb", "a\tb", "a\u{7f}b", "a\u{1}b"] {
193            let failure = quote(name).expect_err("a control character is refused");
194            assert_eq!(failure.code(), "ident.control_character", "input {name:?}");
195            assert_eq!(failure.exit_number().code(), 3, "input {name:?}");
196        }
197    }
198
199    #[test]
200    fn an_empty_name_is_refused() {
201        assert_eq!(quote("").expect_err("empty").code(), "ident.empty");
202    }
203
204    #[test]
205    fn a_name_longer_than_the_server_accepts_is_refused() {
206        let name = "a".repeat(MAX_IDENTIFIER_CHARS + 1);
207        assert_eq!(quote(&name).expect_err("too long").code(), "ident.too_long");
208        assert!(quote(&"a".repeat(MAX_IDENTIFIER_CHARS)).is_ok());
209    }
210
211    /// The length bound counts characters, not bytes, because the server counts
212    /// characters and a byte bound would refuse a legitimate accented name.
213    #[test]
214    fn the_length_bound_counts_characters_and_not_bytes() {
215        let name = "รก".repeat(MAX_IDENTIFIER_CHARS);
216        assert!(name.len() > MAX_IDENTIFIER_CHARS, "the name is multi-byte");
217        assert!(quote(&name).is_ok());
218    }
219
220    #[test]
221    fn a_qualified_name_quotes_every_part_on_its_own() {
222        assert_eq!(
223            quote_qualified(&["shop", "users"]).expect("qualified"),
224            "`shop`.`users`"
225        );
226        assert_eq!(quote_qualified(&["users"]).expect("single"), "`users`");
227    }
228
229    #[test]
230    fn a_qualified_name_keeps_a_dot_inside_the_part_it_belongs_to() {
231        assert_eq!(
232            quote_qualified(&["a.b", "c"]).expect("dot inside"),
233            "`a.b`.`c`"
234        );
235    }
236
237    #[test]
238    fn a_qualified_name_with_no_parts_is_refused() {
239        let empty: [&str; 0] = [];
240        assert_eq!(
241            quote_qualified(&empty).expect_err("no parts").code(),
242            "ident.empty_path"
243        );
244    }
245
246    #[test]
247    fn a_bad_part_refuses_the_whole_qualified_name() {
248        assert_eq!(
249            quote_qualified(&["shop", "a\nb"])
250                .expect_err("bad part")
251                .code(),
252            "ident.control_character"
253        );
254    }
255}