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
//! Reading the structure of a server.
//!
//! Every command on this surface reads metadata and none of them changes
//! anything, so a destination marked read-only answers all of them. The
//! eighteen commands are one operation with different parameters: the
//! parameters live in [`catalog`], the operation in [`query`], and the
//! remaining modules hold the three readings that are not a plain listing.
//!
//! A credential that cannot see an object is not an error here. The objects it
//! can see are returned and the ones it cannot are declared as gaps, so an
//! empty answer caused by a restriction is never mistaken for an empty answer
//! caused by an empty database.

pub mod advice;
pub mod catalog;
pub mod grants;
pub mod kinds;
pub mod map;
pub mod names;
pub mod query;

use kinds::Kind;
use query::{Scope, Statement};

use crate::error::{Category, Failure, Result};
use crate::output::envelope::{Gap, Row};
use crate::sql::ident;
use mysql_async::Conn;
use serde_json::{json, Value};

/// Every ceiling these commands obey.
///
/// Not one of them is decided here. A ceiling depends on how much room the
/// caller has and on how much a scan is worth to it, and this module knows
/// neither.
#[derive(Debug, Clone, Copy)]
pub struct Ceilings {
    /// What the compact map may cost.
    pub map: map::Budget,
    /// Most rows a name search returns for one kind of object.
    pub search_rows: usize,
    /// How many of the largest objects a space report ranks.
    pub ranked_objects: usize,
    /// The estimate above which an exact count is refused before it starts.
    pub countable_rows: u64,
}

/// The kinds of object whose definition the server can write out.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DefinitionKind {
    /// A base table.
    Table,
    /// A view.
    View,
    /// A stored procedure.
    Procedure,
    /// A stored function.
    Function,
    /// A trigger.
    Trigger,
    /// A scheduled event.
    Event,
    /// A number generator.
    Sequence,
}

impl DefinitionKind {
    /// The stable name of this kind, as published and as accepted on input.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Table => "table",
            Self::View => "view",
            Self::Procedure => "procedure",
            Self::Function => "function",
            Self::Trigger => "trigger",
            Self::Event => "event",
            Self::Sequence => "sequence",
        }
    }

    /// The kind that goes by this published name.
    #[must_use]
    pub fn parse(name: &str) -> Option<Self> {
        [
            Self::Table,
            Self::View,
            Self::Procedure,
            Self::Function,
            Self::Trigger,
            Self::Event,
            Self::Sequence,
        ]
        .into_iter()
        .find(|kind| kind.as_str() == name)
    }

    /// The word the server itself uses for this kind.
    const fn keyword(self) -> &'static str {
        match self {
            Self::Table => "TABLE",
            Self::View => "VIEW",
            Self::Procedure => "PROCEDURE",
            Self::Function => "FUNCTION",
            Self::Trigger => "TRIGGER",
            Self::Event => "EVENT",
            Self::Sequence => "SEQUENCE",
        }
    }
}

/// Asks the server to write out the definition of one object.
///
/// The definition comes from the server rather than being assembled here, so
/// what is returned is what that server would accept back.
///
/// # Errors
///
/// Returns a validation failure when a name is not writable, an absence
/// failure when the server writes out nothing, and the mapped driver failure
/// when the definition may not be read.
pub async fn definition(
    connection: &mut Conn,
    kind: DefinitionKind,
    database: &str,
    name: &str,
) -> Result<Value> {
    let target = ident::quote_qualified(&[database, name])?;
    let statement = Statement {
        text: format!("SHOW CREATE {} {target}", kind.keyword()),
        values: Vec::new(),
    };
    let rows = query::run(connection, &statement).await?;

    let written = rows
        .first()
        .and_then(|row| {
            row.iter()
                .find(|(key, _)| key.starts_with("Create") || key.starts_with("SQL Original"))
                .map(|(_, value)| value.clone())
        })
        .ok_or_else(|| {
            Failure::absence(
                "schema.no_definition",
                format!("the server wrote out no definition for `{database}`.`{name}`"),
            )
            .with_detail("detail", format!("{database}.{name}"))
            .with_hint("confirm the object exists and the credential may read its definition")
        })?;

    Ok(json!({
        "kind": kind.as_str(),
        "database": database,
        "name": name,
        "definition": written,
    }))
}

