1use crate::error::{Failure, Result};
10use std::fmt::Write as _;
11
12pub const MAX_IDENTIFIER_CHARS: usize = 64;
14
15const DELIMITER: char = '`';
17
18pub 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
67pub 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 let quoted = quote(part.as_ref())?;
105 let _ = write!(joined, "{quoted}");
106 }
107 Ok(joined)
108}
109
110fn 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 #[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 #[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 #[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}