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
//! The ten commands that send statements to the server.
//!
//! This module is a thin adapter: it unpacks what the caller wrote, hands the
//! work to [`crate::exec`] and wraps the answer in the published envelope. Every
//! defence lives in that layer, so a command here can neither skip one nor put
//! them in another order.
//!
//! Three of these commands reach no server at all. Resolving where a result
//! column comes from is read from the statement's own syntax tree, and keeping
//! a statement under a name only touches the settings location. They are served
//! by [`execute_offline`], so those calls cost no connection.

use super::{query_change, query_read};
use crate::cli::query::{NamedAction, QueryCommand, RunArgs, StatementArgs};
use crate::conn::Session;
use crate::error::{Failure, Result};
use crate::exec::{change, named, prepare, Policy, WriteState};
use crate::output::{Envelope, Gap};
use mysql_async::Conn;
use std::path::PathBuf;

/// When the caller is told that session state dies with the process.
///
/// The notice earns its place by being rare. Raised on every invocation it
/// becomes a line the caller learns to skip, and then it is missing exactly
/// where it matters, which is the invocation that really did leave something
/// behind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EphemeralNotice {
    /// Only where the statement actually created such state.
    OnCreate,
    /// On every invocation that opens a session.
    Always,
}

impl EphemeralNotice {
    /// Reads the moment from the word stored under `sql.ephemeral_notice`.
    ///
    /// There is no fallback branch on purpose, for the reason given on
    /// [`crate::commands::schema::PolicyScope::parse`].
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the word is outside the domain the
    /// registry publishes for that key.
    pub fn parse(word: &str) -> Result<Self> {
        match word {
            "on_create" => Ok(Self::OnCreate),
            "always" => Ok(Self::Always),
            other => Err(Failure::config(
                "config.unknown_ephemeral_notice",
                format!("`{other}` is not a moment the notice can be raised at"),
            )
            .with_detail("detail", other)
            .with_hint("set sql.ephemeral_notice to on_create or to always")),
        }
    }
}

/// Everything one invocation of this family runs under.
#[derive(Debug)]
pub struct Context {
    /// Every ceiling and every guard, decided by the settings layer.
    pub policy: Policy,
    /// Where a statement kept under a name lives.
    pub config_dir: PathBuf,
    /// What the destination said about accepting a change, and how often it
    /// is asked.
    pub write_state: WriteState,
    /// When the notice about state dying with the process is raised.
    pub ephemeral_notice: EphemeralNotice,
    /// The database this invocation works on, when one was named.
    ///
    /// Read from the one global `--database`, for the reason given on
    /// [`crate::commands::data::DataSettings::database`].
    pub database: Option<String>,
    /// How many rows the resume mark passes over before the answer starts.
    ///
    /// Carried so a read asks the server for enough rows to reach the page the
    /// caller asked for. The mark itself is applied by the output pipeline, in
    /// one place, so a row is never passed over twice.
    pub passed_over: usize,
    /// Whether this invocation refuses to ask a person anything.
    ///
    /// Resolved once, here, because the two reads that would really wait are
    /// reached from three different command families and each would otherwise
    /// have to decide for itself what `--no-input` meant.
    pub refuses_to_ask: bool,
    /// How a value is shaped on its way out.
    ///
    /// Carried with the rest of what this family runs under, because every
    /// command here ends in rows and a row cannot be shaped without it. There
    /// is no default to fall back on, so a path that forgot to carry it fails
    /// to compile rather than quietly ignoring the caller's configuration.
    pub conversion: crate::types::Conversion,
    /// The signal that says this invocation was told to stop.
    ///
    /// Carried here rather than threaded through each call because the reads
    /// this family runs are the longest loops the product has, and a loop that
    /// cannot see the signal carries on writing rows long after the caller
    /// asked it to stop. Every other family already reaches the signal; this
    /// one did not, so a flow of a million rows was deaf to it.
    pub token: tokio_util::sync::CancellationToken,
}

/// Serves the commands that reach no server.
///
/// Answers `None` when the command needs a connection, so one is opened only
/// where one is really needed.
///
/// # Errors
///
/// Returns the failure of the command it served.
#[must_use]
pub fn execute_offline(command: &QueryCommand, context: &Context) -> Option<Result<Envelope>> {
    match command {
        QueryCommand::Lineage(args) => Some(query_read::origins(args, context)),
        QueryCommand::Named(args) if !matches!(args.action, NamedAction::Run { .. }) => {
            Some(catalogue(&args.action, context))
        }
        _ => None,
    }
}

