mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! Converting one server value into the shape the type map publishes.
//!
//! The family comes from the column the server declared, never from the bytes
//! that happened to arrive, so the same column always produces the same shape
//! whether the driver sent it as text or as a packed number.
//!
//! A value the server could store but no calendar accepts, such as a zeroed
//! date, is rendered in its declared form and the read continues. Refusing the
//! whole result set because one cell is odd would lose the rows that are fine.
//!
//! Zone handling belongs to the connection, which sets the session zone once.
//! By the time a value reaches here it is already expressed in the declared
//! zone, so conversion renders it and never shifts it.

use super::binary::{self, Policy};
use super::map::{declared_name, family_of, Family, SAFE_INTEGER};
use crate::error::Result;
use mysql_async::{Column, Value as Wire};
use serde_json::Value;
use std::borrow::Cow;

/// Everything that shapes a value on its way out.
///
/// There is deliberately no `Default`, for the reason given on
/// [`super::binary::Policy`]: every field is a published setting, and a default
/// written here would be a second copy of a number the registry already
/// carries. A value of this type can only be built from the registry, which is
/// a stronger guarantee than a test checking that nobody bypassed it.
#[derive(Debug, Clone, Copy)]
pub struct Conversion {
    /// How byte values are handled.
    pub binary: Policy,
}

impl Conversion {
    /// The shaping for the places a display setting must not reach.
    ///
    /// Two kinds of reading use this, for the same reason and not for
    /// convenience.
    ///
    /// The catalogue readings and the server's own status readings select
    /// names, numbers and short texts out of `information_schema` and the
    /// server's status tables. No column there carries raw bytes, so
    /// `output.binary` has nothing to apply to. Two families do carry it —
    /// `binary` and `geometry` — and
    /// that claim is about data rather than about code, so it is checked by
    /// `the_stable_shaping_differs_from_the_published_one_only_for_raw_bytes`
    /// here and by an acceptance proof against a real server. If either goes
    /// red the answer is to thread the registry shaping through that path.
    ///
    /// The signature over an exported copy is the other. It has to be
    /// reproducible for the same rows, so a checksum that moved when somebody
    /// changed how they like byte values displayed would be a defect and not a
    /// feature.
    ///
    /// This is a statement that those settings do not reach here, and not a
    /// default standing in for them. The two are easy to confuse and the
    /// difference matters: a default would be a second copy of a published
    /// number, which is how a setting comes to have no effect. The numbers here
    /// are deliberately not the published ones.
    #[must_use]
    pub const fn stable() -> Self {
        Self {
            binary: Policy {
                content: super::binary::Content::Described,
            },
        }
    }
}

/// Converts one value under the caller's handling of byte columns.
///
/// # Errors
///
/// Returns a limit failure when a byte value exceeds the ceiling for raw
/// content. Every other condition produces a declared shape rather than a
/// failure, so one odd cell never costs the caller the whole result set.
pub fn convert(value: &Wire, column: &Column, options: &Conversion) -> Result<Value> {
    if matches!(value, Wire::NULL) {
        return Ok(Value::Null);
    }
    match family_of(column) {
        Family::Integer | Family::WideInteger | Family::Year => Ok(as_integer(value)),
        Family::FloatingPoint => Ok(as_number(value)),
        // One arm for two reasons that land in the same place. Text, a single
        // choice and a set of them are text already; an exact decimal is not,
        // and is written as text precisely so that no digit of it is rounded
        // away on the trip through an approximate number.
        Family::ExactDecimal | Family::Text | Family::SingleChoice | Family::ChoiceSet => {
            Ok(Value::from(as_text(value)))
        }
        // The three families this server has and its result packet cannot
        // name. They arrive already rendered by the server — the identifier in
        // its canonical hyphenated text, the network addresses in the forms the
        // published map states — so the work here is to carry that text through
        // untouched and never to re-render it into a form of this build's own
        // choosing. Kept apart from the arm above so that reading this file
        // says which families reach it from the catalogue rather than from the
        // packet.
        Family::Uuid | Family::Inet4 | Family::Inet6 => Ok(Value::from(as_text(value))),
        Family::Absent => Ok(Value::Null),
        Family::Bits => Ok(as_bits(value)),
        Family::Date => Ok(Value::from(as_date(value))),
        Family::DateTime | Family::Timestamp => {
            Ok(Value::from(as_date_time(value, column.decimals())))
        }
        Family::Time => Ok(Value::from(as_time(value, column.decimals()))),
        Family::Document => Ok(as_document(value)),
        Family::Binary => binary::describe(&bytes_of(value), &options.binary),
        Family::Geometry => binary::describe_geometry(&bytes_of(value), &options.binary),
        Family::Unknown => Ok(Value::from(declared_name(column.column_type()))),
    }
}

