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
//! Finding the object a caller meant, and saying which one that was.
//!
//! A caller may write a name in a different case from the one the server
//! records. On one server that finds the object and on another it finds
//! nothing, so the name the server actually keeps travels back with the
//! answer rather than being quietly substituted.
//!
//! A name nothing answers to never produces a bare refusal either: the names
//! that are visible and closest to it come with the failure, because a caller
//! that guessed wrongly needs the right guess and not the news that it failed.

use crate::conn::OrFailure;
use crate::error::{Failure, Result};
use crate::sql::ident;
use mysql_async::prelude::Queryable;
use mysql_async::Conn;

/// How this server treats upper and lower case in an object name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NameCase {
    /// Two names differing only by case are two different objects.
    Sensitive,
    /// Case is ignored and names are recorded in lower case.
    InsensitiveStoredLower,
    /// Case is ignored and names are recorded as they were written.
    InsensitiveStoredAsWritten,
    /// The server did not say.
    Unknown,
}

impl NameCase {
    /// The stable name of this rule, as published.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Sensitive => "sensitive",
            Self::InsensitiveStoredLower => "insensitive_stored_lower",
            Self::InsensitiveStoredAsWritten => "insensitive_stored_as_written",
            Self::Unknown => "unknown",
        }
    }

    /// The rule the server's own setting stands for.
    #[must_use]
    pub const fn from_setting(setting: i64) -> Self {
        match setting {
            0 => Self::Sensitive,
            1 => Self::InsensitiveStoredLower,
            2 => Self::InsensitiveStoredAsWritten,
            _ => Self::Unknown,
        }
    }
}

/// Asks the server how it treats case in an object name.
///
/// # Errors
///
/// Returns the mapped driver failure when the setting cannot be read.
pub async fn name_case(connection: &mut Conn) -> Result<NameCase> {
    let setting: Option<i64> = connection
        .query_first("SELECT @@lower_case_table_names")
        .await
        .or_failure()?;
    Ok(setting.map_or(NameCase::Unknown, NameCase::from_setting))
}

/// A name as it was asked for, next to the name the server actually keeps.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Resolved {
    /// The name the caller wrote.
    pub asked: String,
    /// The name the server records.
    pub actual: String,
}

impl Resolved {
    /// Whether the caller reached the object under a different case.
    ///
    /// Worth declaring, because the same call against a server that tells case
    /// apart would have found nothing.
    #[must_use]
    pub fn differs_only_by_case(&self) -> bool {
        self.asked != self.actual && self.asked.eq_ignore_ascii_case(&self.actual)
    }
}

/// The delimiter this server wraps a written-out name in.
const DELIMITER: char = '`';

/// How many parts a name path may have on this server family.
///
/// A database and an object, and nothing above the database, because this
/// server keeps no level above one.
const MOST_PARTS: usize = 2;

/// A written name, split into the database it named and the object itself.
///
/// # Why a name may carry its own database
///
/// `schema map` writes every object as `database.object`, because a map may
/// span more than one database and a bare name in it would say nothing about
/// which. The commands that then read one object receive that same name back,
/// so a caller chaining the two — which is the shape this product exists for —
/// used to be told the object does not exist.
///
/// The database a name carries wins over the one in force, which is the rule
/// this server applies to its own statements: a session sitting on one database
/// still reads `other.table` by naming it. Following the server rather than
/// inventing a rule means there is nothing new for a caller to learn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Qualified {
    /// The database the name carried, when it carried one.
    pub database: Option<String>,
    /// The object on its own, with no database in front of it.
    pub name: String,
}

impl Qualified {
    /// The database this reading is really about.
    ///
    /// The one the name carried wins, and the one in force serves when the
    /// name carried none.
    #[must_use]
    pub fn database_or(&self, in_force: Option<String>) -> Option<String> {
        self.database.clone().or(in_force)
    }

    /// Whether the name carried a database other than the one in force.
    ///
    /// Worth asking, because the answer then declares which database it really
    /// read, rather than leaving a caller to assume the one they named.
    #[must_use]
    pub fn overrides(&self, in_force: Option<&str>) -> bool {
        match (self.database.as_deref(), in_force) {
            (Some(carried), Some(in_force)) => !carried.eq_ignore_ascii_case(in_force),
            _ => false,
        }
    }
}