/// Serves one command that reaches the server.
///
/// # Errors
///
/// Returns the failure of the command it served, and a usage failure when a
/// command served without a connection is routed here.
pub async fn execute(
    command: &QueryCommand,
    session: &mut Session,
    context: &mut Context,
) -> Result<Envelope> {
    let server_read_only = session.facts().read_only;
    let conn = session.connection();
    let mut envelope = served(command, conn, context, server_read_only).await?;

    apply_ephemeral_notice(&mut envelope, context.ephemeral_notice);
    Ok(envelope)
}

/// Raises the blanket notice on an answer, when the caller asked for it always.
///
/// Applied to the finished answer rather than inside each command, so a caller
/// who asked to be reminded on every invocation is reminded on all of them and
/// not only on the ones somebody remembered to mark.
pub fn apply_ephemeral_notice(envelope: &mut Envelope, notice: EphemeralNotice) {
    if matches!(notice, EphemeralNotice::Always) {
        change::note_session_is_ephemeral(&mut envelope.data);
    }
}

/// Routes one command to the work that serves it.
async fn served(
    command: &QueryCommand,
    conn: &mut Conn,
    context: &mut Context,
    server_read_only: bool,
) -> Result<Envelope> {
    match command {
        QueryCommand::Run(args) => run(args, conn, context, server_read_only).await,
        QueryCommand::Sample(args) => query_read::sample(args, conn, context).await,
        QueryCommand::Explain(args) => query_read::explain(args, conn, context).await,
        QueryCommand::Analyze(args) => {
            query_change::measure(args, conn, context, server_read_only).await
        }
        QueryCommand::Plan(args) => query_read::running_plan(args, conn, context).await,
        QueryCommand::File(args) => query_change::file(args, conn, context, server_read_only).await,
        QueryCommand::Tx(args) => query_change::block(args, conn, context, server_read_only).await,
        QueryCommand::Call(args) => query_change::call(args, conn, context, server_read_only).await,
        QueryCommand::Named(args) => query_read::named_run(args, conn, context).await,
        QueryCommand::Lineage(_) => Err(offline_only("query lineage")),
    }
}

/// The failure a command served without a connection answers with here.
pub(super) fn offline_only(name: &str) -> Failure {
    Failure::usage(
        "usage.served_without_a_connection",
        format!("`{name}` is served without a connection"),
    )
    .with_detail("detail", name)
    .with_hint("route it through the path that opens no connection")
}

/// Reads the statement a command was given.
///
/// # Errors
///
/// Returns a usage failure when no statement was given at all, and a
/// configuration failure when the standard input could not be read.
pub fn statement_text(
    args: &StatementArgs,
    refuses_to_ask: bool,
    ceiling: usize,
) -> Result<String> {
    if let Some(text) = &args.statement {
        return Ok(text.clone());
    }
    if !args.stdin {
        return Err(
            Failure::usage("usage.no_statement", "no statement was given").with_hint(
                "write the statement, or pass --stdin to read it from the standard input",
            ),
        );
    }
    read_standard_input(refuses_to_ask, ceiling)
}

/// Demands the name of a kept statement the argument layer is allowed to leave
/// out.
///
/// The argument layer accepts the action without a name so that publishing its
/// contract costs nothing, which makes this the place the requirement is really
/// enforced. Nothing can be kept under an empty name, so the empty string is
/// refused here rather than reaching the catalogue.
///
/// # Errors
///
/// Returns a usage failure showing the form that carries the name.
pub(super) fn kept_name(given: &str) -> Result<&str> {
    if given.trim().is_empty() {
        return Err(Failure::usage(
            "query.name_missing",
            "this action needs the name of a kept statement",
        )
        .with_hint(
            "give one as the first word, as in `query named run pedidos`; \
             `query named list` shows the kept names",
        ));
    }
    Ok(given)
}

/// Reads whatever the caller piped in.
///
/// # Errors
///
/// Returns a configuration failure when nothing could be read, and a limit
/// failure when the stream carries more than `ceiling` bytes.
pub(super) fn read_standard_input(refuses_to_ask: bool, ceiling: usize) -> Result<String> {
    // A read that would wait for a person is refused here rather than entered,
    // which is the whole of what `--no-input` promises.
    crate::settings::refuse_a_read_that_would_wait(refuses_to_ask, "the statement")?;

    // Bounded rather than taken whole. A pipe has no size to ask for in advance,
    // so the bound is enforced while reading; the previous form agreed to hold
    // whatever the other end chose to send.
    super::input::standard_input_within(ceiling)
}

