Skip to main content

sqlx_json/
mysql.rs

1//! [`RowExt`](crate::RowExt) implementation for `MySQL` rows.
2//!
3//! Uses `column.type_info().name()` to pick the right Rust type for each column.
4//! `MySQL` 9 reports `information_schema` text columns as `VARBINARY`; these
5//! are decoded as UTF-8 strings rather than base64. Temporal types (`DATE`,
6//! `TIME`, `DATETIME`, `TIMESTAMP`) are decoded via sqlx's `chrono` integration
7//! and serialized as naive ISO 8601 strings (no timezone offset). `DECIMAL`
8//! is decoded via `BigDecimal` to preserve precision; `FLOAT` is decoded as
9//! `f32` (sqlx-mysql strict-checks the column type), `DOUBLE` as `f64`.
10
11use base64::Engine as _;
12use base64::engine::general_purpose::STANDARD as BASE64;
13use bigdecimal::BigDecimal;
14use serde_json::{Map, Value};
15use sqlx::mysql::MySqlRow;
16use sqlx::types::chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
17use sqlx::{Column, Row, TypeInfo, ValueRef};
18
19use crate::RowExt;
20use crate::numeric::bigdecimal_to_json;
21
22impl RowExt for MySqlRow {
23    fn to_json(&self) -> Value {
24        let columns = self.columns();
25        let mut map = Map::with_capacity(columns.len());
26
27        for column in columns {
28            let idx = column.ordinal();
29            let type_name = column.type_info().name();
30
31            let value = if self.try_get_raw(idx).is_ok_and(|v| v.is_null()) {
32                Value::Null
33            } else {
34                match type_name {
35                    "BOOLEAN" => self.try_get::<bool, _>(idx).map_or(Value::Null, Value::Bool),
36
37                    "TINYINT" | "SMALLINT" | "INT" | "MEDIUMINT" | "BIGINT" | "TINYINT UNSIGNED"
38                    | "SMALLINT UNSIGNED" | "INT UNSIGNED" | "MEDIUMINT UNSIGNED" | "YEAR" => self
39                        .try_get::<i64, _>(idx)
40                        .map_or(Value::Null, |v| Value::Number(v.into())),
41
42                    "BIGINT UNSIGNED" => self.try_get::<u64, _>(idx).map_or(Value::Null, |v| {
43                        i64::try_from(v)
44                            .map_or_else(|_| Value::String(v.to_string()), |signed| Value::Number(signed.into()))
45                    }),
46
47                    "DECIMAL" => self
48                        .try_get::<BigDecimal, _>(idx)
49                        .map_or(Value::Null, |v| bigdecimal_to_json(&v)),
50
51                    "FLOAT" => self.try_get::<f32, _>(idx).map_or(Value::Null, Value::from),
52
53                    "DOUBLE" => self.try_get::<f64, _>(idx).map_or(Value::Null, Value::from),
54
55                    "JSON" => self.try_get::<Value, _>(idx).unwrap_or(Value::Null),
56
57                    // MySQL 9 returns information_schema columns as BINARY/VARBINARY
58                    // even when they contain valid UTF-8. Try String first, then bytes.
59                    "BINARY" | "VARBINARY" => self
60                        .try_get::<String, _>(idx)
61                        .map_or_else(|_| bytes_to_json(self, idx), Value::String),
62
63                    "BLOB" | "TINYBLOB" | "MEDIUMBLOB" | "LONGBLOB" | "BIT" | "GEOMETRY" => bytes_to_json(self, idx),
64
65                    "DATE" => self
66                        .try_get::<NaiveDate, _>(idx)
67                        .map_or(Value::Null, |v| Value::String(v.to_string())),
68
69                    "TIME" => self
70                        .try_get::<NaiveTime, _>(idx)
71                        .map_or(Value::Null, |v| Value::String(v.to_string())),
72
73                    "DATETIME" => self
74                        .try_get::<NaiveDateTime, _>(idx)
75                        .map_or(Value::Null, |v| Value::String(format!("{}T{}", v.date(), v.time()))),
76
77                    // sqlx-mysql's NaiveDateTime decoder only accepts ColumnType::Datetime,
78                    // not Timestamp. DateTime<Utc> accepts both; we then strip the zone
79                    // via naive_utc() so the wire shape matches the naive ISO 8601 form.
80                    "TIMESTAMP" => self.try_get::<DateTime<Utc>, _>(idx).map_or(Value::Null, |v| {
81                        let n = v.naive_utc();
82                        Value::String(format!("{}T{}", n.date(), n.time()))
83                    }),
84
85                    // All other types (VARCHAR, TEXT, ENUM, etc.) → String
86                    _ => self
87                        .try_get::<String, _>(idx)
88                        .map_or_else(|_| bytes_to_json(self, idx), Value::String),
89                }
90            };
91
92            map.insert(column.name().to_string(), value);
93        }
94
95        Value::Object(map)
96    }
97}
98
99/// Extracts a `MySQL` binary column as UTF-8 string, falling back to base64.
100fn bytes_to_json(row: &MySqlRow, idx: usize) -> Value {
101    row.try_get::<Vec<u8>, _>(idx).map_or(Value::Null, |bytes| {
102        String::from_utf8(bytes.clone()).map_or_else(|_| Value::String(BASE64.encode(&bytes)), Value::String)
103    })
104}