mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Safe quoting of an object name.
//!
//! Introspection builds statements around names the caller supplies: a schema,
//! a table, a column. A name is not a value and cannot travel as a parameter,
//! so it is pasted into the text. This module is the only sanctioned way to do
//! that, and it refuses a name it cannot quote instead of producing text that
//! would change what the statement means.

use crate::error::{Failure, Result};
use std::fmt::Write as _;

/// The longest object name this server accepts, in characters.
pub const MAX_IDENTIFIER_CHARS: usize = 64;

/// The delimiter this server uses around an object name.
const DELIMITER: char = '`';

/// Quotes one object name.
///
/// The delimiter inside the name is doubled, which is how this server escapes
/// it. The result always begins and ends with the delimiter, so it is a single
/// name whatever it contains.
///
/// # Examples
///
/// An ordinary name comes back wrapped, and one carrying the delimiter comes
/// back with it doubled, which is what keeps it a single name:
///
/// ```
/// use mariadb_cli::sql::ident::quote;
///
/// assert_eq!(quote("pedidos")?, "`pedidos`");
/// assert_eq!(quote("a`b")?, "`a``b`");
/// # Ok::<(), mariadb_cli::error::Failure>(())
/// ```
///
/// A name that cannot be quoted is refused rather than mangled:
///
/// ```
/// use mariadb_cli::sql::ident::quote;
///
/// assert!(quote("").is_err());
/// assert!(quote("linha\nnova").is_err());
/// ```
///
/// # Errors
///
/// Returns a validation failure when the name is empty, longer than the server
/// accepts, or carries a control character. A control character is refused
/// rather than escaped because it has no escaped form here and would travel to
/// the server as itself.
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)
}

/// Quotes a name made of several parts, such as a schema and a table.
///
/// Each part is quoted on its own and the parts are joined by a dot, so a dot
/// inside a part stays inside that part.
///
/// # Examples
///
/// A schema and a table join with a dot between them, and a dot written inside
/// one part stays inside that part instead of splitting it:
///
/// ```
/// use mariadb_cli::sql::ident::quote_qualified;
///
/// assert_eq!(quote_qualified(&["loja", "pedidos"])?, "`loja`.`pedidos`");
/// assert_eq!(quote_qualified(&["um.dois"])?, "`um.dois`");
/// # Ok::<(), mariadb_cli::error::Failure>(())
/// ```
///
/// # Errors
///
/// Returns a validation failure when the list is empty or any part is refused
/// by [`quote`].
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('.');
        }
        // The buffer is a String, whose write never fails; the result is
        // consumed so no failure path is discarded silently.
        let quoted = quote(part.as_ref())?;
        let _ = write!(joined, "{quoted}");
    }
    Ok(joined)
}

/// Refuses a name that cannot be quoted safely.
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`");
    }

    /// FR-075. A name carrying the delimiter never alters the structure of the
    /// statement it is pasted into: the delimiter is doubled, so what looks
    /// like an escape lands inside the quoted name and stays a name.
    ///
    /// A name carrying the delimiter is the whole point of this module: without
    /// doubling it, the name would close early and the rest would become code.
    #[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`");
    }

    /// FR-075. A name that has no quoted form is refused rather than sent, and
    /// the refusal is the published validation number.
    #[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());
    }

    /// The length bound counts characters, not bytes, because the server counts
    /// characters and a byte bound would refuse a legitimate accented name.
    #[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"
        );
    }
}