/// Works out what kind of object goes by this name.
///
/// # Errors
///
/// Returns an absence failure carrying the nearest names when nothing in the
/// database answers to the name.
pub async fn kind_of(connection: &mut Conn, database: &str, name: &str) -> Result<DefinitionKind> {
    let scope = Scope::on_table(Some(database.to_owned()), Some(name.to_owned()));
    for (kind, definition) in [
        (Kind::Table, DefinitionKind::Table),
        (Kind::View, DefinitionKind::View),
        (Kind::Sequence, DefinitionKind::Sequence),
        (Kind::Event, DefinitionKind::Event),
    ] {
        let mut narrowed = scope.clone();
        if kind.descriptor().table_column.is_none() {
            narrowed.table = None;
            narrowed.name_pattern = Some(name.to_owned());
        }
        if !query::read(connection, kind.descriptor(), &narrowed)
            .await?
            .is_empty()
        {
            return Ok(definition);
        }
    }

    let by_name = by_name(database, name);
    let routines = query::read(connection, Kind::Routine.descriptor(), &by_name).await?;
    if let Some(kind) = routines.first().and_then(routine_kind) {
        return Ok(kind);
    }

    let triggers = query::read(connection, Kind::Trigger.descriptor(), &by_name).await?;
    if triggers.is_empty() {
        return Err(
            Failure::absence("schema.unknown_object", format!("`{name}`"))
                .with_detail("detail", format!("`{name}`"))
                .with_detail("kind", "object-in-database")
                .with_detail("database", format!("`{database}`"))
                .with_detail("reason", "kind")
                .with_hint("name the kind with --kind, or list the database first"),
        );
    }
    Ok(DefinitionKind::Trigger)
}

/// A reading of one database narrowed to objects going by one name.
///
/// Kinds that belong to no table are found by their own name rather than by an
/// owner, so this is the scope they are looked for under.
fn by_name(database: &str, name: &str) -> Scope {
    Scope {
        database: Some(database.to_owned()),
        name_pattern: Some(name.to_owned()),
        ..Scope::default()
    }
}

/// Which of the two routine kinds a routine row describes.
fn routine_kind(row: &Row) -> Option<DefinitionKind> {
    match row.get("type").and_then(Value::as_str)? {
        "FUNCTION" => Some(DefinitionKind::Function),
        "PROCEDURE" => Some(DefinitionKind::Procedure),
        _ => None,
    }
}

/// Counts the rows of a table for real, having first refused to.
///
/// The cheap estimate is read first, and a table whose estimate is past the
/// ceiling is refused before a single row is read, because the point of the
/// ceiling is to avoid the scan and not to report on it afterwards.
///
/// # Errors
///
/// Returns a validation failure when a name is not writable, a limit failure
/// when the estimate is past the ceiling, and the mapped driver failure when
/// the count cannot be run.
pub async fn exact_count(
    connection: &mut Conn,
    database: &str,
    table: &str,
    ceiling: u64,
) -> Result<Value> {
    let target = ident::quote_qualified(&[database, table])?;
    let estimate = estimated_rows(connection, database, table).await?;
    if estimate > ceiling {
        return Err(Failure::limit(
            "schema.count_too_large",
            format!(
                "`{database}`.`{table}` is estimated at {estimate} rows and the ceiling is {ceiling}"
            ),
        )
        .with_detail("detail", format!("{estimate} > {ceiling}"))
        .with_hint("raise the ceiling deliberately, or use `schema stats` for the estimate"));
    }

    let started = std::time::Instant::now();
    let rows = query::run(
        connection,
        &Statement {
            text: format!("SELECT COUNT(*) AS `rows` FROM {target}"),
            values: Vec::new(),
        },
    )
    .await?;
    let elapsed = started.elapsed();

    Ok(json!({
        "database": database,
        "table": table,
        "rows": rows.first().and_then(|row| row.get("rows")).cloned().unwrap_or(Value::Null),
        "exact": true,
        "estimated": false,
        "elapsed_ms": u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX),
    }))
}