/// Borrows the bytes of a value, or an empty run when it carries none.
///
/// The borrowed arm is the one that matters. Every byte-bearing value on the
/// reading path arrives as `Wire::Bytes`, and both callers only ever read the
/// run, so owning a copy of it here cost one full duplication of every large
/// value in the answer and bought nothing. The owned arm stays for the values
/// that genuinely have to be rendered before they can be measured.
fn bytes_of(value: &Wire) -> Cow<'_, [u8]> {
    match value {
        Wire::Bytes(bytes) => Cow::Borrowed(bytes),
        other => Cow::Owned(as_text(other).into_bytes()),
    }
}

/// Renders any value as text, losing nothing.
fn as_text(value: &Wire) -> String {
    match value {
        Wire::NULL => String::new(),
        Wire::Bytes(bytes) => String::from_utf8_lossy(bytes).into_owned(),
        Wire::Int(number) => number.to_string(),
        Wire::UInt(number) => number.to_string(),
        Wire::Float(number) => number.to_string(),
        Wire::Double(number) => number.to_string(),
        Wire::Date(..) => as_date_time(value, 6),
        Wire::Time(..) => as_time(value, 6),
    }
}

/// Emits an integer as a number, or as text when a reader could not parse it
/// back without losing a digit.
fn as_integer(value: &Wire) -> Value {
    let wide = match value {
        Wire::Int(number) => i128::from(*number),
        Wire::UInt(number) => i128::from(*number),
        Wire::Float(number) => return whole_part(f64::from(*number)),
        Wire::Double(number) => return whole_part(*number),
        other => {
            let text = as_text(other);
            return text.parse::<i128>().map_or(Value::from(text), safe_integer);
        }
    };
    safe_integer(wide)
}

/// The whole part of an approximate number, as an exact integer.
///
/// Written through a decimal rendering rather than a machine cast. The cast
/// pins anything past the ends of the integer range onto them, so a number too
/// large to be an integer came back as the largest integer there is: a
/// different number, reported as though it were this one. Rendering keeps every
/// digit, and a value no integer can hold is answered as text, which is already
/// what this file does with an integer too wide for a reader to parse back.
fn whole_part(number: f64) -> Value {
    let whole = format!("{:.0}", number.trunc());
    whole
        .parse::<i128>()
        .map_or(Value::from(whole), safe_integer)
}

/// Chooses between a number and text for one integer.
fn safe_integer(number: i128) -> Value {
    if number.unsigned_abs() <= u128::from(SAFE_INTEGER) {
        if let Ok(narrow) = i64::try_from(number) {
            return Value::from(narrow);
        }
    }
    Value::from(number.to_string())
}

/// Emits an approximate number, falling back to text for a value the output
/// shape cannot carry, such as an infinity.
fn as_number(value: &Wire) -> Value {
    let number = match value {
        Wire::Float(single) => f64::from(*single),
        Wire::Double(double) => *double,
        // Allowed, and not a defect: the column this arrives from is declared
        // approximate, so the caller asked for the nearest number this shape
        // can carry. Refusing the whole value to protect digits the column
        // never promised would lose the cell instead of rounding it, and a
        // whole number too wide to be exact here is still the right answer to
        // the question the column asks.
        Wire::Int(whole) => {
            #[allow(clippy::cast_precision_loss)]
            {
                *whole as f64
            }
        }
        // Allowed for the same reason as the signed arm above.
        Wire::UInt(whole) => {
            #[allow(clippy::cast_precision_loss)]
            {
                *whole as f64
            }
        }
        other => {
            let text = as_text(other);
            return text
                .parse::<f64>()
                .ok()
                .and_then(serde_json::Number::from_f64)
                .map_or(Value::from(text), Value::Number);
        }
    };
    serde_json::Number::from_f64(number)
        .map_or_else(|| Value::from(number.to_string()), Value::Number)
}

/// Reads a bit field as one integer, most significant byte first.
fn as_bits(value: &Wire) -> Value {
    match value {
        Wire::Bytes(bytes) => {
            let mut accumulated: u128 = 0;
            for byte in bytes.iter().take(16) {
                accumulated = (accumulated << 8) | u128::from(*byte);
            }
            i128::try_from(accumulated)
                .map_or_else(|_| Value::from(accumulated.to_string()), safe_integer)
        }
        other => as_integer(other),
    }
}

