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
//! The published type map: one output shape per database type family.
//!
//! The table is fixed. Nothing in the product may parameterise it, because a
//! configurable conversion makes the same row arrive in different shapes on
//! different hosts, and a caller can then no longer trust a single reading of
//! the contract.
//!
//! Callers read this map once through `meta schema --types` and never inspect
//! the server to learn how a value will look.

use mysql_async::consts::{ColumnFlags, ColumnType};
use mysql_async::Column;

/// Character set the server uses to mark a column as raw bytes.
pub const BINARY_CHARSET: u16 = 63;

/// Largest integer every reader parses back without losing a digit.
///
/// Above this magnitude an integer is emitted as text, because a reader that
/// parses numbers as double precision would silently round the last digits.
pub const SAFE_INTEGER: u64 = 9_007_199_254_740_991;

/// The forms a value may take on the primary channel.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shape {
    /// A JSON number.
    Number,
    /// A JSON string.
    Text,
    /// The absence marker, distinct from empty text.
    Absent,
    /// A real structure, never the text of one.
    Structure,
    /// A short description object standing in for a large value.
    Description,
}

impl Shape {
    /// The stable name of this shape, as published.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Number => "number",
            Self::Text => "text",
            Self::Absent => "absent",
            Self::Structure => "structure",
            Self::Description => "description",
        }
    }
}

/// One database type family, as published.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Family {
    /// Integer inside the safe range.
    Integer,
    /// Integer outside the safe range, signed or not.
    WideInteger,
    /// Exact decimal.
    ExactDecimal,
    /// Approximate floating point.
    FloatingPoint,
    /// Text and long text.
    Text,
    /// Absence of value.
    Absent,
    /// Bit field.
    Bits,
    /// Calendar date.
    Date,
    /// Date and time.
    DateTime,
    /// Point in time, in the declared zone.
    Timestamp,
    /// Interval of time, possibly negative or beyond a day.
    Time,
    /// Calendar year.
    Year,
    /// One label out of a declared list.
    SingleChoice,
    /// Several labels out of a declared list.
    ChoiceSet,
    /// Structured document.
    Document,
    /// Universal identifier of a hundred and twenty-eight bits.
    Uuid,
    /// Network address of the fourth version.
    Inet4,
    /// Network address of the sixth version.
    Inet6,
    /// Raw bytes.
    Binary,
    /// Spatial value.
    Geometry,
    /// A type this release does not know.
    Unknown,
}

impl Family {
    /// The stable name of this family, as published.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Integer => "integer",
            Self::WideInteger => "wide_integer",
            Self::ExactDecimal => "exact_decimal",
            Self::FloatingPoint => "floating_point",
            Self::Text => "text",
            Self::Absent => "absent",
            Self::Bits => "bits",
            Self::Date => "date",
            Self::DateTime => "date_time",
            Self::Timestamp => "timestamp",
            Self::Time => "time",
            Self::Year => "year",
            Self::SingleChoice => "single_choice",
            Self::ChoiceSet => "choice_set",
            Self::Document => "document",
            Self::Uuid => "uuid",
            Self::Inet4 => "inet4",
            Self::Inet6 => "inet6",
            Self::Binary => "binary",
            Self::Geometry => "geometry",
            Self::Unknown => "unknown",
        }
    }

    /// The output shape this family always takes.
    #[must_use]
    pub const fn shape(self) -> Shape {
        match self {
            Self::Integer | Self::FloatingPoint | Self::Bits | Self::Year => Shape::Number,
            Self::WideInteger
            | Self::ExactDecimal
            | Self::Text
            | Self::Date
            | Self::DateTime
            | Self::Timestamp
            | Self::Time
            | Self::SingleChoice
            | Self::ChoiceSet
            | Self::Geometry
            | Self::Uuid
            | Self::Inet4
            | Self::Inet6
            | Self::Unknown => Shape::Text,
            Self::Absent => Shape::Absent,
            Self::Document => Shape::Structure,
            Self::Binary => Shape::Description,
        }
    }
}

/// One published row of the type map.
#[derive(Debug, Clone, Copy)]
pub struct Entry {
    /// The family this row describes.
    pub family: Family,
    /// The shape values of that family always take.
    pub shape: Shape,
    /// Why the shape is what it is, in one sentence.
    pub note: &'static str,
}

