Skip to main content

turnloop_mysql/
types.rs

1//! mysql2 conversion policy, independent of JS allocation, timezone databases or
2//! a clock. `Json` and `Date` explicitly request host-side JS construction.
3use crate::{ColumnTypeInfo, Error, RawValue, Result, Value};
4use std::borrow::Cow;
5#[derive(Debug, Clone, Copy, Default)]
6pub struct Options {
7    pub decimal_numbers: bool,
8    pub support_big_numbers: bool,
9    pub big_number_strings: bool,
10    pub date_strings: bool,
11    pub json_strings: bool,
12    /// mysql2's binary-protocol DATETIME/TIMESTAMP string policy: cut the
13    /// fractional seconds of a formatted `date_strings` value to the column's
14    /// declared `decimals` (DATETIME(3) gives `.123`, not `.123000`). Without
15    /// it all six digits are kept. Text-protocol values already arrive with the
16    /// declared digits and are returned verbatim either way.
17    pub truncate_fraction_to_decimals: bool,
18}
19#[derive(Debug, Clone, PartialEq)]
20pub enum Date<'a> {
21    Text(&'a str),
22    Calendar {
23        year: u16,
24        month: u8,
25        day: u8,
26        hour: u8,
27        minute: u8,
28        second: u8,
29        microsecond: u32,
30    },
31}
32#[derive(Debug, Clone, PartialEq)]
33pub enum JsValue<'a> {
34    Null,
35    Number(f64),
36    String(Cow<'a, str>),
37    Buffer(Cow<'a, [u8]>),
38    Json(&'a str),
39    Date(Date<'a>),
40    /// A GEOMETRY value (4-byte little-endian SRID, then WKB). mysql2 turns it
41    /// into point/array objects; like `Json` and `Date` that is host work.
42    Geometry(&'a [u8]),
43}
44fn utf8(b: &[u8]) -> Result<&str> {
45    std::str::from_utf8(b)
46        .map_err(|_| Error::Protocol("non-UTF8 text; decode with the column charset in the host"))
47}
48fn parse<T: std::str::FromStr>(b: &[u8]) -> Result<T> {
49    utf8(b)?
50        .parse()
51        .map_err(|_| Error::Protocol("invalid numeric value"))
52}
53fn bigint(value: i128, options: Options) -> JsValue<'static> {
54    if options.support_big_numbers
55        && (options.big_number_strings
56            || !(-9_007_199_254_740_991..=9_007_199_254_740_991).contains(&value))
57    {
58        JsValue::String(value.to_string().into())
59    } else {
60        JsValue::Number(value as f64)
61    }
62}
63/// Invoke this default conversion after a host typeCast hook chooses `next()`;
64/// raw fields and Column metadata are also available without conversion
65/// (`Row::typed` pairs every value with its `ColumnTypeInfo`).
66///
67/// The policy is chosen by MySQL column type first. `character_set == 63`
68/// (binary) is reported for every non-string column, so it only selects Buffer
69/// for the string/BLOB family; TIME stays a string, BIT a Buffer and GEOMETRY a
70/// `Geometry` request, matching mysql2.
71pub fn decode<'a>(
72    info: ColumnTypeInfo,
73    value: RawValue<'a>,
74    options: Options,
75) -> Result<JsValue<'a>> {
76    let kind = info.column_type as u8;
77    Ok(match value {
78        RawValue::Null => JsValue::Null,
79        RawValue::Bytes(bytes) => match kind {
80            0 | 246 => {
81                if options.decimal_numbers {
82                    JsValue::Number(parse(bytes)?)
83                } else {
84                    JsValue::String(utf8(bytes)?.into())
85                }
86            }
87            1..=5 | 9 | 13 => JsValue::Number(parse(bytes)?),
88            8 => {
89                if options.support_big_numbers {
90                    let value: i128 = parse(bytes)?;
91                    if options.big_number_strings
92                        || !(-9_007_199_254_740_991..=9_007_199_254_740_991).contains(&value)
93                    {
94                        JsValue::String(utf8(bytes)?.into())
95                    } else {
96                        JsValue::Number(value as f64)
97                    }
98                } else {
99                    JsValue::Number(parse(bytes)?)
100                }
101            }
102            7 | 10 | 12 | 14 => {
103                if options.date_strings {
104                    JsValue::String(utf8(bytes)?.into())
105                } else {
106                    JsValue::Date(Date::Text(utf8(bytes)?))
107                }
108            }
109            245 => {
110                if options.json_strings {
111                    JsValue::String(utf8(bytes)?.into())
112                } else {
113                    JsValue::Json(utf8(bytes)?)
114                }
115            }
116            11 => JsValue::String(utf8(bytes)?.into()),
117            16 => JsValue::Buffer(bytes.into()),
118            255 => JsValue::Geometry(bytes),
119            _ if info.character_set == 63 => JsValue::Buffer(bytes.into()),
120            _ => JsValue::String(utf8(bytes)?.into()),
121        },
122        RawValue::Scalar(Value::NULL) => JsValue::Null,
123        RawValue::Scalar(Value::Int(n)) => {
124            if kind == 8 {
125                bigint(n as i128, options)
126            } else {
127                JsValue::Number(n as f64)
128            }
129        }
130        RawValue::Scalar(Value::UInt(n)) => {
131            if kind == 8 {
132                bigint(n as i128, options)
133            } else {
134                JsValue::Number(n as f64)
135            }
136        }
137        RawValue::Scalar(Value::Float(n)) => JsValue::Number(n as f64),
138        RawValue::Scalar(Value::Double(n)) => JsValue::Number(n),
139        RawValue::Scalar(Value::Bytes(_)) => {
140            return Err(Error::State("use borrowed bytes for a wire field"));
141        }
142        RawValue::Scalar(Value::Date(year, month, day, hour, minute, second, microsecond)) => {
143            if options.date_strings {
144                let s = if kind == 10 {
145                    format!("{year:04}-{month:02}-{day:02}")
146                } else {
147                    let mut s =
148                        format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
149                    let digits = if options.truncate_fraction_to_decimals {
150                        usize::from(info.decimals.min(6))
151                    } else {
152                        6
153                    };
154                    if microsecond != 0 && digits > 0 {
155                        let fraction = format!("{microsecond:06}");
156                        s.push('.');
157                        s.push_str(&fraction[..digits]);
158                    }
159                    s
160                };
161                JsValue::String(s.into())
162            } else {
163                JsValue::Date(Date::Calendar {
164                    year,
165                    month,
166                    day,
167                    hour,
168                    minute,
169                    second,
170                    microsecond,
171                })
172            }
173        }
174        RawValue::Scalar(Value::Time(negative, days, hour, minute, second, microsecond)) => {
175            let hour = days as u64 * 24 + hour as u64;
176            let mut s = format!(
177                "{}{hour:02}:{minute:02}:{second:02}",
178                if negative { "-" } else { "" }
179            );
180            if microsecond != 0 {
181                s.push_str(&format!(".{microsecond:06}"));
182            }
183            JsValue::String(s.into())
184        }
185    })
186}
187#[cfg(test)]
188mod tests {
189    use super::*;
190    use crate::{ColumnFlags, ColumnType};
191    fn info(t: ColumnType) -> ColumnTypeInfo {
192        ColumnTypeInfo {
193            column_type: t,
194            flags: ColumnFlags::empty(),
195            character_set: 45,
196            decimals: 0,
197        }
198    }
199    /// MySQL reports charset 63 for every non-string column; the column type,
200    /// not the charset, must pick TIME/BIT/GEOMETRY's policy.
201    #[test]
202    fn binary_charset_does_not_collapse_time_bit_and_geometry() {
203        let binary = |t| ColumnTypeInfo {
204            character_set: 63,
205            ..info(t)
206        };
207        let decode = |t, bytes| decode(binary(t), RawValue::Bytes(bytes), Options::default());
208        assert_eq!(
209            decode(ColumnType::MYSQL_TYPE_TIME, b"-838:59:59.5"),
210            Ok(JsValue::String("-838:59:59.5".into()))
211        );
212        assert_eq!(
213            decode(ColumnType::MYSQL_TYPE_BIT, &[0b101]),
214            Ok(JsValue::Buffer(Cow::Borrowed(&[0b101])))
215        );
216        let point = [0, 0, 0, 0, 1, 1, 0, 0, 0];
217        assert_eq!(
218            decode(ColumnType::MYSQL_TYPE_GEOMETRY, &point),
219            Ok(JsValue::Geometry(&point))
220        );
221        assert_eq!(
222            decode(ColumnType::MYSQL_TYPE_VAR_STRING, b"\xff\x00"),
223            Ok(JsValue::Buffer(Cow::Borrowed(b"\xff\x00"))),
224            "VARBINARY still follows the binary charset"
225        );
226    }
227    #[test]
228    fn datetime_fraction_follows_the_column_decimals_on_request() {
229        let value = || RawValue::Scalar(Value::Date(2026, 9, 22, 10, 11, 12, 123_456));
230        let datetime = |decimals| ColumnTypeInfo {
231            decimals,
232            ..info(ColumnType::MYSQL_TYPE_DATETIME)
233        };
234        let strings = Options {
235            date_strings: true,
236            ..Options::default()
237        };
238        let truncated = Options {
239            truncate_fraction_to_decimals: true,
240            ..strings
241        };
242        assert_eq!(
243            decode(datetime(3), value(), strings),
244            Ok(JsValue::String("2026-09-22 10:11:12.123456".into()))
245        );
246        assert_eq!(
247            decode(datetime(3), value(), truncated),
248            Ok(JsValue::String("2026-09-22 10:11:12.123".into()))
249        );
250        assert_eq!(
251            decode(datetime(6), value(), truncated),
252            Ok(JsValue::String("2026-09-22 10:11:12.123456".into()))
253        );
254        assert_eq!(
255            decode(datetime(0), value(), truncated),
256            Ok(JsValue::String("2026-09-22 10:11:12".into()))
257        );
258        assert_eq!(
259            decode(
260                ColumnTypeInfo {
261                    decimals: 2,
262                    ..info(ColumnType::MYSQL_TYPE_TIMESTAMP)
263                },
264                value(),
265                truncated
266            ),
267            Ok(JsValue::String("2026-09-22 10:11:12.12".into()))
268        );
269    }
270    #[test]
271    fn node_conversion_options() {
272        let decimal = info(ColumnType::MYSQL_TYPE_NEWDECIMAL);
273        assert_eq!(
274            decode(decimal, RawValue::Bytes(b"1.2300"), Options::default()).unwrap(),
275            JsValue::String("1.2300".into())
276        );
277        let big = info(ColumnType::MYSQL_TYPE_LONGLONG);
278        assert_eq!(
279            decode(
280                big,
281                RawValue::Bytes(b"18446744073709551615"),
282                Options {
283                    support_big_numbers: true,
284                    ..Options::default()
285                }
286            )
287            .unwrap(),
288            JsValue::String("18446744073709551615".into())
289        );
290        assert_eq!(
291            decode(
292                info(ColumnType::MYSQL_TYPE_TINY),
293                RawValue::Bytes(b"1"),
294                Options::default()
295            )
296            .unwrap(),
297            JsValue::Number(1.)
298        );
299        assert_eq!(
300            decode(
301                info(ColumnType::MYSQL_TYPE_JSON),
302                RawValue::Bytes(b"{\"x\":1}"),
303                Options::default()
304            )
305            .unwrap(),
306            JsValue::Json("{\"x\":1}")
307        );
308        let mut blob = info(ColumnType::MYSQL_TYPE_BLOB);
309        blob.character_set = 63;
310        assert_eq!(
311            decode(blob, RawValue::Bytes(&[0, 255]), Options::default()).unwrap(),
312            JsValue::Buffer(Cow::Borrowed(&[0, 255]))
313        );
314        assert_eq!(
315            decode(
316                info(ColumnType::MYSQL_TYPE_DATE),
317                RawValue::Scalar(Value::Date(2026, 9, 14, 0, 0, 0, 0)),
318                Options {
319                    date_strings: true,
320                    ..Options::default()
321                }
322            )
323            .unwrap(),
324            JsValue::String("2026-09-14".into())
325        );
326    }
327}