use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
use bigdecimal::BigDecimal;
use serde_json::{Map, Value};
use sqlx::mysql::MySqlRow;
use sqlx::types::chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
use sqlx::{Column, Row, TypeInfo, ValueRef};
use crate::RowExt;
use crate::numeric::bigdecimal_to_json;
impl RowExt for MySqlRow {
fn to_json(&self) -> Value {
let columns = self.columns();
let mut map = Map::with_capacity(columns.len());
for column in columns {
let idx = column.ordinal();
let type_name = column.type_info().name();
let value = if self.try_get_raw(idx).is_ok_and(|v| v.is_null()) {
Value::Null
} else {
match type_name {
"BOOLEAN" => self.try_get::<bool, _>(idx).map_or(Value::Null, Value::Bool),
"TINYINT" | "SMALLINT" | "INT" | "MEDIUMINT" | "BIGINT" | "TINYINT UNSIGNED"
| "SMALLINT UNSIGNED" | "INT UNSIGNED" | "MEDIUMINT UNSIGNED" | "YEAR" => self
.try_get::<i64, _>(idx)
.map_or(Value::Null, |v| Value::Number(v.into())),
"BIGINT UNSIGNED" => self.try_get::<u64, _>(idx).map_or(Value::Null, |v| {
i64::try_from(v)
.map_or_else(|_| Value::String(v.to_string()), |signed| Value::Number(signed.into()))
}),
"DECIMAL" => self
.try_get::<BigDecimal, _>(idx)
.map_or(Value::Null, |v| bigdecimal_to_json(&v)),
"FLOAT" => self.try_get::<f32, _>(idx).map_or(Value::Null, Value::from),
"DOUBLE" => self.try_get::<f64, _>(idx).map_or(Value::Null, Value::from),
"JSON" => self.try_get::<Value, _>(idx).unwrap_or(Value::Null),
"BINARY" | "VARBINARY" => self
.try_get::<String, _>(idx)
.map_or_else(|_| bytes_to_json(self, idx), Value::String),
"BLOB" | "TINYBLOB" | "MEDIUMBLOB" | "LONGBLOB" | "BIT" | "GEOMETRY" => bytes_to_json(self, idx),
"DATE" => self
.try_get::<NaiveDate, _>(idx)
.map_or(Value::Null, |v| Value::String(v.to_string())),
"TIME" => self
.try_get::<NaiveTime, _>(idx)
.map_or(Value::Null, |v| Value::String(v.to_string())),
"DATETIME" => self
.try_get::<NaiveDateTime, _>(idx)
.map_or(Value::Null, |v| Value::String(format!("{}T{}", v.date(), v.time()))),
"TIMESTAMP" => self.try_get::<DateTime<Utc>, _>(idx).map_or(Value::Null, |v| {
let n = v.naive_utc();
Value::String(format!("{}T{}", n.date(), n.time()))
}),
_ => self
.try_get::<String, _>(idx)
.map_or_else(|_| bytes_to_json(self, idx), Value::String),
}
};
map.insert(column.name().to_string(), value);
}
Value::Object(map)
}
}
fn bytes_to_json(row: &MySqlRow, idx: usize) -> Value {
row.try_get::<Vec<u8>, _>(idx).map_or(Value::Null, |bytes| {
String::from_utf8(bytes.clone()).map_or_else(|_| Value::String(BASE64.encode(&bytes)), Value::String)
})
}