mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! How one value is written inside a copy.
//!
//! Kept apart from the copy itself because the rule here is about one value
//! and one column, and it is provable without a server or a file. It earned
//! its own place the hard way: the rule used to read the shape of the bytes
//! that arrived, and over the text protocol nearly every value arrives as
//! bytes, so a number was written in a form the server read back as a
//! different number.

use crate::types::map::{family_of, Family};
use mysql_async::Value as Wire;

/// One value as it appears inside a statement.
///
/// The column decides the form, and it has to. This reading uses the text
/// protocol, so the server hands back nearly every value as bytes: the number
/// `1` arrives as the byte `0x31` and the amount `120.50` as the six bytes of
/// its digits. Writing all of those in the numeric form put `0x31` into the
/// copy, and a server reading `0x31` back into a whole-number column reads a
/// NUMBER, not the digit: the row came back carrying 49. An amount fared worse,
/// because the number a six-byte hex literal denotes is far past what the
/// column holds, so every amount in a restored copy sat at the column's
/// ceiling. That is silent corruption of a copy whose whole promise is that it
/// restores.
///
/// So the numeric form is kept for what it was meant for, which is content the
/// server itself marks as raw bytes, and everything else is quoted. Quoting is
/// what makes a character survive; the numeric form only preserves bytes, and
/// bytes are not what a text or a number column stores.
#[must_use]
pub fn literal(value: &Wire, column: &mysql_async::Column) -> String {
    match value {
        Wire::NULL => "NULL".to_owned(),
        Wire::Int(inner) => inner.to_string(),
        Wire::UInt(inner) => inner.to_string(),
        Wire::Float(inner) => inner.to_string(),
        Wire::Double(inner) => inner.to_string(),
        Wire::Bytes(inner) => {
            if holds_raw_bytes(column) {
                bytes_literal(inner)
            } else {
                quoted(&value.as_sql(true))
            }
        }
        Wire::Date(..) | Wire::Time(..) => quoted(&value.as_sql(true)),
    }
}

/// Whether this column stores bytes rather than characters or a number.
///
/// Asked of the published type map rather than answered again here, so a copy
/// and a reading can never disagree about what a column holds.
fn holds_raw_bytes(column: &mysql_async::Column) -> bool {
    matches!(
        family_of(column),
        Family::Binary | Family::Geometry | Family::Bits
    )
}

/// A byte string as a numeric literal, with the empty case spelled out.
///
/// The room needed is known before a byte is written — two characters for the
/// prefix and two per byte — so it is taken once instead of being grown into,
/// which matters because this runs for every byte-bearing cell of a copy.
fn bytes_literal(bytes: &[u8]) -> String {
    if bytes.is_empty() {
        return "''".to_owned();
    }
    let mut literal = String::with_capacity(2 + bytes.len() * 2);
    literal.push_str("0x");
    literal.push_str(&hex::encode(bytes));
    literal
}