/// The whole published table, in a fixed order.
///
/// The order never varies, so two runs of `meta schema --types` produce the
/// same bytes.
///
/// # Examples
///
/// The table is fixed at build time, so two readings of it are the same
/// reading. That is the whole promise, and asserting it here means a change
/// that made the order depend on anything would fail the build of the manual
/// rather than only the byte comparison of some later answer:
///
/// ```
/// use mariadb_cli::types::map::published;
///
/// let once: Vec<_> = published().iter().map(|entry| entry.family).collect();
/// let twice: Vec<_> = published().iter().map(|entry| entry.family).collect();
/// assert_eq!(once, twice);
/// assert!(!published().is_empty(), "an empty map would publish nothing");
/// ```
#[must_use]
pub const fn published() -> &'static [Entry] {
    PUBLISHED
}

/// Builds one published row, so shape and family can never drift apart.
const fn row(family: Family, note: &'static str) -> Entry {
    Entry {
        family,
        shape: family.shape(),
        note,
    }
}

/// The table itself, built once at compile time.
static PUBLISHED: &[Entry] = &[
    row(
        Family::Integer,
        "fits the range every reader parses exactly",
    ),
    row(
        Family::WideInteger,
        "text, so no digit is lost in the reader",
    ),
    row(
        Family::ExactDecimal,
        "always text, because a number would round it",
    ),
    row(
        Family::FloatingPoint,
        "already approximate, so a number loses nothing",
    ),
    row(Family::Text, "the bytes as text"),
    row(Family::Absent, "its own marker, never empty text"),
    row(Family::Bits, "the bits read as one integer"),
    row(Family::Date, "year, month and day"),
    row(
        Family::DateTime,
        "date and time, with the fraction the column declares",
    ),
    row(
        Family::Timestamp,
        "same form as date and time, in the declared zone",
    ),
    row(
        Family::Time,
        "an interval, which may be negative or exceed a day",
    ),
    row(Family::Year, "a plain calendar year"),
    row(Family::SingleChoice, "the chosen label"),
    row(Family::ChoiceSet, "the chosen labels, separated by commas"),
    row(Family::Document, "a real structure, never the text of one"),
    row(
        Family::Uuid,
        "the canonical text of the identifier, with its hyphens",
    ),
    row(Family::Inet4, "four numbers separated by dots, as text"),
    row(
        Family::Inet6,
        "the shortened canonical text the server itself returns",
    ),
    row(
        Family::Binary,
        "size, apparent kind and signature, never the content",
    ),
    row(
        Family::Geometry,
        "the readable form the server itself returned",
    ),
    row(Family::Unknown, "text carrying the declared type name"),
];

/// The family a column belongs to.
///
/// The decision comes from the column the server declared, never from the
/// shape of the bytes that arrived, so an empty result set and a full one
/// describe their columns identically.
#[must_use]
pub fn family_of(column: &Column) -> Family {
    let kind = column.column_type();
    match kind {
        ColumnType::MYSQL_TYPE_TINY
        | ColumnType::MYSQL_TYPE_SHORT
        | ColumnType::MYSQL_TYPE_LONG
        | ColumnType::MYSQL_TYPE_INT24
        | ColumnType::MYSQL_TYPE_LONGLONG => Family::Integer,
        ColumnType::MYSQL_TYPE_DECIMAL | ColumnType::MYSQL_TYPE_NEWDECIMAL => Family::ExactDecimal,
        ColumnType::MYSQL_TYPE_FLOAT | ColumnType::MYSQL_TYPE_DOUBLE => Family::FloatingPoint,
        ColumnType::MYSQL_TYPE_NULL => Family::Absent,
        ColumnType::MYSQL_TYPE_BIT => Family::Bits,
        ColumnType::MYSQL_TYPE_DATE | ColumnType::MYSQL_TYPE_NEWDATE => Family::Date,
        ColumnType::MYSQL_TYPE_DATETIME | ColumnType::MYSQL_TYPE_DATETIME2 => Family::DateTime,
        ColumnType::MYSQL_TYPE_TIMESTAMP | ColumnType::MYSQL_TYPE_TIMESTAMP2 => Family::Timestamp,
        ColumnType::MYSQL_TYPE_TIME | ColumnType::MYSQL_TYPE_TIME2 => Family::Time,
        ColumnType::MYSQL_TYPE_YEAR => Family::Year,
        ColumnType::MYSQL_TYPE_ENUM => Family::SingleChoice,
        ColumnType::MYSQL_TYPE_SET => Family::ChoiceSet,
        ColumnType::MYSQL_TYPE_JSON => Family::Document,
        // This column holds raw bytes, and the byte rule is what keeps a copy
        // of it restorable. `holds_raw_bytes` in `datamove::literal` asks this
        // map which values leave a copy as a numeric literal, and a value that
        // leaves quoted instead does not survive the round trip: the server
        // rejects the text and, restoring outside strict mode, writes zeros in
        // its place. MariaDB hit this in its own dump tool and fixed it in
        // 11.7.2 by forcing the numeric form for exactly three declarations —
        // this one, geometry and bit — which is the same set `holds_raw_bytes`
        // carries. Routing this column anywhere else silently reintroduces
        // that loss here, so the mapping is load-bearing rather than tidy.
        ColumnType::MYSQL_TYPE_VECTOR => Family::Binary,
        ColumnType::MYSQL_TYPE_GEOMETRY => Family::Geometry,
        ColumnType::MYSQL_TYPE_VARCHAR
        | ColumnType::MYSQL_TYPE_VAR_STRING
        | ColumnType::MYSQL_TYPE_STRING
        | ColumnType::MYSQL_TYPE_BLOB
        | ColumnType::MYSQL_TYPE_TINY_BLOB
        | ColumnType::MYSQL_TYPE_MEDIUM_BLOB
        | ColumnType::MYSQL_TYPE_LONG_BLOB => textual_or_binary(column),
        ColumnType::MYSQL_TYPE_TYPED_ARRAY | ColumnType::MYSQL_TYPE_UNKNOWN => Family::Unknown,
    }
}