/// Splits a written name into the database it names and the object itself.
///
/// A name carrying no database comes back whole. So does a name whose text
/// cannot be read as a path: it is not refused here, because it then travels
/// the ordinary route and fails, if it fails, carrying the nearest visible
/// names, which serves a caller better than a second kind of refusal.
///
/// # Examples
///
/// A bare name is left alone, and a qualified one is taken apart:
///
/// ```
/// use mariadb_cli::introspect::names::split;
///
/// assert_eq!(split("orders").database, None);
/// assert_eq!(split("orders").name, "orders");
/// assert_eq!(split("shop.orders").database.as_deref(), Some("shop"));
/// assert_eq!(split("shop.orders").name, "orders");
/// ```
///
/// A name that really carries a dot is written in the server's own delimiter,
/// and then it stays one name:
///
/// ```
/// use mariadb_cli::introspect::names::split;
///
/// assert_eq!(split("`a.b`").database, None);
/// assert_eq!(split("`a.b`").name, "a.b");
/// ```
#[must_use]
pub fn split(asked: &str) -> Qualified {
    let whole = || Qualified {
        database: None,
        name: asked.to_owned(),
    };
    match parts(asked).as_deref() {
        Some([name]) => Qualified {
            database: None,
            name: name.clone(),
        },
        Some([database, name]) => Qualified {
            database: Some(database.clone()),
            name: name.clone(),
        },
        _ => whole(),
    }
}

/// Reads a written name as a path, honouring the server's own delimiter.
///
/// Answers `None` for text that is not a well-formed path: an unclosed
/// delimiter, an empty part, ordinary text sitting outside the delimiters of a
/// part that used them, or more parts than this server has levels.
fn parts(asked: &str) -> Option<Vec<String>> {
    let mut found: Vec<String> = Vec::new();
    let mut current = String::new();
    // Inside a delimited part right now, and this part used delimiters at all.
    let mut inside = false;
    let mut delimited = false;
    let mut characters = asked.chars().peekable();

    while let Some(character) = characters.next() {
        match character {
            // The delimiter doubled inside a delimited part is that character
            // itself, which is how this server escapes it.
            DELIMITER if inside => {
                if characters.peek() == Some(&DELIMITER) {
                    characters.next();
                    current.push(DELIMITER);
                } else {
                    inside = false;
                }
            }
            // A delimiter may only open a part, never join one already begun.
            DELIMITER if current.is_empty() && !delimited => {
                inside = true;
                delimited = true;
            }
            DELIMITER => return None,
            '.' if !inside => {
                if current.is_empty() {
                    return None;
                }
                found.push(std::mem::take(&mut current));
                delimited = false;
            }
            // Ordinary text after a part closed its delimiter is malformed.
            _ if delimited && !inside => return None,
            other => current.push(other),
        }
    }

    if inside || current.is_empty() {
        return None;
    }
    found.push(current);
    (found.len() <= MOST_PARTS).then_some(found)
}

/// Finds the database the caller means, whatever case it was written in.
///
/// # Errors
///
/// Returns an absence failure carrying the closest names when no database of
/// that name is visible, so a caller is never told only that nothing was found.
pub async fn resolve_database(connection: &mut Conn, asked: &str) -> Result<Resolved> {
    ident::quote(asked)?;
    let found: Option<String> = connection
        .exec_first(
            "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA \
             WHERE LOWER(SCHEMA_NAME) = LOWER(?) ORDER BY SCHEMA_NAME LIMIT 1",
            (asked,),
        )
        .await
        .or_failure()?;

    if let Some(actual) = found {
        return Ok(Resolved {
            asked: asked.to_owned(),
            actual,
        });
    }

    let candidates: Vec<String> = connection
        .query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA ORDER BY SCHEMA_NAME")
        .await
        .or_failure()?;
    Err(missing("database", asked, &candidates))
}

/// Finds the table the caller means, whatever case it was written in.
///
/// # Errors
///
/// Returns an absence failure carrying the closest names when no table of that
/// name is visible in the database.
pub async fn resolve_table(connection: &mut Conn, database: &str, asked: &str) -> Result<Resolved> {
    ident::quote(database)?;
    ident::quote(asked)?;
    let found: Option<String> = connection
        .exec_first(
            "SELECT TABLE_NAME FROM information_schema.TABLES \
             WHERE TABLE_SCHEMA = ? AND LOWER(TABLE_NAME) = LOWER(?) \
             ORDER BY TABLE_NAME LIMIT 1",
            (database, asked),
        )
        .await
        .or_failure()?;

    if let Some(actual) = found {
        return Ok(Resolved {
            asked: asked.to_owned(),
            actual,
        });
    }

    let candidates: Vec<String> = connection
        .exec(
            "SELECT TABLE_NAME FROM information_schema.TABLES \
             WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME",
            (database,),
        )
        .await
        .or_failure()?;
    Err(missing("table", asked, &candidates))
}

