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
//! The readings themselves, one function per command.
//!
//! This module holds no reading logic of its own: it turns a command into a
//! descriptor and a scope and hands both to the one reader in
//! [`crate::introspect::query`].

use super::args::{object_of, pattern_of, table_of, unknown_kind};
use super::{advice_wanted, Target};
use crate::cli::schema::{
    AdvisableTableArgs, DdlArgs, Detail, DetailedTableArgs, MapArgs, ScopeArgs, SearchArgs,
    SizeArgs, TableArgs, TablesArgs, ViewsArgs,
};
use crate::conn::Session;
use crate::error::{Failure, Result};
use crate::introspect::kinds::Kind;
use crate::introspect::names;
use crate::introspect::query::{self, Scope};
use crate::introspect::{advice, map, DefinitionKind};
use crate::output::envelope::Gap;
use crate::output::Envelope;
use serde_json::{json, Value};

/// Finds the database and table the caller means, whatever case they wrote.
///
/// The names the server actually records travel back in the answer, because a
/// caller that reached an object under another case would have found nothing
/// on a server that tells case apart, and has to know that.
///
/// A table may name its own database, which is the form `schema map` writes,
/// and that database wins over the one in force. The disagreement, when there
/// is one, is declared rather than applied quietly.
async fn locate(
    session: &mut Session,
    database: Option<String>,
    table: Option<String>,
) -> Result<(Scope, Vec<Value>)> {
    let mut declared = Vec::new();
    let (database, table) = match table {
        None => (database, None),
        Some(written) => {
            let split = names::split(&written);
            if split.overrides(database.as_deref()) {
                declared.push(json!({
                    "asked": database,
                    "actual": split.database,
                    "kind": "database_from_name",
                }));
            }
            (split.database_or(database), Some(split.name))
        }
    };
    let Some(database) = database else {
        return Ok((Scope::on_table(None, table), declared));
    };

    let found = names::resolve_database(session.connection(), &database).await?;
    if found.differs_only_by_case() {
        declared.push(json!({"asked": found.asked, "actual": found.actual, "kind": "database"}));
    }
    let database = found.actual;

    let Some(table) = table else {
        return Ok((Scope::in_database(Some(database)), declared));
    };
    let found = names::resolve_table(session.connection(), &database, &table).await?;
    if found.differs_only_by_case() {
        declared.push(json!({"asked": found.asked, "actual": found.actual, "kind": "table"}));
    }
    Ok((
        Scope::on_table(Some(database), Some(found.actual)),
        declared,
    ))
}

/// Adds what the answer has to say about names beyond the rows themselves.
async fn annotate(session: &mut Session, data: &mut Value, declared: Vec<Value>) -> Result<()> {
    data["name_case"] = json!(names::name_case(session.connection()).await?.as_str());
    if !declared.is_empty() {
        data["resolved_names"] = json!(declared);
    }
    Ok(())
}

/// One listing: find the objects the caller means and answer with them.
///
/// Fourteen of the nineteen commands are this function under another name, so
/// it is written once. What differs between them is the kind and the scope,
/// and both arrive as arguments.
pub(super) async fn listing(
    name: &'static str,
    kind: Kind,
    session: &mut Session,
    database: Option<String>,
    table: Option<String>,
    detailed: bool,
) -> Result<Envelope> {
    let (scope, declared) = locate(session, database, table).await?;
    let rows = query::read(
        session.connection(),
        kind.descriptor(),
        &scope.detailed(detailed),
    )
    .await?;
    let mut data = json!({ "rows": rows });
    annotate(session, &mut data, declared).await?;
    Ok(Envelope::new(name, data))
}

/// A listing narrowed to one database.
pub(super) async fn in_database(
    name: &'static str,
    kind: Kind,
    args: &ScopeArgs,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    let database = target.database.clone();
    listing(
        name,
        kind,
        session,
        database,
        None,
        Detail::or_default(args.detail, Detail::Summary),
    )
    .await
}

/// A listing narrowed to one table.
pub(super) async fn on_table(
    name: &'static str,
    kind: Kind,
    args: &DetailedTableArgs,
    detailed: bool,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    let table = table_of(args.table.as_ref())?;
    let database = target.database.clone();
    listing(name, kind, session, database, Some(table), detailed).await
}

