use serde_json::Value;
use sqlx::mysql::MySqlRow;
use crate::prelude::*;
impl DecodeCell for MySqlRow {
fn decode_cell(&self, idx: usize, type_name: &str) -> Option<Cell> {
match type_name {
"BOOLEAN" => self
.try_get(idx)
.map(Cell::Int)
.or_else(|_| self.try_get(idx).map(Cell::UInt))
.ok()
.map(|cell| match cell {
Cell::Int(0) | Cell::UInt(0) => Cell::Bool(false),
Cell::Int(1) | Cell::UInt(1) => Cell::Bool(true),
cell => cell,
}),
"TINYINT" | "SMALLINT" | "INT" | "MEDIUMINT" | "BIGINT" => self.try_get(idx).ok().map(Cell::Int),
"TINYINT UNSIGNED" | "SMALLINT UNSIGNED" | "MEDIUMINT UNSIGNED" | "INT UNSIGNED" | "BIGINT UNSIGNED"
| "YEAR" | "BIT" => self.try_get(idx).ok().map(Cell::UInt),
"DECIMAL" => self.try_get(idx).ok().map(Cell::Decimal),
"FLOAT" => self.try_get(idx).ok().map(Cell::Float32),
"DOUBLE" => self.try_get(idx).ok().map(Cell::Float64),
"JSON" => self.try_get(idx).ok().map(Cell::Json),
"BLOB" | "TINYBLOB" | "MEDIUMBLOB" | "LONGBLOB" => self
.try_get(idx)
.ok()
.map(Cell::Text)
.or_else(|| self.try_get(idx).ok().map(Cell::Bytes)),
"VECTOR" => self.try_get_unchecked::<&[u8], _>(idx).ok().map(vector),
"GEOMETRY" => self.try_get_unchecked(idx).ok().map(Cell::Bytes),
"DATE" => self.try_get(idx).ok().map(Cell::Date),
"TIME" => self.try_get(idx).ok().map(Cell::Time),
"DATETIME" => self.try_get(idx).ok().map(Cell::DateTime),
"TIMESTAMP" => self.try_get(idx).ok().map(Cell::DateTimeUtc),
_ => None,
}
.or_else(|| text_or_bytes(self, idx))
}
}
fn text_or_bytes(row: &MySqlRow, idx: usize) -> Option<Cell> {
row.try_get_unchecked::<&[u8], _>(idx)
.ok()
.map(|bytes| match std::str::from_utf8(bytes) {
Ok(text) => Cell::Text(text.to_owned()),
Err(_) => Cell::Bytes(bytes.to_vec()),
})
}
fn vector(bytes: &[u8]) -> Cell {
let floats = bytes
.chunks_exact(4)
.map(|chunk| f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
if !bytes.len().is_multiple_of(4) || floats.clone().any(|f| !f.is_finite()) {
return Cell::Bytes(bytes.to_vec());
}
Cell::Json(Value::Array(floats.map(Value::from).collect()))
}
#[cfg(test)]
mod tests {
use super::*;
fn le(values: &[f32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
#[test]
fn vector_decodes_little_endian_floats() {
let Cell::Json(value) = vector(&le(&[1.5, 2.0, 3.0])) else {
panic!("expected a JSON array");
};
assert_eq!(value, serde_json::json!([1.5, 2.0, 3.0]));
}
#[test]
fn empty_vector_is_an_empty_array() {
assert!(matches!(vector(&[]), Cell::Json(Value::Array(items)) if items.is_empty()));
}
#[test]
fn vector_with_partial_float_stays_bytes() {
let mut bytes = le(&[1.5]);
bytes.push(0);
assert!(matches!(vector(&bytes), Cell::Bytes(b) if b == bytes));
}
#[test]
fn vector_with_non_finite_float_stays_bytes() {
for value in [f32::NAN, f32::INFINITY] {
let bytes = le(&[1.0, value]);
assert!(matches!(vector(&bytes), Cell::Bytes(b) if b == bytes));
}
}
}