/// The failure for a name nothing answers to, carrying the nearest names.
fn missing(kind: &str, asked: &str, candidates: &[String]) -> Failure {
    let near = nearest(asked, candidates, near_name_count());
    let failure = Failure::absence("schema.unknown_object", format!("`{asked}`"))
        .with_detail("detail", format!("`{asked}`"))
        .with_detail("kind", kind.to_owned());
    if near.is_empty() {
        return failure
            .with_detail("reason", "alone")
            .with_hint("no object of a similar name is visible either");
    }
    let names = near.join(", ");
    failure
        .with_detail("reason", "near")
        .with_hint(format!("the closest visible names are: {names}"))
        .with_detail("names", names)
}

/// How many near names a failure carries when nobody has said otherwise.
///
/// Enough to be useful and few enough that the failure stays readable. It is
/// the built-in behind `output.near_name_count` rather than the last word.
const NEAR_NAME_COUNT: usize = 5;

/// The count in force for this invocation, once configuration has been read.
///
/// Zero means nothing has been settled and [`NEAR_NAME_COUNT`] stands. Settled
/// once and read from here for the reason the packet ceiling and the admission
/// ceiling are: this number is wanted while a failure is being built, deep
/// enough that no configuration is in hand, and a hint is not worth putting a
/// settings argument on every signature between here and there.
static IN_FORCE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// Puts the configured count in force for the rest of the invocation.
pub fn declare_near_name_count(count: usize) {
    IN_FORCE.store(count, std::sync::atomic::Ordering::Relaxed);
}

/// The count in force, which is the built-in until one has been settled.
#[must_use]
pub fn near_name_count() -> usize {
    match IN_FORCE.load(std::sync::atomic::Ordering::Relaxed) {
        0 => NEAR_NAME_COUNT,
        settled => settled,
    }
}

/// The names closest to the one asked for, nearest first.
///
/// Closeness is measured on the lowered name, because a name that differs only
/// by case is the single most likely thing the caller meant.
#[must_use]
pub fn nearest(asked: &str, candidates: &[String], count: usize) -> Vec<String> {
    let wanted = asked.to_lowercase();
    let mut scored: Vec<(usize, &String)> = candidates
        .iter()
        .map(|candidate| (distance(&wanted, &candidate.to_lowercase()), candidate))
        .collect();
    scored.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(right.1)));
    scored
        .into_iter()
        .take(count)
        .map(|(_, candidate)| candidate.clone())
        .collect()
}