/// Tells a character column from a byte column.
///
/// The server marks raw bytes with the binary character set; the binary flag
/// alone also appears on collated text, so the character set decides first.
fn textual_or_binary(column: &Column) -> Family {
    if column.character_set() == BINARY_CHARSET {
        return Family::Binary;
    }
    if column.character_set() == 0 && column.flags().contains(ColumnFlags::BINARY_FLAG) {
        return Family::Binary;
    }
    Family::Text
}

/// The families this server has that its result packet cannot name.
///
/// The key is the type name as the catalogue writes it, in the lower case the
/// catalogue already uses.
static SERVER_ONLY: &[(&str, Family)] = &[
    ("uuid", Family::Uuid),
    ("inet4", Family::Inet4),
    ("inet6", Family::Inet6),
];

/// The family a catalogue type name declares, when it declares a server-only one.
///
/// # Why the catalogue and not the packet
///
/// Measured against the driver this build carries: the column packet of a
/// result carries no extended type mark, so a universal identifier and a
/// network address arrive under the same packet type as ordinary text. On
/// retrieval the server hands both back already rendered — the identifier in
/// its canonical hyphenated text, the sixth-version address in the shortened
/// form the server itself chooses — and a reader that only looked at the
/// packet would call all three `text` and be right about the shape by
/// accident while being wrong about the family.
///
/// So the family of these three is read from the type the catalogue declares
/// for the stored column, and from nothing else. A caller that has an origin
/// for a result column — the stored table and stored column the server names,
/// which [`crate::exec::lineage::declared_origin`] already reads — can ask the
/// catalogue for that type and pass it here.
///
/// A name this build does not know is not guessed at: the answer is `None` and
/// the packet decides, which is what already happened before these families
/// existed.
#[must_use]
pub fn declared_family(declared: &str) -> Option<Family> {
    let named = declared.trim().to_ascii_lowercase();
    SERVER_ONLY
        .iter()
        .find(|(name, _)| *name == named)
        .map(|(_, family)| *family)
}

/// The family of a result column, preferring the type its origin declares.
///
/// A column with no declared origin — an expression, the result of a function,
/// anything the server produced rather than read from a table — has no
/// catalogue type to ask, so it falls to [`family_of`] and the packet. That is
/// a real condition of this server rather than a shortcoming of this build, so
/// the published map states it out loud instead of leaving a caller to find it.
#[must_use]
pub fn family_for(column: &Column, declared: Option<&str>) -> Family {
    declared
        .and_then(declared_family)
        .unwrap_or_else(|| family_of(column))
}