/// Renders a calendar date.
fn as_date(value: &Wire) -> String {
    match value {
        Wire::Date(year, month, day, ..) => format!("{year:04}-{month:02}-{day:02}"),
        other => as_text(other),
    }
}

/// Renders a date and time, with the fraction the column declares.
fn as_date_time(value: &Wire, decimals: u8) -> String {
    let Wire::Date(year, month, day, hour, minute, second, micros) = value else {
        return as_text(value);
    };
    let mut rendered = format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
    push_fraction(&mut rendered, *micros, decimals);
    rendered
}

/// Renders an interval, which may run backwards or past a whole day.
fn as_time(value: &Wire, decimals: u8) -> String {
    let Wire::Time(negative, days, hours, minutes, seconds, micros) = value else {
        return as_text(value);
    };
    let total_hours = u64::from(*days) * 24 + u64::from(*hours);
    let sign = if *negative { "-" } else { "" };
    let mut rendered = format!("{sign}{total_hours:02}:{minutes:02}:{seconds:02}");
    push_fraction(&mut rendered, *micros, decimals);
    rendered
}

/// Appends the fractional part, but only as far as the column declares it.
fn push_fraction(rendered: &mut String, micros: u32, decimals: u8) {
    let digits = usize::from(decimals.min(6));
    if digits == 0 {
        return;
    }
    let full = format!("{micros:06}");
    rendered.push('.');
    rendered.push_str(&full[..digits]);
}

/// Reads a structured document as a real structure.
///
/// A document the server stored but no parser accepts becomes text, so one
/// malformed cell does not end the read.
fn as_document(value: &Wire) -> Value {
    let text = as_text(value);
    serde_json::from_str(&text).unwrap_or_else(|_| Value::from(text))
}

#[cfg(test)]
mod tests {
    use super::*;
    use mysql_async::consts::ColumnType;

    fn column(kind: ColumnType) -> Column {
        Column::new(kind)
    }

    fn with_decimals(kind: ColumnType, decimals: u8) -> Column {
        Column::new(kind).with_decimals(decimals)
    }

    /// The published shape, written here rather than read from the registry,
    /// because a test asserting the registry's own numbers would only restate
    /// them.
    fn described() -> Conversion {
        Conversion {
            binary: Policy {
                content: super::super::binary::Content::Described,
            },
        }
    }

    fn convert_ok(value: &Wire, column: &Column) -> Value {
        convert(value, column, &described()).expect("converts")
    }

    #[test]
    fn an_integer_inside_the_safe_range_is_a_number() {
        let out = convert_ok(&Wire::Int(42), &column(ColumnType::MYSQL_TYPE_LONG));
        assert_eq!(out, Value::from(42));
        assert!(out.is_number());
    }

    #[test]
    fn an_unsigned_integer_above_the_safe_range_is_text() {
        let huge = SAFE_INTEGER + 1;
        let out = convert_ok(&Wire::UInt(huge), &column(ColumnType::MYSQL_TYPE_LONGLONG));
        assert_eq!(out, Value::from(huge.to_string()));
        assert!(out.is_string(), "no digit may be lost in the reader");
    }

    #[test]
    fn an_exact_decimal_is_always_text_even_when_it_would_seem_to_fit() {
        let out = convert_ok(
            &Wire::Bytes(b"1.50".to_vec()),
            &column(ColumnType::MYSQL_TYPE_NEWDECIMAL),
        );
        assert_eq!(out, Value::from("1.50"));

        let small = convert_ok(
            &Wire::Bytes(b"2".to_vec()),
            &column(ColumnType::MYSQL_TYPE_DECIMAL),
        );
        assert!(small.is_string(), "an exact decimal never becomes a number");
    }

    #[test]
    fn floating_point_stays_a_number_and_text_stays_text() {
        let number = convert_ok(&Wire::Double(1.5), &column(ColumnType::MYSQL_TYPE_DOUBLE));
        assert_eq!(number, Value::from(1.5));
        let text = convert_ok(
            &Wire::Bytes("olá".as_bytes().to_vec()),
            &column(ColumnType::MYSQL_TYPE_VAR_STRING),
        );
        assert_eq!(text, Value::from("olá"));
    }

