use super::binary::{self, Policy};
use super::map::{declared_name, family_of, Family, SAFE_INTEGER};
use crate::error::Result;
use mysql_async::{Column, Value as Wire};
use serde_json::Value;
use std::borrow::Cow;
#[derive(Debug, Clone, Copy)]
pub struct Conversion {
pub binary: Policy,
}
impl Conversion {
#[must_use]
pub const fn stable() -> Self {
Self {
binary: Policy {
content: super::binary::Content::Described,
},
}
}
}
pub fn convert(value: &Wire, column: &Column, options: &Conversion) -> Result<Value> {
if matches!(value, Wire::NULL) {
return Ok(Value::Null);
}
match family_of(column) {
Family::Integer | Family::WideInteger | Family::Year => Ok(as_integer(value)),
Family::FloatingPoint => Ok(as_number(value)),
Family::ExactDecimal | Family::Text | Family::SingleChoice | Family::ChoiceSet => {
Ok(Value::from(as_text(value)))
}
Family::Uuid | Family::Inet4 | Family::Inet6 => Ok(Value::from(as_text(value))),
Family::Absent => Ok(Value::Null),
Family::Bits => Ok(as_bits(value)),
Family::Date => Ok(Value::from(as_date(value))),
Family::DateTime | Family::Timestamp => {
Ok(Value::from(as_date_time(value, column.decimals())))
}
Family::Time => Ok(Value::from(as_time(value, column.decimals()))),
Family::Document => Ok(as_document(value)),
Family::Binary => binary::describe(&bytes_of(value), &options.binary),
Family::Geometry => binary::describe_geometry(&bytes_of(value), &options.binary),
Family::Unknown => Ok(Value::from(declared_name(column.column_type()))),
}
}
fn bytes_of(value: &Wire) -> Cow<'_, [u8]> {
match value {
Wire::Bytes(bytes) => Cow::Borrowed(bytes),
other => Cow::Owned(as_text(other).into_bytes()),
}
}
fn as_text(value: &Wire) -> String {
match value {
Wire::NULL => String::new(),
Wire::Bytes(bytes) => String::from_utf8_lossy(bytes).into_owned(),
Wire::Int(number) => number.to_string(),
Wire::UInt(number) => number.to_string(),
Wire::Float(number) => number.to_string(),
Wire::Double(number) => number.to_string(),
Wire::Date(..) => as_date_time(value, 6),
Wire::Time(..) => as_time(value, 6),
}
}
fn as_integer(value: &Wire) -> Value {
let wide = match value {
Wire::Int(number) => i128::from(*number),
Wire::UInt(number) => i128::from(*number),
Wire::Float(number) => return whole_part(f64::from(*number)),
Wire::Double(number) => return whole_part(*number),
other => {
let text = as_text(other);
return text.parse::<i128>().map_or(Value::from(text), safe_integer);
}
};
safe_integer(wide)
}
fn whole_part(number: f64) -> Value {
let whole = format!("{:.0}", number.trunc());
whole
.parse::<i128>()
.map_or(Value::from(whole), safe_integer)
}
fn safe_integer(number: i128) -> Value {
if number.unsigned_abs() <= u128::from(SAFE_INTEGER) {
if let Ok(narrow) = i64::try_from(number) {
return Value::from(narrow);
}
}
Value::from(number.to_string())
}
fn as_number(value: &Wire) -> Value {
let number = match value {
Wire::Float(single) => f64::from(*single),
Wire::Double(double) => *double,
Wire::Int(whole) => {
#[allow(clippy::cast_precision_loss)]
{
*whole as f64
}
}
Wire::UInt(whole) => {
#[allow(clippy::cast_precision_loss)]
{
*whole as f64
}
}
other => {
let text = as_text(other);
return text
.parse::<f64>()
.ok()
.and_then(serde_json::Number::from_f64)
.map_or(Value::from(text), Value::Number);
}
};
serde_json::Number::from_f64(number)
.map_or_else(|| Value::from(number.to_string()), Value::Number)
}
fn as_bits(value: &Wire) -> Value {
match value {
Wire::Bytes(bytes) => {
let mut accumulated: u128 = 0;
for byte in bytes.iter().take(16) {
accumulated = (accumulated << 8) | u128::from(*byte);
}
i128::try_from(accumulated)
.map_or_else(|_| Value::from(accumulated.to_string()), safe_integer)
}
other => as_integer(other),
}
}
fn as_date(value: &Wire) -> String {
match value {
Wire::Date(year, month, day, ..) => format!("{year:04}-{month:02}-{day:02}"),
other => as_text(other),
}
}
fn as_date_time(value: &Wire, decimals: u8) -> String {
let Wire::Date(year, month, day, hour, minute, second, micros) = value else {
return as_text(value);
};
let mut rendered = format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
push_fraction(&mut rendered, *micros, decimals);
rendered
}
fn as_time(value: &Wire, decimals: u8) -> String {
let Wire::Time(negative, days, hours, minutes, seconds, micros) = value else {
return as_text(value);
};
let total_hours = u64::from(*days) * 24 + u64::from(*hours);
let sign = if *negative { "-" } else { "" };
let mut rendered = format!("{sign}{total_hours:02}:{minutes:02}:{seconds:02}");
push_fraction(&mut rendered, *micros, decimals);
rendered
}
fn push_fraction(rendered: &mut String, micros: u32, decimals: u8) {
let digits = usize::from(decimals.min(6));
if digits == 0 {
return;
}
let full = format!("{micros:06}");
rendered.push('.');
rendered.push_str(&full[..digits]);
}
fn as_document(value: &Wire) -> Value {
let text = as_text(value);
serde_json::from_str(&text).unwrap_or_else(|_| Value::from(text))
}
#[cfg(test)]
mod tests {
use super::*;
use mysql_async::consts::ColumnType;
fn column(kind: ColumnType) -> Column {
Column::new(kind)
}
fn with_decimals(kind: ColumnType, decimals: u8) -> Column {
Column::new(kind).with_decimals(decimals)
}
fn described() -> Conversion {
Conversion {
binary: Policy {
content: super::super::binary::Content::Described,
},
}
}
fn convert_ok(value: &Wire, column: &Column) -> Value {
convert(value, column, &described()).expect("converts")
}
#[test]
fn an_integer_inside_the_safe_range_is_a_number() {
let out = convert_ok(&Wire::Int(42), &column(ColumnType::MYSQL_TYPE_LONG));
assert_eq!(out, Value::from(42));
assert!(out.is_number());
}
#[test]
fn an_unsigned_integer_above_the_safe_range_is_text() {
let huge = SAFE_INTEGER + 1;
let out = convert_ok(&Wire::UInt(huge), &column(ColumnType::MYSQL_TYPE_LONGLONG));
assert_eq!(out, Value::from(huge.to_string()));
assert!(out.is_string(), "no digit may be lost in the reader");
}
#[test]
fn an_exact_decimal_is_always_text_even_when_it_would_seem_to_fit() {
let out = convert_ok(
&Wire::Bytes(b"1.50".to_vec()),
&column(ColumnType::MYSQL_TYPE_NEWDECIMAL),
);
assert_eq!(out, Value::from("1.50"));
let small = convert_ok(
&Wire::Bytes(b"2".to_vec()),
&column(ColumnType::MYSQL_TYPE_DECIMAL),
);
assert!(small.is_string(), "an exact decimal never becomes a number");
}
#[test]
fn floating_point_stays_a_number_and_text_stays_text() {
let number = convert_ok(&Wire::Double(1.5), &column(ColumnType::MYSQL_TYPE_DOUBLE));
assert_eq!(number, Value::from(1.5));
let text = convert_ok(
&Wire::Bytes("olá".as_bytes().to_vec()),
&column(ColumnType::MYSQL_TYPE_VAR_STRING),
);
assert_eq!(text, Value::from("olá"));
}
#[test]
fn absence_is_its_own_marker_and_not_empty_text() {
let absent = convert_ok(&Wire::NULL, &column(ColumnType::MYSQL_TYPE_VAR_STRING));
let empty = convert_ok(
&Wire::Bytes(Vec::new()),
&column(ColumnType::MYSQL_TYPE_VAR_STRING),
);
assert_eq!(absent, Value::Null);
assert_eq!(empty, Value::from(""));
assert_ne!(absent, empty, "absence must differ from empty text");
}
#[test]
fn a_bit_field_reads_as_one_number() {
let out = convert_ok(
&Wire::Bytes(vec![0x01, 0x00]),
&column(ColumnType::MYSQL_TYPE_BIT),
);
assert_eq!(out, Value::from(256));
}
#[test]
fn a_date_carries_year_month_and_day() {
let out = convert_ok(
&Wire::Date(2026, 8, 7, 0, 0, 0, 0),
&column(ColumnType::MYSQL_TYPE_DATE),
);
assert_eq!(out, Value::from("2026-08-07"));
}
#[test]
fn a_zeroed_date_is_rendered_and_never_ends_the_read() {
let out = convert(
&Wire::Date(0, 0, 0, 0, 0, 0, 0),
&column(ColumnType::MYSQL_TYPE_DATE),
&described(),
);
assert_eq!(out.expect("keeps reading"), Value::from("0000-00-00"));
}
#[test]
fn the_fraction_appears_only_as_far_as_the_column_declares_it() {
let bare = convert_ok(
&Wire::Date(2026, 8, 7, 12, 30, 5, 123_456),
&column(ColumnType::MYSQL_TYPE_DATETIME),
);
assert_eq!(bare, Value::from("2026-08-07 12:30:05"));
let precise = convert_ok(
&Wire::Date(2026, 8, 7, 12, 30, 5, 123_456),
&with_decimals(ColumnType::MYSQL_TYPE_TIMESTAMP, 3),
);
assert_eq!(precise, Value::from("2026-08-07 12:30:05.123"));
}
#[test]
fn an_interval_accepts_a_negative_value_and_one_past_a_whole_day() {
let backwards = convert_ok(
&Wire::Time(true, 0, 2, 30, 0, 0),
&column(ColumnType::MYSQL_TYPE_TIME),
);
assert_eq!(backwards, Value::from("-02:30:00"));
let long = convert_ok(
&Wire::Time(false, 35, 4, 5, 6, 0),
&column(ColumnType::MYSQL_TYPE_TIME),
);
assert_eq!(long, Value::from("844:05:06"));
}
#[test]
fn a_year_is_a_number_and_a_label_is_text() {
assert_eq!(
convert_ok(&Wire::Int(2026), &column(ColumnType::MYSQL_TYPE_YEAR)),
Value::from(2026)
);
assert_eq!(
convert_ok(
&Wire::Bytes(b"high".to_vec()),
&column(ColumnType::MYSQL_TYPE_ENUM)
),
Value::from("high")
);
assert_eq!(
convert_ok(
&Wire::Bytes(b"read,write".to_vec()),
&column(ColumnType::MYSQL_TYPE_SET)
),
Value::from("read,write")
);
}
#[test]
fn a_document_becomes_a_structure_and_never_the_text_of_one() {
let out = convert_ok(
&Wire::Bytes(br#"{"a":[1,2]}"#.to_vec()),
&column(ColumnType::MYSQL_TYPE_JSON),
);
assert!(
out.is_object(),
"a document must be a real structure: {out}"
);
assert_eq!(out["a"][1], Value::from(2));
}
#[test]
fn a_malformed_document_becomes_text_rather_than_ending_the_read() {
let out = convert(
&Wire::Bytes(b"{not json".to_vec()),
&column(ColumnType::MYSQL_TYPE_JSON),
&described(),
);
assert_eq!(out.expect("keeps reading"), Value::from("{not json"));
}
#[test]
fn a_byte_column_leaves_as_a_description() {
let binary_column = Column::new(ColumnType::MYSQL_TYPE_BLOB)
.with_character_set(super::super::map::BINARY_CHARSET);
let out = convert_ok(&Wire::Bytes(vec![0u8; 5000]), &binary_column);
assert_eq!(out["kind"], "binary");
assert_eq!(out["bytes"], 5000);
}
#[test]
fn the_stable_shaping_differs_from_the_published_one_only_for_raw_bytes() {
use super::super::binary::{Content, Policy};
use mysql_async::consts::ColumnType;
let published = Conversion {
binary: Policy {
content: Content::Raw { max_bytes: 4096 },
},
};
let payload = Wire::Bytes(vec![7u8; 16]);
let every_type = [
ColumnType::MYSQL_TYPE_LONG,
ColumnType::MYSQL_TYPE_LONGLONG,
ColumnType::MYSQL_TYPE_NEWDECIMAL,
ColumnType::MYSQL_TYPE_DOUBLE,
ColumnType::MYSQL_TYPE_VAR_STRING,
ColumnType::MYSQL_TYPE_BIT,
ColumnType::MYSQL_TYPE_DATE,
ColumnType::MYSQL_TYPE_DATETIME,
ColumnType::MYSQL_TYPE_TIMESTAMP,
ColumnType::MYSQL_TYPE_TIME,
ColumnType::MYSQL_TYPE_YEAR,
ColumnType::MYSQL_TYPE_ENUM,
ColumnType::MYSQL_TYPE_SET,
ColumnType::MYSQL_TYPE_JSON,
ColumnType::MYSQL_TYPE_TYPED_ARRAY,
];
for kind in every_type {
let column = column(kind);
let family = super::super::map::family_of(&column);
assert!(
!matches!(family, Family::Binary | Family::Geometry),
"{} carries raw bytes and does not belong in this list",
family.as_str()
);
assert_eq!(
convert(&payload, &column, &Conversion::stable()).expect("converts"),
convert(&payload, &column, &published).expect("converts"),
"the two shapings disagree on {}, so the stable one is no longer safe there",
family.as_str()
);
}
let packed = Wire::Bytes(vec![0x00, 0x01, 0x02, 0x03]);
for carrier in [
Column::new(ColumnType::MYSQL_TYPE_BLOB)
.with_character_set(super::super::map::BINARY_CHARSET),
Column::new(ColumnType::MYSQL_TYPE_VECTOR),
Column::new(ColumnType::MYSQL_TYPE_GEOMETRY),
] {
let family = super::super::map::family_of(&carrier);
assert_ne!(
convert(&packed, &carrier, &Conversion::stable()).expect("converts"),
convert(&packed, &carrier, &published).expect("converts"),
"the two shapings agree on {}, so this test would not catch it moving",
family.as_str()
);
}
}
#[test]
fn an_unknown_type_carries_its_declared_name() {
let out = convert_ok(
&Wire::Bytes(b"anything".to_vec()),
&column(ColumnType::MYSQL_TYPE_TYPED_ARRAY),
);
let text = out.as_str().expect("text");
assert!(text.contains("TYPED_ARRAY"), "{text}");
}
}