/// The declared name of a column type, for the unknown family.
#[must_use]
pub fn declared_name(kind: ColumnType) -> String {
    format!("{kind:?}")
}

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

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

    fn binary_column(kind: ColumnType) -> Column {
        Column::new(kind).with_character_set(BINARY_CHARSET)
    }

    #[test]
    fn every_published_family_declares_its_shape_once() {
        let table = published();
        assert_eq!(table.len(), 21, "the published table has a fixed length");
        for entry in table {
            assert_eq!(
                entry.shape,
                entry.family.shape(),
                "{}",
                entry.family.as_str()
            );
            assert!(!entry.note.is_empty());
        }
    }

    #[test]
    fn family_names_are_unique_so_a_caller_can_branch_on_them() {
        let mut names: Vec<&str> = published()
            .iter()
            .map(|entry| entry.family.as_str())
            .collect();
        names.sort_unstable();
        let before = names.len();
        names.dedup();
        assert_eq!(names.len(), before, "family names must not repeat");
    }

    #[test]
    fn exact_decimal_is_text_and_floating_point_is_a_number() {
        assert_eq!(
            family_of(&column(ColumnType::MYSQL_TYPE_NEWDECIMAL)),
            Family::ExactDecimal
        );
        assert_eq!(Family::ExactDecimal.shape(), Shape::Text);
        assert_eq!(
            family_of(&column(ColumnType::MYSQL_TYPE_DOUBLE)),
            Family::FloatingPoint
        );
        assert_eq!(Family::FloatingPoint.shape(), Shape::Number);
    }

    #[test]
    fn a_document_is_a_structure_and_never_text() {
        assert_eq!(
            family_of(&column(ColumnType::MYSQL_TYPE_JSON)),
            Family::Document
        );
        assert_eq!(Family::Document.shape(), Shape::Structure);
    }

    #[test]
    fn absence_has_a_shape_of_its_own_apart_from_text() {
        assert_ne!(Family::Absent.shape(), Family::Text.shape());
        assert_eq!(Family::Absent.shape(), Shape::Absent);
    }

    #[test]
    fn the_character_set_tells_a_byte_column_from_a_text_one() {
        assert_eq!(
            family_of(&binary_column(ColumnType::MYSQL_TYPE_BLOB)),
            Family::Binary
        );
        assert_eq!(
            family_of(&column(ColumnType::MYSQL_TYPE_BLOB)),
            Family::Text
        );
        assert_eq!(
            family_of(&column(ColumnType::MYSQL_TYPE_VAR_STRING)),
            Family::Text
        );
    }

    #[test]
    fn each_temporal_type_lands_on_its_own_family() {
        assert_eq!(
            family_of(&column(ColumnType::MYSQL_TYPE_DATE)),
            Family::Date
        );
        assert_eq!(
            family_of(&column(ColumnType::MYSQL_TYPE_DATETIME)),
            Family::DateTime
        );
        assert_eq!(
            family_of(&column(ColumnType::MYSQL_TYPE_TIMESTAMP)),
            Family::Timestamp
        );
        assert_eq!(
            family_of(&column(ColumnType::MYSQL_TYPE_TIME)),
            Family::Time
        );
        assert_eq!(
            family_of(&column(ColumnType::MYSQL_TYPE_YEAR)),
            Family::Year
        );
    }

    /// FR-130. The three families this server has are read from the type the
    /// catalogue declares, because the packet cannot tell them from text. This
    /// is the reading that says so: the very same packet answers `text` and
    /// answers each family once the catalogue is consulted.
    #[test]
    fn a_server_only_family_comes_from_the_catalogue_and_never_from_the_packet() {
        let carrier = column(ColumnType::MYSQL_TYPE_VAR_STRING);
        assert_eq!(
            family_of(&carrier),
            Family::Text,
            "the packet of this server cannot name these families"
        );

        for (declared, family) in [
            ("uuid", Family::Uuid),
            ("inet4", Family::Inet4),
            ("inet6", Family::Inet6),
        ] {
            assert_eq!(declared_family(declared), Some(family));
            assert_eq!(family_for(&carrier, Some(declared)), family);
            assert_eq!(family.shape(), Shape::Text, "{declared}");
        }
        assert_eq!(declared_family("  INET6 "), Some(Family::Inet6));
    }

    /// A column the server produced rather than read has no catalogue type to
    /// ask about, so it keeps the family the packet gives it. A type name this
    /// build does not know is treated the same way rather than guessed at.
    #[test]
    fn a_column_with_no_declared_origin_keeps_the_family_of_the_packet() {
        let carrier = column(ColumnType::MYSQL_TYPE_VAR_STRING);
        assert_eq!(family_for(&carrier, None), Family::Text);
        assert_eq!(family_for(&carrier, Some("something_else")), Family::Text);
        assert_eq!(declared_family("something_else"), None);
    }

    #[test]
    fn an_unknown_type_keeps_its_declared_name() {
        assert_eq!(
            family_of(&column(ColumnType::MYSQL_TYPE_TYPED_ARRAY)),
            Family::Unknown
        );
        let name = declared_name(ColumnType::MYSQL_TYPE_TYPED_ARRAY);
        assert!(name.contains("TYPED_ARRAY"), "{name}");
    }
}