use crate::error::{Failure, Result};
use std::fmt::Write as _;
pub const MAX_IDENTIFIER_CHARS: usize = 64;
const DELIMITER: char = '`';
pub fn quote(name: &str) -> Result<String> {
refuse_unquotable(name)?;
let mut quoted = String::with_capacity(name.len() + 2);
quoted.push(DELIMITER);
for character in name.chars() {
if character == DELIMITER {
quoted.push(DELIMITER);
}
quoted.push(character);
}
quoted.push(DELIMITER);
Ok(quoted)
}
pub fn quote_qualified<S: AsRef<str>>(parts: &[S]) -> Result<String> {
if parts.is_empty() {
return Err(
Failure::validation("ident.empty_path", "the object name has no parts")
.with_hint("give at least one name part"),
);
}
let mut joined = String::new();
for (position, part) in parts.iter().enumerate() {
if position > 0 {
joined.push('.');
}
let quoted = quote(part.as_ref())?;
let _ = write!(joined, "{quoted}");
}
Ok(joined)
}
fn refuse_unquotable(name: &str) -> Result<()> {
if name.is_empty() {
return Err(
Failure::validation("ident.empty", "the object name is empty")
.with_hint("give a name with at least one character"),
);
}
if let Some(offset) = name
.char_indices()
.find_map(|(offset, character)| character.is_control().then_some(offset))
{
return Err(Failure::validation(
"ident.control_character",
format!("the object name carries a control character at byte {offset}"),
)
.with_detail("detail", offset.to_string())
.with_hint("remove the control character from the name"));
}
let length = name.chars().count();
if length > MAX_IDENTIFIER_CHARS {
return Err(Failure::validation(
"ident.too_long",
format!(
"the object name has {length} characters and this server accepts {MAX_IDENTIFIER_CHARS}"
),
)
.with_detail("detail", format!("{length} > {MAX_IDENTIFIER_CHARS}"))
.with_hint("shorten the name"));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_plain_name_is_wrapped_in_the_delimiter() {
assert_eq!(quote("users").expect("plain name"), "`users`");
}
#[test]
fn a_reserved_word_is_a_usable_name_once_quoted() {
assert_eq!(quote("select").expect("reserved word"), "`select`");
assert_eq!(quote("order").expect("reserved word"), "`order`");
}
#[test]
fn the_delimiter_inside_the_name_is_doubled() {
assert_eq!(quote("a`b").expect("delimiter inside"), "`a``b`");
assert_eq!(
quote("t` ; DROP TABLE users; -- ").expect("delimiter inside"),
"`t`` ; DROP TABLE users; -- `"
);
}
#[test]
fn a_name_with_a_separator_or_a_quote_stays_one_name() {
assert_eq!(quote("a;b").expect("separator"), "`a;b`");
assert_eq!(quote("a'b").expect("quote"), "`a'b`");
assert_eq!(quote("a\"b").expect("quote"), "`a\"b`");
}
#[test]
fn a_name_with_a_dot_stays_one_name() {
assert_eq!(quote("a.b").expect("dot"), "`a.b`");
}
#[test]
fn a_name_with_a_control_character_is_refused() {
for name in ["a\0b", "a\nb", "a\rb", "a\tb", "a\u{7f}b", "a\u{1}b"] {
let failure = quote(name).expect_err("a control character is refused");
assert_eq!(failure.code(), "ident.control_character", "input {name:?}");
assert_eq!(failure.exit_number().code(), 3, "input {name:?}");
}
}
#[test]
fn an_empty_name_is_refused() {
assert_eq!(quote("").expect_err("empty").code(), "ident.empty");
}
#[test]
fn a_name_longer_than_the_server_accepts_is_refused() {
let name = "a".repeat(MAX_IDENTIFIER_CHARS + 1);
assert_eq!(quote(&name).expect_err("too long").code(), "ident.too_long");
assert!(quote(&"a".repeat(MAX_IDENTIFIER_CHARS)).is_ok());
}
#[test]
fn the_length_bound_counts_characters_and_not_bytes() {
let name = "รก".repeat(MAX_IDENTIFIER_CHARS);
assert!(name.len() > MAX_IDENTIFIER_CHARS, "the name is multi-byte");
assert!(quote(&name).is_ok());
}
#[test]
fn a_qualified_name_quotes_every_part_on_its_own() {
assert_eq!(
quote_qualified(&["shop", "users"]).expect("qualified"),
"`shop`.`users`"
);
assert_eq!(quote_qualified(&["users"]).expect("single"), "`users`");
}
#[test]
fn a_qualified_name_keeps_a_dot_inside_the_part_it_belongs_to() {
assert_eq!(
quote_qualified(&["a.b", "c"]).expect("dot inside"),
"`a.b`.`c`"
);
}
#[test]
fn a_qualified_name_with_no_parts_is_refused() {
let empty: [&str; 0] = [];
assert_eq!(
quote_qualified(&empty).expect_err("no parts").code(),
"ident.empty_path"
);
}
#[test]
fn a_bad_part_refuses_the_whole_qualified_name() {
assert_eq!(
quote_qualified(&["shop", "a\nb"])
.expect_err("bad part")
.code(),
"ident.control_character"
);
}
}