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