/// Builds an envelope out of a payload and the gaps that came with it.
pub(super) fn envelope(command: &'static str, data: serde_json::Value, gaps: Vec<Gap>) -> Envelope {
    gaps.into_iter()
        .fold(Envelope::new(command, data), Envelope::with_gap)
}

/// Runs one statement, taking the path its classification calls for.
async fn run(
    args: &RunArgs,
    conn: &mut Conn,
    context: &mut Context,
    server_read_only: bool,
) -> Result<Envelope> {
    let text = statement_text(
        &args.statement,
        context.refuses_to_ask,
        context.policy.max_input_bytes,
    )?;
    let gated = prepare::gate(&text, &args.statement.params, &context.policy)?;
    prepare::echo(&gated);

    if gated.classification().is_read() {
        let ceiling = context.policy.max_rows;
        return query_read::reading(
            "query run",
            gated,
            conn,
            &context.policy,
            ceiling,
            &context.conversion,
            context.passed_over,
        )
        .await;
    }
    let outcome = change::apply(
        &gated,
        conn,
        &context.policy,
        &mut context.write_state,
        server_read_only,
    )
    .await?;
    // A change the caller confirmed has to outlive the process. Every session
    // opens with automatic confirmation off, so a change left unconfirmed here
    // is undone the moment this one-shot invocation closes its connection, and
    // the caller is handed a row count for work that was thrown away.
    if !outcome.simulated {
        crate::exec::script::confirm_changes(conn).await?;
    }
    let data = change::describe(&gated, &outcome);
    Ok(envelope("query run", data, outcome.gaps))
}