/// Tables, over one database or over every database the credential sees.
pub(super) async fn tables(
    name: &'static str,
    args: &TablesArgs,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    let database = if args.all_databases {
        None
    } else {
        target.database.clone()
    };
    listing(
        name,
        Kind::Table,
        session,
        database,
        None,
        Detail::or_default(args.detail, Detail::Summary),
    )
    .await
}

/// Links or indexes, with structural advice only when it was asked for.
pub(super) async fn advised(
    name: &'static str,
    kind: Kind,
    args: &AdvisableTableArgs,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    let database = target.database.clone();
    let (scope, declared) = locate(session, database, args.table.clone()).await?;
    let deep = Detail::or_default(args.detail, Detail::Summary);
    let rows = query::read(
        session.connection(),
        kind.descriptor(),
        &scope.clone().detailed(deep),
    )
    .await?;

    let mut data = json!({ "rows": rows });
    if advice_wanted(args, target) {
        let keys = query::read(session.connection(), Kind::ForeignKey.descriptor(), &scope).await?;
        let indexes = query::read(session.connection(), Kind::Index.descriptor(), &scope).await?;
        data["advice"] = advice::for_kind(kind, &keys, &indexes);
    }
    annotate(session, &mut data, declared).await?;
    Ok(Envelope::new(name, data))
}

/// Views, with a cut for the ones that keep a written-down result.
///
/// This server family keeps no such object, so the cut answers with an empty
/// list and says why, rather than answering with the ordinary views under a
/// name that would misdescribe them.
pub(super) async fn views(
    name: &'static str,
    args: &ViewsArgs,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    let (scope, declared) = locate(session, target.database.clone(), None).await?;
    if args.materialized {
        let mut data = json!({ "rows": [] });
        annotate(session, &mut data, declared).await?;
        return Ok(Envelope::new(name, data).with_gap(Gap::new(
            "materialized_view",
            "unsupported",
            "this server family keeps no view with a written-down result",
        )));
    }
    let rows = query::read(
        session.connection(),
        Kind::View.descriptor(),
        &scope.detailed(Detail::or_default(args.detail, Detail::Summary)),
    )
    .await?;
    let mut data = json!({ "rows": rows });
    annotate(session, &mut data, declared).await?;
    Ok(Envelope::new(name, data))
}

/// Scheduled events, together with whether the server would run them at all.
///
/// An event marked as enabled never runs while the server's own scheduler is
/// off, so reporting the events without the scheduler would mislead.
pub(super) async fn events(
    name: &'static str,
    args: &ScopeArgs,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    let mut envelope = in_database(name, Kind::Event, args, session, target).await?;
    let scheduler = query::setting(session.connection(), "SELECT @@event_scheduler").await?;
    envelope.data["scheduler"] = scheduler.unwrap_or(Value::Null);
    Ok(envelope)
}

/// Number generators, when this server keeps them at all.
///
/// The current value of a generator is deliberately not read: reading it moves
/// it on, and a listing must never change the server.
pub(super) async fn sequences(
    name: &'static str,
    args: &ScopeArgs,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    if !session.facts().capabilities.sequences {
        return Ok(
            Envelope::new(name, json!({ "rows": [] })).with_gap(Gap::new(
                "sequence",
                "unsupported",
                "this server release keeps no number generators",
            )),
        );
    }
    let mut envelope = in_database(name, Kind::Sequence, args, session, target).await?;
    envelope.data["current_value_read"] = json!(false);
    Ok(envelope.with_gap(Gap::new(
        "sequence_current_value",
        "would_change_the_server",
        "reading the current value of a generator moves it on, so it is not read",
    )))
}

/// The cheap figures of a table, declared as the estimates they are.
pub(super) async fn stats(
    name: &'static str,
    args: &DetailedTableArgs,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    let deep = Detail::or_default(args.detail, Detail::Full);
    let mut envelope = on_table(name, Kind::Statistic, args, deep, session, target).await?;
    envelope.data["estimated"] = json!(true);
    envelope.data["exact"] = json!(false);
    Ok(envelope)
}