/// The catalog's own estimate for one table, or nothing when it keeps none.
async fn estimated_rows(connection: &mut Conn, database: &str, table: &str) -> Result<u64> {
    let rows = query::read(
        connection,
        Kind::Statistic.descriptor(),
        &Scope::on_table(Some(database.to_owned()), Some(table.to_owned())),
    )
    .await?;
    Ok(rows
        .first()
        .and_then(|row| row.get("estimated_rows"))
        .and_then(Value::as_u64)
        .unwrap_or_default())
}

/// The gap to declare when the catalog keeps no space figure for a database.
///
/// Summing an absent figure to zero would tell the caller the database is
/// empty, which is a different statement from not knowing how big it is.
#[must_use]
pub fn missing_space(rows: &[Row]) -> Option<Gap> {
    let blind: Vec<&str> = rows
        .iter()
        .filter(|row| row.get("total_bytes").is_none_or(Value::is_null))
        .filter_map(|row| row.get("database").and_then(Value::as_str))
        .collect();
    (!blind.is_empty()).then(|| {
        Gap::new(
            blind.join(", "),
            "no_space_figure",
            "the catalog keeps no space figure for these databases, which is not the same as zero",
        )
    })
}

/// The kinds a search looks through: the ones asked for, else all of them.
///
/// A kind outside the published set is refused rather than quietly ignored,
/// because ignoring it would answer a narrower question than the one asked.
///
/// # Errors
///
/// Returns a usage failure naming the kinds this product does search.
pub fn searched_kinds(asked: &[String]) -> Result<Vec<Kind>> {
    if asked.is_empty() {
        return Ok(kinds::SEARCHABLE.to_vec());
    }
    asked
        .iter()
        .map(|name| {
            Kind::parse(name).ok_or_else(|| {
                let kinds = kinds::SEARCHABLE
                    .iter()
                    .map(|kind| kind.as_str())
                    .collect::<Vec<_>>()
                    .join(", ");
                Failure::usage("schema.unknown_kind", format!("`{name}`"))
                    .with_detail("detail", format!("`{name}`"))
                    .with_detail("reason", "searched")
                    .with_hint(format!("the kinds searched are: {kinds}"))
                    .with_detail("kinds", kinds)
            })
        })
        .collect()
}

/// Looks for an object by a pattern in its name, across several kinds.
///
/// A kind the credential may not read is declared as a gap and the search goes
/// on, so one restricted catalog never costs the caller the whole answer.
///
/// # Errors
///
/// Returns a validation failure when the pattern or the database name is not
/// writable, and the mapped driver failure for anything other than a refusal.
pub async fn search(
    connection: &mut Conn,
    pattern: &str,
    database: Option<&str>,
    kinds: &[Kind],
    ceiling: usize,
    detailed: bool,
) -> Result<(Vec<Row>, Vec<Gap>)> {
    let mut found = Vec::new();
    let mut gaps = Vec::new();

    for kind in kinds {
        let scope = Scope {
            database: database.map(ToOwned::to_owned),
            name_pattern: Some(pattern.to_owned()),
            limit: Some(ceiling),
            detailed,
            ..Scope::default()
        };
        match query::read(connection, kind.descriptor(), &scope).await {
            Ok(rows) => {
                if rows.len() >= ceiling {
                    gaps.push(Gap::new(
                        kind.as_str(),
                        "ceiling",
                        format!("the search stopped at {ceiling} matches of this kind"),
                    ));
                }
                found.extend(rows.into_iter().map(|row| tagged(*kind, row)));
            }
            Err(failure) if failure.category() == Category::Permission => {
                gaps.push(Gap::new(
                    kind.as_str(),
                    "permission",
                    format!(
                        "the credential may not read this catalog: {}",
                        failure.message()
                    ),
                ));
            }
            Err(failure) => return Err(failure),
        }
    }
    Ok((found, gaps))
}