/// Keeps, lists or removes a statement stored under a name.
///
/// The name and the text an action needs are demanded here, because the
/// argument layer lets both be absent so that publishing the contract of the
/// action costs nothing.
fn catalogue(action: &NamedAction, context: &Context) -> Result<Envelope> {
    match action {
        NamedAction::Save {
            name, statement, ..
        } => {
            kept_name(name)?;
            if statement.trim().is_empty() {
                return Err(Failure::usage(
                    "query.statement_missing",
                    "keeping a statement under a name needs the statement itself",
                )
                .with_hint(
                    "give it as the second word, as in \
                     `query named save pedidos 'SELECT * FROM pedidos'`",
                ));
            }
        }
        NamedAction::Remove { name } | NamedAction::Run { name, .. } => {
            kept_name(name)?;
        }
        NamedAction::List => {}
    }

    let data = named::serve(action, &context.config_dir, &context.policy)?;
    Ok(Envelope::new("query named", data))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::globals::RowCountMode;
    use crate::cli::query::{NamedArgs, PlanArgs};
    use crate::sql::ParseLimits;
    use std::time::Duration;

    fn context() -> Context {
        Context {
            // Never cancelled here: what these tests measure is what a command
            // decides, and none of them reaches a loop that could be stopped.
            token: tokio_util::sync::CancellationToken::new(),
            policy: Policy::new(
                ParseLimits::default(),
                100,
                50,
                RowCountMode::Changed,
                ";".to_owned(),
                Duration::from_secs(30),
            ),
            config_dir: std::env::temp_dir(),
            write_state: WriteState::default(),
            ephemeral_notice: EphemeralNotice::OnCreate,
            // Nothing in these tests converts a value, and the type carries no
            // default on purpose, so the shaping that reaches no display
            // setting stands in for one here.
            conversion: crate::types::Conversion::stable(),
            refuses_to_ask: false,
            database: None,
            passed_over: 0,
        }
    }

    /// The word stored under the key decides the moment, and a word outside the
    /// published domain is refused rather than read as the default.
    #[test]
    fn the_moment_of_the_notice_is_read_from_its_own_word() {
        assert_eq!(
            EphemeralNotice::parse("on_create").expect("published"),
            EphemeralNotice::OnCreate
        );
        assert_eq!(
            EphemeralNotice::parse("always").expect("published"),
            EphemeralNotice::Always
        );
        assert_eq!(
            EphemeralNotice::parse("never")
                .expect_err("outside the domain")
                .code(),
            "config.unknown_ephemeral_notice"
        );
    }

    fn statement(text: &str) -> StatementArgs {
        StatementArgs {
            statement: Some(text.to_owned()),
            stdin: false,
            params: Vec::new(),
        }
    }

    /// Resolving where a column comes from is read from the statement's own
    /// tree, so it must cost no connection; everything else must ask for one.
    #[test]
    fn only_the_commands_that_need_no_server_are_served_without_one() {
        let context = context();
        let lineage = QueryCommand::Lineage(statement("SELECT p.a FROM t AS p"));
        let envelope = execute_offline(&lineage, &context)
            .expect("served offline")
            .expect("resolves");
        assert_eq!(envelope.command, "query lineage");
        assert_eq!(envelope.data["rows"][0]["sources"][0]["table"], "t");

        for command in [
            QueryCommand::Run(RunArgs {
                statement: statement("SELECT 1"),
            }),
            QueryCommand::Analyze(statement("SELECT 1")),
            QueryCommand::Plan(PlanArgs { id: Some(1) }),
            QueryCommand::Named(NamedArgs {
                action: NamedAction::Run {
                    name: "pedidos".to_owned(),
                    args: Vec::new(),
                },
            }),
        ] {
            assert!(execute_offline(&command, &context).is_none());
        }
    }

    #[test]
    fn a_command_given_no_statement_is_refused_without_touching_anything() {
        let none = StatementArgs {
            statement: None,
            stdin: false,
            params: Vec::new(),
        };
        let missing = statement_text(&none, false, crate::exec::DEFAULT_MAX_INPUT_BYTES)
            .expect_err("must refuse");
        assert_eq!(missing.code(), "usage.no_statement");
        assert_eq!(missing.exit_number().code(), 2);
    }

    fn save(name: &str, statement: &str) -> NamedAction {
        NamedAction::Save {
            name: name.to_owned(),
            statement: statement.to_owned(),
            params: Vec::new(),
            max_rows: Some(10),
        }
    }
    /// Keeping, listing and removing a statement all happen on disk, and a
    /// statement that would be refused is proved so before it is ever stored,
    /// because whoever runs it by name never sees its text.
    #[test]
    fn the_catalogue_is_served_on_disk_and_never_keeps_a_refused_statement() {
        let directory = tempfile::tempdir().expect("scratch");
        let mut context = context();
        context.config_dir = directory.path().to_owned();

        let saved = catalogue(&save("pedidos", "SELECT * FROM pedidos"), &context).expect("stored");
        assert_eq!(saved.data["stored"], true);
        assert_eq!(
            catalogue(&NamedAction::List, &context).expect("lists").data["rows"][0]["name"],
            "pedidos"
        );

        let refused = catalogue(&save("duas", "SELECT 1; DROP TABLE users"), &context)
            .expect_err("must refuse");
        assert_eq!(refused.code(), "sql.multiple_statements");
        let reopened = named::Catalogue::open(directory.path()).expect("opens");
        assert!(
            reopened.get("duas").is_err(),
            "a refused statement is never left in the catalogue"
        );

        let gone = NamedAction::Remove {
            name: "pedidos".to_owned(),
        };
        assert_eq!(
            catalogue(&gone, &context).expect("removes").data["removed"],
            true
        );
    }

    /// Publishing the contract must cost nothing, so the argument layer accepts
    /// an action with no name. That moves the requirement here, where an action
    /// naming nothing has to be refused with a code and shown the form that
    /// carries a name, rather than reaching the catalogue.
    #[test]
    fn an_action_without_a_name_is_refused_with_a_code() {
        let context = context();
        for action in [
            NamedAction::Remove {
                name: String::new(),
            },
            NamedAction::Run {
                name: String::new(),
                args: Vec::new(),
            },
            save("", "SELECT 1"),
        ] {
            let failure = catalogue(&action, &context).expect_err("must refuse");
            assert_eq!(failure.code(), "query.name_missing");
            assert_eq!(failure.exit_number().code(), 2);
            assert!(failure
                .hint()
                .is_some_and(|hint| hint.contains("query named")));
        }
    }

    /// Keeping a statement under a name needs the statement as much as the
    /// name, and the absence of either is refused before anything is stored.
    #[test]
    fn keeping_a_statement_without_the_statement_is_refused_with_a_code() {
        let context = context();
        let failure = catalogue(&save("pedidos", ""), &context).expect_err("must refuse");

        assert_eq!(failure.code(), "query.statement_missing");
        assert_eq!(failure.exit_number().code(), 2);
        assert!(failure
            .hint()
            .is_some_and(|hint| hint.contains("query named save")));
    }
}