/// How many single-character edits separate two names.
fn distance(left: &str, right: &str) -> usize {
    let right_chars: Vec<char> = right.chars().collect();
    let mut previous: Vec<usize> = (0..=right_chars.len()).collect();
    let mut current = vec![0_usize; right_chars.len() + 1];

    for (row, left_char) in left.chars().enumerate() {
        current[0] = row + 1;
        for (column, right_char) in right_chars.iter().enumerate() {
            let substitution = previous[column] + usize::from(left_char != *right_char);
            current[column + 1] = substitution
                .min(previous[column + 1] + 1)
                .min(current[column] + 1);
        }
        std::mem::swap(&mut previous, &mut current);
    }
    previous[right_chars.len()]
}

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

    #[test]
    fn the_case_rule_comes_from_the_server_setting() {
        assert_eq!(NameCase::from_setting(0), NameCase::Sensitive);
        assert_eq!(NameCase::from_setting(1), NameCase::InsensitiveStoredLower);
        assert_eq!(
            NameCase::from_setting(2),
            NameCase::InsensitiveStoredAsWritten
        );
        assert_eq!(NameCase::from_setting(9), NameCase::Unknown);
    }

    /// Reaching an object under another case is worth declaring, because the
    /// same call would find nothing on a server that tells case apart.
    #[test]
    fn a_name_reached_under_another_case_is_declared() {
        let reached = Resolved {
            asked: "PEDIDOS".to_owned(),
            actual: "pedidos".to_owned(),
        };
        assert!(reached.differs_only_by_case());

        let exact = Resolved {
            asked: "pedidos".to_owned(),
            actual: "pedidos".to_owned(),
        };
        assert!(!exact.differs_only_by_case());
    }

    /// A miss suggests the names actually visible, nearest first.
    #[test]
    fn a_miss_suggests_the_nearest_visible_names() {
        let visible = vec![
            "pedidos".to_owned(),
            "pedido_item".to_owned(),
            "clientes".to_owned(),
        ];
        let near = nearest("pedido", &visible, 2);
        assert_eq!(near, vec!["pedidos".to_owned(), "pedido_item".to_owned()]);

        let failure = missing("table", "pedido", &visible);
        assert_eq!(failure.category(), crate::error::Category::Absence);
        assert!(failure.hint().is_some_and(|hint| hint.contains("pedidos")));
    }

    /// With nothing visible at all, the failure says so rather than offering
    /// an empty list of suggestions.
    #[test]
    fn a_miss_with_nothing_visible_says_so() {
        let failure = missing("database", "shop", &[]);
        assert!(failure.hint().is_some_and(|hint| hint.contains("similar")));
    }

    /// The name `schema map` writes is the name the readings take.
    ///
    /// This is the whole point of the split: the map qualifies every object,
    /// and a caller chaining the map into a reading hands that qualified name
    /// straight back.
    #[test]
    fn the_qualified_name_a_map_writes_comes_apart_again() {
        let split = split("shop.events_by_year");
        assert_eq!(split.database.as_deref(), Some("shop"));
        assert_eq!(split.name, "events_by_year");
    }

    /// A bare name is untouched, so nothing that worked before changes.
    #[test]
    fn a_bare_name_is_left_exactly_as_it_was_written() {
        for name in ["orders", "ORDERS", "pedido_item", "t1"] {
            let split = split(name);
            assert_eq!(split.database, None, "input {name}");
            assert_eq!(split.name, name, "input {name}");
        }
    }

    /// The database a name carries wins over the one in force, and the one in
    /// force serves when the name carried none.
    #[test]
    fn the_database_the_name_carries_wins_over_the_one_in_force() {
        let carried = split("shop.orders");
        assert_eq!(
            carried.database_or(Some("other".to_owned())).as_deref(),
            Some("shop")
        );

        let bare = split("orders");
        assert_eq!(
            bare.database_or(Some("other".to_owned())).as_deref(),
            Some("other")
        );
        assert_eq!(bare.database_or(None), None);
    }

    /// Winning silently would leave a caller assuming the database they named,
    /// so the disagreement is something the answer can declare.
    #[test]
    fn a_name_that_overrides_the_database_in_force_says_so() {
        assert!(split("shop.orders").overrides(Some("other")));
        // The same database written in another case is not a disagreement.
        assert!(!split("shop.orders").overrides(Some("SHOP")));
        assert!(!split("shop.orders").overrides(None));
        assert!(!split("orders").overrides(Some("shop")));
    }

    /// A name that really carries a dot keeps it, written in the delimiter
    /// this server uses for exactly that.
    #[test]
    fn a_name_written_in_the_delimiter_stays_one_name() {
        let literal = split("`a.b`");
        assert_eq!(literal.database, None);
        assert_eq!(literal.name, "a.b");

        // The delimiter doubled inside a delimited name is that character.
        let escaped = split("`a``b`");
        assert_eq!(escaped.database, None);
        assert_eq!(escaped.name, "a`b");
    }

    /// The fully written-out form a caller may paste from the server itself
    /// comes apart the same way the plain one does.
    #[test]
    fn a_fully_delimited_path_comes_apart_into_its_two_parts() {
        let split = split("`shop`.`orders`");
        assert_eq!(split.database.as_deref(), Some("shop"));
        assert_eq!(split.name, "orders");
    }

    /// Text that is not a path is handed on whole rather than refused here,
    /// so the caller meets the ordinary absence failure and its near names
    /// instead of a second kind of refusal.
    #[test]
    fn text_that_is_not_a_path_is_handed_on_whole() {
        for name in [
            // No level above the database exists on this server.
            "a.b.c", // An empty part on either side.
            ".orders", "shop.",
            // A delimiter that never closes, and one that joins a bare part.
            "`orders", "a`b",
            // Ordinary text sitting outside the delimiters it opened with.
            "`a`b", "",
        ] {
            let split = split(name);
            assert_eq!(split.database, None, "input {name:?}");
            assert_eq!(split.name, name, "input {name:?}");
        }
    }
}