    #[test]
    fn absence_is_its_own_marker_and_not_empty_text() {
        let absent = convert_ok(&Wire::NULL, &column(ColumnType::MYSQL_TYPE_VAR_STRING));
        let empty = convert_ok(
            &Wire::Bytes(Vec::new()),
            &column(ColumnType::MYSQL_TYPE_VAR_STRING),
        );
        assert_eq!(absent, Value::Null);
        assert_eq!(empty, Value::from(""));
        assert_ne!(absent, empty, "absence must differ from empty text");
    }

    #[test]
    fn a_bit_field_reads_as_one_number() {
        let out = convert_ok(
            &Wire::Bytes(vec![0x01, 0x00]),
            &column(ColumnType::MYSQL_TYPE_BIT),
        );
        assert_eq!(out, Value::from(256));
    }

    #[test]
    fn a_date_carries_year_month_and_day() {
        let out = convert_ok(
            &Wire::Date(2026, 8, 7, 0, 0, 0, 0),
            &column(ColumnType::MYSQL_TYPE_DATE),
        );
        assert_eq!(out, Value::from("2026-08-07"));
    }

    #[test]
    fn a_zeroed_date_is_rendered_and_never_ends_the_read() {
        let out = convert(
            &Wire::Date(0, 0, 0, 0, 0, 0, 0),
            &column(ColumnType::MYSQL_TYPE_DATE),
            &described(),
        );
        assert_eq!(out.expect("keeps reading"), Value::from("0000-00-00"));
    }

    #[test]
    fn the_fraction_appears_only_as_far_as_the_column_declares_it() {
        let bare = convert_ok(
            &Wire::Date(2026, 8, 7, 12, 30, 5, 123_456),
            &column(ColumnType::MYSQL_TYPE_DATETIME),
        );
        assert_eq!(bare, Value::from("2026-08-07 12:30:05"));

        let precise = convert_ok(
            &Wire::Date(2026, 8, 7, 12, 30, 5, 123_456),
            &with_decimals(ColumnType::MYSQL_TYPE_TIMESTAMP, 3),
        );
        assert_eq!(precise, Value::from("2026-08-07 12:30:05.123"));
    }

    #[test]
    fn an_interval_accepts_a_negative_value_and_one_past_a_whole_day() {
        let backwards = convert_ok(
            &Wire::Time(true, 0, 2, 30, 0, 0),
            &column(ColumnType::MYSQL_TYPE_TIME),
        );
        assert_eq!(backwards, Value::from("-02:30:00"));

        let long = convert_ok(
            &Wire::Time(false, 35, 4, 5, 6, 0),
            &column(ColumnType::MYSQL_TYPE_TIME),
        );
        assert_eq!(long, Value::from("844:05:06"));
    }

    #[test]
    fn a_year_is_a_number_and_a_label_is_text() {
        assert_eq!(
            convert_ok(&Wire::Int(2026), &column(ColumnType::MYSQL_TYPE_YEAR)),
            Value::from(2026)
        );
        assert_eq!(
            convert_ok(
                &Wire::Bytes(b"high".to_vec()),
                &column(ColumnType::MYSQL_TYPE_ENUM)
            ),
            Value::from("high")
        );
        assert_eq!(
            convert_ok(
                &Wire::Bytes(b"read,write".to_vec()),
                &column(ColumnType::MYSQL_TYPE_SET)
            ),
            Value::from("read,write")
        );
    }