/// The same row, saying which kind of object it describes.
///
/// A search returns objects of several kinds at once, and without the kind the
/// caller cannot tell a view from a table by looking at the row.
fn tagged(kind: Kind, row: Row) -> Row {
    let mut tagged = Row::new();
    tagged.insert("kind".to_owned(), json!(kind.as_str()));
    tagged.extend(row);
    tagged
}

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

    #[test]
    fn a_published_kind_name_resolves_back_to_its_kind() {
        assert_eq!(DefinitionKind::parse("table"), Some(DefinitionKind::Table));
        assert_eq!(
            DefinitionKind::parse("function"),
            Some(DefinitionKind::Function)
        );
        assert_eq!(DefinitionKind::parse("materialised"), None);
    }

    /// The name of an object never reaches the statement unquoted, so a name
    /// carrying a separator cannot turn one statement into two.
    #[test]
    fn a_definition_target_is_always_quoted() {
        let target = ident::quote_qualified(&["shop", "a`; DROP TABLE users; --"]).expect("quotes");
        let text = format!("SHOW CREATE {} {target}", DefinitionKind::Table.keyword());
        assert!(
            text.starts_with("SHOW CREATE TABLE `shop`.`a``; DROP"),
            "{text}"
        );
        assert!(text.ends_with('`'), "the name is closed: {text}");
    }

    /// A name this product would refuse to write never reaches the server.
    #[test]
    fn an_unwritable_name_never_reaches_a_definition_statement() {
        let failure = ident::quote_qualified(&["shop", "bad\nname"]).expect_err("refuses");
        assert_eq!(failure.code(), "ident.control_character");
    }

    /// A row tagged with its kind keeps the kind first, so a caller reading a
    /// mixed list branches before it reads anything else.
    #[test]
    fn a_searched_row_says_what_kind_it_is() {
        let mut row = Row::new();
        row.insert("name".to_owned(), json!("orders"));
        let tagged = tagged(Kind::Table, row);
        assert_eq!(
            tagged.get_index(0).map(|(key, _)| key.as_str()),
            Some("kind")
        );
        assert_eq!(tagged["kind"], json!("table"));
    }

    #[test]
    fn a_routine_row_says_whether_it_returns_a_value() {
        let mut function = Row::new();
        function.insert("type".to_owned(), json!("FUNCTION"));
        assert_eq!(routine_kind(&function), Some(DefinitionKind::Function));

        let mut procedure = Row::new();
        procedure.insert("type".to_owned(), json!("PROCEDURE"));
        assert_eq!(routine_kind(&procedure), Some(DefinitionKind::Procedure));

        assert_eq!(routine_kind(&Row::new()), None);
    }

    /// A search with no kinds named looks through every kind it publishes.
    #[test]
    fn a_search_with_no_kinds_looks_through_them_all() {
        assert_eq!(
            searched_kinds(&[]).expect("all kinds"),
            kinds::SEARCHABLE.to_vec()
        );
    }

    /// A kind outside the published set is refused, rather than answering a
    /// narrower question than the one asked.
    #[test]
    fn a_kind_outside_the_published_set_is_refused() {
        let failure = searched_kinds(&["nonexistent".to_owned()]).expect_err("must refuse");
        assert_eq!(failure.code(), "schema.unknown_kind");
        assert_eq!(failure.exit_number().code(), 2);
    }

    #[test]
    fn a_named_kind_narrows_the_search() {
        assert_eq!(
            searched_kinds(&["table".to_owned(), "view".to_owned()]).expect("named kinds"),
            vec![Kind::Table, Kind::View]
        );
    }

    /// A database the catalog keeps no space figure for is declared, because
    /// summing an absent figure to zero would say the database is empty.
    #[test]
    fn a_database_with_no_space_figure_is_declared() {
        let mut blind = Row::new();
        blind.insert("database".to_owned(), json!("shop"));
        blind.insert("total_bytes".to_owned(), Value::Null);
        let gap = missing_space(&[blind]).expect("declared");
        assert_eq!(gap.cause, "no_space_figure");
        assert_eq!(gap.object, "shop");

        let mut known = Row::new();
        known.insert("database".to_owned(), json!("shop"));
        known.insert("total_bytes".to_owned(), json!(4096));
        assert!(missing_space(&[known]).is_none());
    }
}