/// Wraps a rendering the driver already quoted, without quoting it twice.
fn quoted(rendered: &str) -> String {
    if rendered.starts_with('\'') {
        return rendered.to_owned();
    }
    format!("'{rendered}'")
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A column of the given type, for asking what form a value takes in it.
    fn column_of(kind: mysql_async::consts::ColumnType) -> mysql_async::Column {
        mysql_async::Column::new(kind)
    }

    #[test]
    fn absence_of_a_value_is_told_apart_from_empty_content() {
        let text = column_of(mysql_async::consts::ColumnType::MYSQL_TYPE_VAR_STRING);
        assert_eq!(literal(&Wire::NULL, &text), "NULL");
        assert_eq!(literal(&Wire::Bytes(Vec::new()), &text), "''");
    }

    #[test]
    fn byte_content_travels_in_a_form_no_character_set_can_change() {
        let raw = column_of(mysql_async::consts::ColumnType::MYSQL_TYPE_GEOMETRY);
        let rendered = literal(&Wire::Bytes(b"O'Brien\\".to_vec()), &raw);
        assert!(rendered.starts_with("0x"));
        assert!(
            !rendered.contains('\''),
            "nothing to escape and nothing to break"
        );
        assert_eq!(rendered, format!("0x{}", hex::encode(b"O'Brien\\")));
    }

    /// Every declaration that holds bytes leaves a copy in the restorable form.
    ///
    /// The test above asks the question of one declaration; this one asks it of
    /// the whole set, because the damage of getting it wrong is not a wrong
    /// character in a copy but a value the server refuses on the way back in.
    /// Restoring outside strict mode does not refuse loudly: it writes a zero
    /// and carries on, so a copy taken this way reads as successful and the
    /// loss surfaces only when somebody compares the two databases.
    ///
    /// MariaDB reached the same set from the other direction, having shipped a
    /// dump tool that quoted these and finding restored values replaced by
    /// zeros; the fix in 11.7.2 forces the numeric form for exactly these
    /// three. A change that moves any of them to another family belongs here in
    /// red, and this is the only place that would catch it without a server.
    #[test]
    fn every_declaration_that_holds_bytes_leaves_in_the_restorable_form() {
        use mysql_async::consts::ColumnType;

        let content = b"\x00\x01\xff'\\".to_vec();
        for kind in [
            ColumnType::MYSQL_TYPE_VECTOR,
            ColumnType::MYSQL_TYPE_GEOMETRY,
            ColumnType::MYSQL_TYPE_BIT,
        ] {
            let rendered = literal(&Wire::Bytes(content.clone()), &column_of(kind));
            assert_eq!(
                rendered,
                format!("0x{}", hex::encode(&content)),
                "a {kind:?} column left a copy in a form the server reads back as zero"
            );
        }
    }

    /// A number arrives as the bytes of its digits over this protocol, and the
    /// numeric form would turn those digits into a different number entirely.
    ///
    /// This is the defect the column argument exists to stop. The amount
    /// `120.50` reaches here as six bytes; written as `0x3132302e3530` it
    /// denotes a number far past what the column holds, and a restored copy
    /// carried the column's ceiling in place of the amount. The digit `1`
    /// reaches here as one byte and came back as 49.
    #[test]
    fn a_number_that_arrived_as_digits_is_not_written_as_bytes() {
        let amount = column_of(mysql_async::consts::ColumnType::MYSQL_TYPE_NEWDECIMAL);
        let rendered = literal(&Wire::Bytes(b"120.50".to_vec()), &amount);
        assert!(
            !rendered.starts_with("0x"),
            "a number must never travel as bytes"
        );
        assert!(
            rendered.contains("120.50"),
            "the amount itself has to be in there"
        );

        let whole = column_of(mysql_async::consts::ColumnType::MYSQL_TYPE_LONG);
        let one = literal(&Wire::Bytes(b"1".to_vec()), &whole);
        assert!(
            !one.starts_with("0x"),
            "`0x31` is the number 49, not the digit 1"
        );
    }

    /// A character keeps its own quoting, because the numeric form preserves
    /// bytes and a character column stores characters, not bytes.
    /// A backslash leaves a copy untouched, which only restores under the mode
    /// the copy itself declares.
    ///
    /// The rendering here passes `true` for the driver's no-backslash rule, so
    /// a backslash is written exactly as it stood and only a quote is doubled.
    /// That is correct, and it is correct only on a server reading under
    /// `NO_BACKSLASH_ESCAPES`. The copy's own header is what puts the server
    /// into that mode, so the two are one decision written in two files, and
    /// this test is the thread between them.
    ///
    /// They were apart once. The header set the mode without naming the
    /// backslash rule while the values were already written as if it had, so
    /// `C:\novo` restored as `C:` followed by a line break and `ovo`, and a
    /// value ending in a backslash escaped the closing quote and let the
    /// statement run on into the next one.
    #[test]
    fn a_backslash_is_written_untouched_and_the_copy_declares_the_mode_that_reads_it() {
        let text = column_of(mysql_async::consts::ColumnType::MYSQL_TYPE_VAR_STRING);

        let rendered = literal(&Wire::Bytes(br"C:\novo".to_vec()), &text);
        assert_eq!(
            rendered, r"'C:\novo'",
            "the backslash is written as it stood, not doubled and not escaped"
        );

        let trailing = literal(&Wire::Bytes(br"ends with\".to_vec()), &text);
        assert_eq!(
            trailing, r"'ends with\'",
            "a trailing backslash sits right against the closing quote"
        );

        // Which is readable only under the mode the copy asks for. Asserted
        // against the header itself so moving one without the other fails here.
        let opening = crate::datamove::export::header();
        assert!(
            opening.contains("NO_BACKSLASH_ESCAPES"),
            "the copy renders backslashes raw and must ask for the mode that \
             reads them raw; the header says: {opening}"
        );
    }

    #[test]
    fn a_character_is_written_quoted_and_survives_its_own_accents() {
        let text = column_of(mysql_async::consts::ColumnType::MYSQL_TYPE_VAR_STRING);
        let rendered = literal(&Wire::Bytes("acentuação".as_bytes().to_vec()), &text);
        assert!(!rendered.starts_with("0x"));
        assert!(rendered.contains("acentuação"));
    }

    #[test]
    fn numbers_are_written_without_quotes() {
        let whole = column_of(mysql_async::consts::ColumnType::MYSQL_TYPE_LONG);
        assert_eq!(literal(&Wire::Int(-7), &whole), "-7");
        assert_eq!(
            literal(&Wire::UInt(18_446_744_073_709_551_615), &whole),
            "18446744073709551615"
        );
    }

    #[test]
    fn a_moment_in_time_is_written_quoted_exactly_once() {
        let moment = column_of(mysql_async::consts::ColumnType::MYSQL_TYPE_DATETIME);
        let rendered = literal(&Wire::Date(2026, 8, 7, 12, 30, 0, 0), &moment);
        assert!(rendered.starts_with('\''));
        assert!(rendered.ends_with('\''));
        assert!(!rendered.starts_with("''"));
    }
}