1use super::binary::{self, Policy};
16use super::map::{declared_name, family_of, Family, SAFE_INTEGER};
17use crate::error::Result;
18use mysql_async::{Column, Value as Wire};
19use serde_json::Value;
20use std::borrow::Cow;
21
22#[derive(Debug, Clone, Copy)]
30pub struct Conversion {
31 pub binary: Policy,
33}
34
35impl Conversion {
36 #[must_use]
62 pub const fn stable() -> Self {
63 Self {
64 binary: Policy {
65 content: super::binary::Content::Described,
66 },
67 }
68 }
69}
70
71pub fn convert(value: &Wire, column: &Column, options: &Conversion) -> Result<Value> {
79 if matches!(value, Wire::NULL) {
80 return Ok(Value::Null);
81 }
82 match family_of(column) {
83 Family::Integer | Family::WideInteger | Family::Year => Ok(as_integer(value)),
84 Family::FloatingPoint => Ok(as_number(value)),
85 Family::ExactDecimal | Family::Text | Family::SingleChoice | Family::ChoiceSet => {
90 Ok(Value::from(as_text(value)))
91 }
92 Family::Uuid | Family::Inet4 | Family::Inet6 => Ok(Value::from(as_text(value))),
101 Family::Absent => Ok(Value::Null),
102 Family::Bits => Ok(as_bits(value)),
103 Family::Date => Ok(Value::from(as_date(value))),
104 Family::DateTime | Family::Timestamp => {
105 Ok(Value::from(as_date_time(value, column.decimals())))
106 }
107 Family::Time => Ok(Value::from(as_time(value, column.decimals()))),
108 Family::Document => Ok(as_document(value)),
109 Family::Binary => binary::describe(&bytes_of(value), &options.binary),
110 Family::Geometry => binary::describe_geometry(&bytes_of(value), &options.binary),
111 Family::Unknown => Ok(Value::from(declared_name(column.column_type()))),
112 }
113}
114
115fn bytes_of(value: &Wire) -> Cow<'_, [u8]> {
123 match value {
124 Wire::Bytes(bytes) => Cow::Borrowed(bytes),
125 other => Cow::Owned(as_text(other).into_bytes()),
126 }
127}
128
129fn as_text(value: &Wire) -> String {
131 match value {
132 Wire::NULL => String::new(),
133 Wire::Bytes(bytes) => String::from_utf8_lossy(bytes).into_owned(),
134 Wire::Int(number) => number.to_string(),
135 Wire::UInt(number) => number.to_string(),
136 Wire::Float(number) => number.to_string(),
137 Wire::Double(number) => number.to_string(),
138 Wire::Date(..) => as_date_time(value, 6),
139 Wire::Time(..) => as_time(value, 6),
140 }
141}
142
143fn as_integer(value: &Wire) -> Value {
146 let wide = match value {
147 Wire::Int(number) => i128::from(*number),
148 Wire::UInt(number) => i128::from(*number),
149 Wire::Float(number) => return whole_part(f64::from(*number)),
150 Wire::Double(number) => return whole_part(*number),
151 other => {
152 let text = as_text(other);
153 return text.parse::<i128>().map_or(Value::from(text), safe_integer);
154 }
155 };
156 safe_integer(wide)
157}
158
159fn whole_part(number: f64) -> Value {
168 let whole = format!("{:.0}", number.trunc());
169 whole
170 .parse::<i128>()
171 .map_or(Value::from(whole), safe_integer)
172}
173
174fn safe_integer(number: i128) -> Value {
176 if number.unsigned_abs() <= u128::from(SAFE_INTEGER) {
177 if let Ok(narrow) = i64::try_from(number) {
178 return Value::from(narrow);
179 }
180 }
181 Value::from(number.to_string())
182}
183
184fn as_number(value: &Wire) -> Value {
187 let number = match value {
188 Wire::Float(single) => f64::from(*single),
189 Wire::Double(double) => *double,
190 Wire::Int(whole) => {
197 #[allow(clippy::cast_precision_loss)]
198 {
199 *whole as f64
200 }
201 }
202 Wire::UInt(whole) => {
204 #[allow(clippy::cast_precision_loss)]
205 {
206 *whole as f64
207 }
208 }
209 other => {
210 let text = as_text(other);
211 return text
212 .parse::<f64>()
213 .ok()
214 .and_then(serde_json::Number::from_f64)
215 .map_or(Value::from(text), Value::Number);
216 }
217 };
218 serde_json::Number::from_f64(number)
219 .map_or_else(|| Value::from(number.to_string()), Value::Number)
220}
221
222fn as_bits(value: &Wire) -> Value {
224 match value {
225 Wire::Bytes(bytes) => {
226 let mut accumulated: u128 = 0;
227 for byte in bytes.iter().take(16) {
228 accumulated = (accumulated << 8) | u128::from(*byte);
229 }
230 i128::try_from(accumulated)
231 .map_or_else(|_| Value::from(accumulated.to_string()), safe_integer)
232 }
233 other => as_integer(other),
234 }
235}
236
237fn as_date(value: &Wire) -> String {
239 match value {
240 Wire::Date(year, month, day, ..) => format!("{year:04}-{month:02}-{day:02}"),
241 other => as_text(other),
242 }
243}
244
245fn as_date_time(value: &Wire, decimals: u8) -> String {
247 let Wire::Date(year, month, day, hour, minute, second, micros) = value else {
248 return as_text(value);
249 };
250 let mut rendered = format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
251 push_fraction(&mut rendered, *micros, decimals);
252 rendered
253}
254
255fn as_time(value: &Wire, decimals: u8) -> String {
257 let Wire::Time(negative, days, hours, minutes, seconds, micros) = value else {
258 return as_text(value);
259 };
260 let total_hours = u64::from(*days) * 24 + u64::from(*hours);
261 let sign = if *negative { "-" } else { "" };
262 let mut rendered = format!("{sign}{total_hours:02}:{minutes:02}:{seconds:02}");
263 push_fraction(&mut rendered, *micros, decimals);
264 rendered
265}
266
267fn push_fraction(rendered: &mut String, micros: u32, decimals: u8) {
269 let digits = usize::from(decimals.min(6));
270 if digits == 0 {
271 return;
272 }
273 let full = format!("{micros:06}");
274 rendered.push('.');
275 rendered.push_str(&full[..digits]);
276}
277
278fn as_document(value: &Wire) -> Value {
283 let text = as_text(value);
284 serde_json::from_str(&text).unwrap_or_else(|_| Value::from(text))
285}
286
287#[cfg(test)]
288mod tests {
289 use super::*;
290 use mysql_async::consts::ColumnType;
291
292 fn column(kind: ColumnType) -> Column {
293 Column::new(kind)
294 }
295
296 fn with_decimals(kind: ColumnType, decimals: u8) -> Column {
297 Column::new(kind).with_decimals(decimals)
298 }
299
300 fn described() -> Conversion {
304 Conversion {
305 binary: Policy {
306 content: super::super::binary::Content::Described,
307 },
308 }
309 }
310
311 fn convert_ok(value: &Wire, column: &Column) -> Value {
312 convert(value, column, &described()).expect("converts")
313 }
314
315 #[test]
316 fn an_integer_inside_the_safe_range_is_a_number() {
317 let out = convert_ok(&Wire::Int(42), &column(ColumnType::MYSQL_TYPE_LONG));
318 assert_eq!(out, Value::from(42));
319 assert!(out.is_number());
320 }
321
322 #[test]
323 fn an_unsigned_integer_above_the_safe_range_is_text() {
324 let huge = SAFE_INTEGER + 1;
325 let out = convert_ok(&Wire::UInt(huge), &column(ColumnType::MYSQL_TYPE_LONGLONG));
326 assert_eq!(out, Value::from(huge.to_string()));
327 assert!(out.is_string(), "no digit may be lost in the reader");
328 }
329
330 #[test]
331 fn an_exact_decimal_is_always_text_even_when_it_would_seem_to_fit() {
332 let out = convert_ok(
333 &Wire::Bytes(b"1.50".to_vec()),
334 &column(ColumnType::MYSQL_TYPE_NEWDECIMAL),
335 );
336 assert_eq!(out, Value::from("1.50"));
337
338 let small = convert_ok(
339 &Wire::Bytes(b"2".to_vec()),
340 &column(ColumnType::MYSQL_TYPE_DECIMAL),
341 );
342 assert!(small.is_string(), "an exact decimal never becomes a number");
343 }
344
345 #[test]
346 fn floating_point_stays_a_number_and_text_stays_text() {
347 let number = convert_ok(&Wire::Double(1.5), &column(ColumnType::MYSQL_TYPE_DOUBLE));
348 assert_eq!(number, Value::from(1.5));
349 let text = convert_ok(
350 &Wire::Bytes("olá".as_bytes().to_vec()),
351 &column(ColumnType::MYSQL_TYPE_VAR_STRING),
352 );
353 assert_eq!(text, Value::from("olá"));
354 }
355
356 #[test]
357 fn absence_is_its_own_marker_and_not_empty_text() {
358 let absent = convert_ok(&Wire::NULL, &column(ColumnType::MYSQL_TYPE_VAR_STRING));
359 let empty = convert_ok(
360 &Wire::Bytes(Vec::new()),
361 &column(ColumnType::MYSQL_TYPE_VAR_STRING),
362 );
363 assert_eq!(absent, Value::Null);
364 assert_eq!(empty, Value::from(""));
365 assert_ne!(absent, empty, "absence must differ from empty text");
366 }
367
368 #[test]
369 fn a_bit_field_reads_as_one_number() {
370 let out = convert_ok(
371 &Wire::Bytes(vec![0x01, 0x00]),
372 &column(ColumnType::MYSQL_TYPE_BIT),
373 );
374 assert_eq!(out, Value::from(256));
375 }
376
377 #[test]
378 fn a_date_carries_year_month_and_day() {
379 let out = convert_ok(
380 &Wire::Date(2026, 8, 7, 0, 0, 0, 0),
381 &column(ColumnType::MYSQL_TYPE_DATE),
382 );
383 assert_eq!(out, Value::from("2026-08-07"));
384 }
385
386 #[test]
387 fn a_zeroed_date_is_rendered_and_never_ends_the_read() {
388 let out = convert(
389 &Wire::Date(0, 0, 0, 0, 0, 0, 0),
390 &column(ColumnType::MYSQL_TYPE_DATE),
391 &described(),
392 );
393 assert_eq!(out.expect("keeps reading"), Value::from("0000-00-00"));
394 }
395
396 #[test]
397 fn the_fraction_appears_only_as_far_as_the_column_declares_it() {
398 let bare = convert_ok(
399 &Wire::Date(2026, 8, 7, 12, 30, 5, 123_456),
400 &column(ColumnType::MYSQL_TYPE_DATETIME),
401 );
402 assert_eq!(bare, Value::from("2026-08-07 12:30:05"));
403
404 let precise = convert_ok(
405 &Wire::Date(2026, 8, 7, 12, 30, 5, 123_456),
406 &with_decimals(ColumnType::MYSQL_TYPE_TIMESTAMP, 3),
407 );
408 assert_eq!(precise, Value::from("2026-08-07 12:30:05.123"));
409 }
410
411 #[test]
412 fn an_interval_accepts_a_negative_value_and_one_past_a_whole_day() {
413 let backwards = convert_ok(
414 &Wire::Time(true, 0, 2, 30, 0, 0),
415 &column(ColumnType::MYSQL_TYPE_TIME),
416 );
417 assert_eq!(backwards, Value::from("-02:30:00"));
418
419 let long = convert_ok(
420 &Wire::Time(false, 35, 4, 5, 6, 0),
421 &column(ColumnType::MYSQL_TYPE_TIME),
422 );
423 assert_eq!(long, Value::from("844:05:06"));
424 }
425
426 #[test]
427 fn a_year_is_a_number_and_a_label_is_text() {
428 assert_eq!(
429 convert_ok(&Wire::Int(2026), &column(ColumnType::MYSQL_TYPE_YEAR)),
430 Value::from(2026)
431 );
432 assert_eq!(
433 convert_ok(
434 &Wire::Bytes(b"high".to_vec()),
435 &column(ColumnType::MYSQL_TYPE_ENUM)
436 ),
437 Value::from("high")
438 );
439 assert_eq!(
440 convert_ok(
441 &Wire::Bytes(b"read,write".to_vec()),
442 &column(ColumnType::MYSQL_TYPE_SET)
443 ),
444 Value::from("read,write")
445 );
446 }
447
448 #[test]
449 fn a_document_becomes_a_structure_and_never_the_text_of_one() {
450 let out = convert_ok(
451 &Wire::Bytes(br#"{"a":[1,2]}"#.to_vec()),
452 &column(ColumnType::MYSQL_TYPE_JSON),
453 );
454 assert!(
455 out.is_object(),
456 "a document must be a real structure: {out}"
457 );
458 assert_eq!(out["a"][1], Value::from(2));
459 }
460
461 #[test]
462 fn a_malformed_document_becomes_text_rather_than_ending_the_read() {
463 let out = convert(
464 &Wire::Bytes(b"{not json".to_vec()),
465 &column(ColumnType::MYSQL_TYPE_JSON),
466 &described(),
467 );
468 assert_eq!(out.expect("keeps reading"), Value::from("{not json"));
469 }
470
471 #[test]
472 fn a_byte_column_leaves_as_a_description() {
473 let binary_column = Column::new(ColumnType::MYSQL_TYPE_BLOB)
474 .with_character_set(super::super::map::BINARY_CHARSET);
475 let out = convert_ok(&Wire::Bytes(vec![0u8; 5000]), &binary_column);
476 assert_eq!(out["kind"], "binary");
477 assert_eq!(out["bytes"], 5000);
478 }
479
480 #[test]
497 fn the_stable_shaping_differs_from_the_published_one_only_for_raw_bytes() {
498 use super::super::binary::{Content, Policy};
499 use mysql_async::consts::ColumnType;
500
501 let published = Conversion {
505 binary: Policy {
506 content: Content::Raw { max_bytes: 4096 },
507 },
508 };
509
510 let payload = Wire::Bytes(vec![7u8; 16]);
511 let every_type = [
512 ColumnType::MYSQL_TYPE_LONG,
513 ColumnType::MYSQL_TYPE_LONGLONG,
514 ColumnType::MYSQL_TYPE_NEWDECIMAL,
515 ColumnType::MYSQL_TYPE_DOUBLE,
516 ColumnType::MYSQL_TYPE_VAR_STRING,
517 ColumnType::MYSQL_TYPE_BIT,
518 ColumnType::MYSQL_TYPE_DATE,
519 ColumnType::MYSQL_TYPE_DATETIME,
520 ColumnType::MYSQL_TYPE_TIMESTAMP,
521 ColumnType::MYSQL_TYPE_TIME,
522 ColumnType::MYSQL_TYPE_YEAR,
523 ColumnType::MYSQL_TYPE_ENUM,
524 ColumnType::MYSQL_TYPE_SET,
525 ColumnType::MYSQL_TYPE_JSON,
526 ColumnType::MYSQL_TYPE_TYPED_ARRAY,
527 ];
528
529 for kind in every_type {
530 let column = column(kind);
531 let family = super::super::map::family_of(&column);
532 assert!(
533 !matches!(family, Family::Binary | Family::Geometry),
534 "{} carries raw bytes and does not belong in this list",
535 family.as_str()
536 );
537 assert_eq!(
538 convert(&payload, &column, &Conversion::stable()).expect("converts"),
539 convert(&payload, &column, &published).expect("converts"),
540 "the two shapings disagree on {}, so the stable one is no longer safe there",
541 family.as_str()
542 );
543 }
544
545 let packed = Wire::Bytes(vec![0x00, 0x01, 0x02, 0x03]);
549 for carrier in [
550 Column::new(ColumnType::MYSQL_TYPE_BLOB)
551 .with_character_set(super::super::map::BINARY_CHARSET),
552 Column::new(ColumnType::MYSQL_TYPE_VECTOR),
559 Column::new(ColumnType::MYSQL_TYPE_GEOMETRY),
560 ] {
561 let family = super::super::map::family_of(&carrier);
562 assert_ne!(
563 convert(&packed, &carrier, &Conversion::stable()).expect("converts"),
564 convert(&packed, &carrier, &published).expect("converts"),
565 "the two shapings agree on {}, so this test would not catch it moving",
566 family.as_str()
567 );
568 }
569 }
570
571 #[test]
572 fn an_unknown_type_carries_its_declared_name() {
573 let out = convert_ok(
574 &Wire::Bytes(b"anything".to_vec()),
575 &column(ColumnType::MYSQL_TYPE_TYPED_ARRAY),
576 );
577 let text = out.as_str().expect("text");
578 assert!(text.contains("TYPED_ARRAY"), "{text}");
579 }
580}