/// An object search by a pattern in its name.
pub(super) async fn find(
    name: &'static str,
    args: &SearchArgs,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    let pattern = pattern_of(args)?;
    if pattern.trim().is_empty() {
        return Err(
            Failure::validation("schema.empty_pattern", "the search pattern is empty")
                .with_hint("give a pattern, using % where any text may stand"),
        );
    }
    let kinds = crate::introspect::searched_kinds(&args.kind)?;
    let database = target.database.clone();
    let (scope, declared) = locate(session, database, None).await?;

    let (rows, gaps) = crate::introspect::search(
        session.connection(),
        &pattern,
        scope.database.as_deref(),
        &kinds,
        target.ceilings.search_rows,
        Detail::or_default(args.detail, Detail::Summary),
    )
    .await?;

    let mut data = json!({ "rows": rows });
    annotate(session, &mut data, declared).await?;
    Ok(gaps
        .into_iter()
        .fold(Envelope::new(name, data), Envelope::with_gap))
}

/// The definition of one object, written out by the server itself.
pub(super) async fn definition(
    name: &'static str,
    args: &DdlArgs,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    let object = object_of(args)?;
    // The object may name its own database, which is the form `schema map`
    // writes, and that database wins over the one in force.
    let split = names::split(&object);
    let object = split.name.clone();
    let database = split.database_or(target.database.clone()).ok_or_else(|| {
        Failure::usage(
            "schema.no_database",
            "no database was named and none is in force",
        )
        .with_hint("name one with --database")
    })?;
    let found = names::resolve_database(session.connection(), &database).await?;

    let kind = match args.kind.as_deref() {
        Some(asked) => DefinitionKind::parse(asked).ok_or_else(|| unknown_kind(asked))?,
        None => crate::introspect::kind_of(session.connection(), &found.actual, &object).await?,
    };
    let written =
        crate::introspect::definition(session.connection(), kind, &found.actual, &object).await?;
    Ok(Envelope::new(name, written))
}

/// The exact number of rows, having first refused to count too much.
pub(super) async fn count(
    name: &'static str,
    args: &TableArgs,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    let table = table_of(args.table.as_ref())?;
    let database = target.database.clone();
    let (scope, declared) = locate(session, database, Some(table)).await?;
    let (Some(database), Some(table)) = (scope.database.clone(), scope.table.clone()) else {
        return Err(Failure::usage(
            "schema.no_database",
            "no database was named and none is in force",
        )
        .with_hint("name one with --database"));
    };

    let mut data = crate::introspect::exact_count(
        session.connection(),
        &database,
        &table,
        target.ceilings.countable_rows,
    )
    .await?;
    annotate(session, &mut data, declared).await?;
    Ok(Envelope::new(name, data))
}

/// Space per database, and the largest objects in order.
pub(super) async fn size(
    name: &'static str,
    args: &SizeArgs,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    let (scope, declared) = locate(session, target.database.clone(), None).await?;
    let ranked = args.top.unwrap_or(target.ceilings.ranked_objects);

    let databases = query::read(
        session.connection(),
        Kind::DatabaseSpace.descriptor(),
        &scope,
    )
    .await?;
    let objects = query::read(
        session.connection(),
        Kind::ObjectSpace.descriptor(),
        &scope.clone().limited(Some(ranked)),
    )
    .await?;

    let mut data = json!({ "rows": databases, "largest_objects": objects, "ranked": ranked });
    annotate(session, &mut data, declared).await?;
    let envelope = Envelope::new(name, data);
    Ok(match crate::introspect::missing_space(&databases) {
        Some(gap) => envelope.with_gap(gap),
        None => envelope,
    })
}

/// The compact map of a database.
pub(super) async fn compact_map(
    name: &'static str,
    args: &MapArgs,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    let (scope, declared) = locate(session, target.database.clone(), None).await?;
    let (mut data, gaps) = map::compact(
        session.connection(),
        scope.database.as_deref(),
        args.with_comments,
        target.ceilings.map,
    )
    .await?;
    annotate(session, &mut data, declared).await?;
    Ok(gaps
        .into_iter()
        .fold(Envelope::new(name, data), Envelope::with_gap))
}