use sqlx::mysql::MySqlRow;
use crate::prelude::*;
impl RowExt for MySqlRow {
fn to_json(&self) -> Value {
row_to_json(self)
}
}
impl DecodeCell for MySqlRow {
fn decode_cell(&self, idx: usize, type_name: &str) -> Cell {
let cell = match type_name {
"BOOLEAN" => self
.try_get(idx)
.map(Cell::Int)
.or_else(|_| self.try_get(idx).map(Cell::UInt))
.map_or(Cell::Null, |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).map_or(Cell::Null, Cell::Int),
"TINYINT UNSIGNED" | "SMALLINT UNSIGNED" | "MEDIUMINT UNSIGNED" | "INT UNSIGNED" | "BIGINT UNSIGNED"
| "YEAR" | "BIT" => self.try_get(idx).map_or(Cell::Null, Cell::UInt),
"DECIMAL" => self.try_get(idx).map_or(Cell::Null, Cell::Decimal),
"FLOAT" => self.try_get(idx).map_or(Cell::Null, Cell::Float32),
"DOUBLE" => self.try_get(idx).map_or(Cell::Null, Cell::Float64),
"JSON" => self.try_get(idx).map_or(Cell::Null, Cell::Json),
"BLOB" | "TINYBLOB" | "MEDIUMBLOB" | "LONGBLOB" => self
.try_get(idx)
.map_or_else(|_| self.try_get(idx).map_or(Cell::Null, Cell::Bytes), Cell::Text),
"GEOMETRY" => self.try_get_unchecked(idx).map_or(Cell::Null, Cell::Bytes),
"DATE" => self.try_get(idx).map_or(Cell::Null, Cell::Date),
"TIME" => self.try_get(idx).map_or(Cell::Null, Cell::Time),
"DATETIME" => self.try_get(idx).map_or(Cell::Null, Cell::DateTime),
"TIMESTAMP" => self.try_get(idx).map_or(Cell::Null, Cell::DateTimeUtc),
_ => text_or_bytes(self, idx),
};
match cell {
Cell::Null => text_or_bytes(self, idx),
cell => cell,
}
}
}
fn text_or_bytes(row: &MySqlRow, idx: usize) -> Cell {
row.try_get_unchecked::<&[u8], _>(idx)
.map_or(Cell::Null, |bytes| match std::str::from_utf8(bytes) {
Ok(text) => Cell::Text(text.to_owned()),
Err(_) => Cell::Bytes(bytes.to_vec()),
})
}