    #[test]
    fn a_document_becomes_a_structure_and_never_the_text_of_one() {
        let out = convert_ok(
            &Wire::Bytes(br#"{"a":[1,2]}"#.to_vec()),
            &column(ColumnType::MYSQL_TYPE_JSON),
        );
        assert!(
            out.is_object(),
            "a document must be a real structure: {out}"
        );
        assert_eq!(out["a"][1], Value::from(2));
    }

    #[test]
    fn a_malformed_document_becomes_text_rather_than_ending_the_read() {
        let out = convert(
            &Wire::Bytes(b"{not json".to_vec()),
            &column(ColumnType::MYSQL_TYPE_JSON),
            &described(),
        );
        assert_eq!(out.expect("keeps reading"), Value::from("{not json"));
    }

    #[test]
    fn a_byte_column_leaves_as_a_description() {
        let binary_column = Column::new(ColumnType::MYSQL_TYPE_BLOB)
            .with_character_set(super::super::map::BINARY_CHARSET);
        let out = convert_ok(&Wire::Bytes(vec![0u8; 5000]), &binary_column);
        assert_eq!(out["kind"], "binary");
        assert_eq!(out["bytes"], 5000);
    }

    /// The claim `Conversion::stable` rests on, checked rather than asserted in
    /// prose.
    ///
    /// The catalogue and status readings use the stable shaping because no
    /// column they touch carries raw bytes. That is a claim about data, and
    /// claims about data go stale. This bounds the damage if it ever does: for
    /// every other family the stable shaping and the published one agree
    /// exactly, so the only way `stable()` can differ from what a caller
    /// configured is a column of one of the two byte-bearing families
    /// appearing on one of those paths. The companion proof, that none does,
    /// needs a server and lives with the acceptance proofs.
    ///
    /// Writing this test is what established that the second family is
    /// `geometry` and not only `binary`: a spatial value the server returned in
    /// its packed form goes through the same policy, so it too carries content
    /// when the content was asked for.
    #[test]
    fn the_stable_shaping_differs_from_the_published_one_only_for_raw_bytes() {
        use super::super::binary::{Content, Policy};
        use mysql_async::consts::ColumnType;

        // The published shaping, written here rather than read from the
        // registry, because this test is about the boundary between the two and
        // not about what the registry currently says.
        let published = Conversion {
            binary: Policy {
                content: Content::Raw { max_bytes: 4096 },
            },
        };

        let payload = Wire::Bytes(vec![7u8; 16]);
        let every_type = [
            ColumnType::MYSQL_TYPE_LONG,
            ColumnType::MYSQL_TYPE_LONGLONG,
            ColumnType::MYSQL_TYPE_NEWDECIMAL,
            ColumnType::MYSQL_TYPE_DOUBLE,
            ColumnType::MYSQL_TYPE_VAR_STRING,
            ColumnType::MYSQL_TYPE_BIT,
            ColumnType::MYSQL_TYPE_DATE,
            ColumnType::MYSQL_TYPE_DATETIME,
            ColumnType::MYSQL_TYPE_TIMESTAMP,
            ColumnType::MYSQL_TYPE_TIME,
            ColumnType::MYSQL_TYPE_YEAR,
            ColumnType::MYSQL_TYPE_ENUM,
            ColumnType::MYSQL_TYPE_SET,
            ColumnType::MYSQL_TYPE_JSON,
            ColumnType::MYSQL_TYPE_TYPED_ARRAY,
        ];

        for kind in every_type {
            let column = column(kind);
            let family = super::super::map::family_of(&column);
            assert!(
                !matches!(family, Family::Binary | Family::Geometry),
                "{} carries raw bytes and does not belong in this list",
                family.as_str()
            );
            assert_eq!(
                convert(&payload, &column, &Conversion::stable()).expect("converts"),
                convert(&payload, &column, &published).expect("converts"),
                "the two shapings disagree on {}, so the stable one is no longer safe there",
                family.as_str()
            );
        }

        // And they must disagree on every family that does carry raw bytes, or
        // the test above would pass for a stable shaping that simply copied the
        // published one. Each is built the way the server declares it.
        let packed = Wire::Bytes(vec![0x00, 0x01, 0x02, 0x03]);
        for carrier in [
            Column::new(ColumnType::MYSQL_TYPE_BLOB)
                .with_character_set(super::super::map::BINARY_CHARSET),
            // This declaration is on the list because a copy of it is only
            // restorable while it reads under the byte rule, and this is the
            // cheapest place that notices when it stops. Routing it to
            // `Unknown` or to text turns the assertion red here, in a unit
            // test, rather than in a restored database where the values have
            // already become zeros and nothing says when they did.
            Column::new(ColumnType::MYSQL_TYPE_VECTOR),
            Column::new(ColumnType::MYSQL_TYPE_GEOMETRY),
        ] {
            let family = super::super::map::family_of(&carrier);
            assert_ne!(
                convert(&packed, &carrier, &Conversion::stable()).expect("converts"),
                convert(&packed, &carrier, &published).expect("converts"),
                "the two shapings agree on {}, so this test would not catch it moving",
                family.as_str()
            );
        }
    }

    #[test]
    fn an_unknown_type_carries_its_declared_name() {
        let out = convert_ok(
            &Wire::Bytes(b"anything".to_vec()),
            &column(ColumnType::MYSQL_TYPE_TYPED_ARRAY),
        );
        let text = out.as_str().expect("text");
        assert!(text.contains("TYPED_ARRAY"), "{text}");
    }
}