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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! Everything that can be refused before a connection is opened.
//!
//! A statement the analysis would refuse must never cost a connection. Opening
//! one first would spend a round trip on work that was doomed, and would report
//! a network failure for what is really a refused statement — sending the
//! caller after the wrong problem.

use crate::cli::query::QueryCommand;
use crate::cli::{Cli, Command};
use crate::commands::query::Context;
use crate::error::Result;
use crate::sql::ParseLimits;

/// Refuses whatever this invocation can already be refused for.
///
/// Runs after the settings are known and before the destination is reached, so
/// the answer to a bad statement is a validation failure rather than whatever
/// the network happens to say.
///
/// # Errors
///
/// Returns a validation failure when the statement carries more than one
/// command, reads or writes a server file, or cannot be classified; and a
/// usage failure when no statement was given at all.
pub fn refuse_early(cli: &Cli, config: &crate::config::Config, context: &Context) -> Result<()> {
    // The statement is judged first, and deliberately. A malformed statement is
    // malformed wherever it was going to be sent, so reporting it as a missing
    // destination would send the caller after the wrong problem — which is the
    // very thing this module exists to prevent.
    refuse_an_unsound_statement(cli, config, context)?;
    refuse_a_named_query_that_cannot_run(cli, context)?;
    refuse_an_unwritten_target(cli, config)
}

/// Refuses a kept statement that could not run whatever the server said.
///
/// # Why this is here and not where the statement runs
///
/// `exec::named` says of its own checks that "every check here happens before a
/// connection is opened, so a missing value or a wrong kind costs nothing but
/// the check itself". That was not so. The checks live in `named_run`, which
/// takes an open connection, so all three of them — a name that was never kept,
/// a value left out, a value of the wrong kind — were reached only after the
/// destination had been dialled. Measured against a destination nothing answers
/// at: all three came back `network.unreachable`, which names the wrong problem
/// and charges for it.
///
/// Everything needed is local. The catalogue is a file in the settings
/// directory, and matching values against declarations is arithmetic over what
/// the file holds. The work is done again in `named_run`, and doing it twice
/// costs one read of a small local file — less than the connection it saves.
///
/// # Errors
///
/// Returns the failure the kept statement already earns: a name that is not
/// kept, or values that do not match what it declares.
fn refuse_a_named_query_that_cannot_run(cli: &Cli, context: &Context) -> Result<()> {
    let Command::Query(QueryCommand::Named(args)) = &cli.command else {
        return Ok(());
    };
    let crate::cli::query::NamedAction::Run { name, args: given } = &args.action else {
        return Ok(());
    };

    let catalogue = crate::exec::named::Catalogue::open(&context.config_dir)?;
    let stored = catalogue.get(name)?;
    crate::exec::named::arguments(stored, given).map(|_| ())
}

/// Refuses whatever the statement's own text already condemns.
///
/// # Errors
///
/// Returns a validation failure when the statement carries more than one
/// command, reads or writes a server file, or cannot be classified; and a
/// usage failure when no statement was given at all.
fn refuse_an_unsound_statement(
    cli: &Cli,
    config: &crate::config::Config,
    context: &Context,
) -> Result<()> {
    let Command::Query(command) = &cli.command else {
        return Ok(());
    };

    // Only the forms that carry statement text can be analysed here. The rest
    // name an object or an identifier, which only the server can resolve.
    let statement = match command {
        QueryCommand::Run(args) => &args.statement,
        QueryCommand::Explain(args) => &args.statement,
        QueryCommand::Analyze(args) | QueryCommand::Lineage(args) => args,
        _ => return Ok(()),
    };

    // A statement read from the standard input is left alone: consuming the
    // stream here would leave nothing for the work that follows.
    if statement.statement.is_none() {
        return Ok(());
    }

    let text = crate::commands::query::statement_text(
        statement,
        crate::settings::no_input(&cli.globals),
        context.policy.max_input_bytes,
    )?;
    let gated = crate::exec::gate(&text, &statement.params, &context.policy)?;

    // FR-071 names `--read-only` and `sql.read_only` as things it is realised
    // by, and the field on the policy says the refusal happens "before the
    // connection is opened". It did not: the guard lived in `exec::change`,
    // whose function already takes an open connection, so a refused change
    // still paid for one. Measured against an unreachable destination, the
    // answer was `network.unreachable` and not `safety.read_only`.
    //
    // The classification is decided here from the statement's own text and
    // needs no server, so the refusal belongs here too. The guard downstream
    // stays where it is: it also covers the paths that arrive with text this
    // one never saw, such as a statement read from the standard input.
    if !gated.classification().is_read() {
        context.policy.admit_read_only(gated.kind())?;
        refuse_a_change_a_profile_forbids(cli, config, context, gated.kind())?;
    }
    Ok(())
}

/// Refuses a change the destination's own stored policy does not carry.
///
/// # Why the policy on the profile needs its own look
///
/// The mark and the stored key are read by `settings::read_only`, and the
/// policy written on a profile is not: it joins them later, in
/// `context::connection`, where the destination is being prepared. That is
/// deliberate for what it does there — a profile that refuses change opens its
/// session inside a read-only block, so the refusal comes from the server and
/// covers statements this product's own classification would not recognise.
///
/// What it cannot do from there is arrive early. FR-087 promises a refusal
/// "before connecting" and asks to be proved with the server switched off;
/// measured against a destination nothing answers at, a change through such a
/// profile came back `network.unreachable`, and against one that merely does
/// not answer it spent the whole timeout first.
///
/// So the refusal is made here as well. The block on the session stays: this
/// catches what can be classified, and that catches the rest.
///
/// # Errors
///
/// Returns a validation failure when the named profile refuses every change.
fn refuse_a_change_a_profile_forbids(
    cli: &Cli,
    config: &crate::config::Config,
    context: &Context,
    what: &str,
) -> Result<()> {
    // A destination written as one text carries its own policy and never a
    // stored one, so there is nothing here to read for it.
    if cli.globals.destination.dsn.is_some() {
        return Ok(());
    }

    let store = crate::conn::store::ProfileStore::open(&context.config_dir)?;
    let stored_default = super::context::stored_default(config)?;
    let Ok(profile) = store.resolve(
        cli.globals.destination.profile.as_deref(),
        stored_default.as_deref(),
    ) else {
        // No destination resolves. Saying so is the job of the layer that
        // opens one, and answering it here would replace a clear failure about
        // the destination with one about a policy nobody could read.
        return Ok(());
    };

    if profile.read_only {
        return Err(crate::error::Failure::validation(
            "safety.read_only",
            format!(
                "the profile `{}` refuses every change, and `{what}` is one",
                profile.name
            ),
        )
        .with_detail("detail", what)
        .with_hint("use a profile that carries changes, or clear the policy with `conn edit`"));
    }
    Ok(())
}

/// Refuses a change whose destination nobody wrote on the call.
///
/// # Why reading is allowed to inherit and changing is not
///
/// A read that lands on the wrong destination answers the wrong question and
/// stops there, and the caller sees a result that does not match what they
/// expected. A change that lands on the wrong destination has already happened
/// by the time anybody reads the answer, and the answer used to say nothing
/// about which server it happened on.
///
/// So the stored default keeps serving reads, which is what FR-001 designed it
/// for, and stops serving anything with an effect unless the call names where
/// the effect goes.
///
/// # Why the whole command and not the statement
///
/// A statement's own classification is known here only when the text is on the
/// call. Read from the standard input it is not, and consuming the stream to
/// look would leave nothing for the work that follows. The families below are
/// therefore judged by what they are for, and `query run` is judged by its
/// statement when the statement is readable and treated as a change when it is
/// not. Failing closed costs a caller one flag; failing open costs them a
/// change on a server they did not name.
///
/// # Errors
///
/// Returns a validation failure when the destination would be inherited and the
/// command can change the server.
fn refuse_an_unwritten_target(cli: &Cli, config: &crate::config::Config) -> Result<()> {
    use crate::output::envelope::TargetSource;

    if cli.globals.destination.source() != TargetSource::Config {
        return Ok(());
    }
    if !crate::settings::boolean(config, "conn.require_explicit_target")? {
        return Ok(());
    }
    // Built here and not sooner. The two guards above leave without judging
    // anything, and reading settings for a judgement nobody asked for would turn
    // an invocation that works today into one that reports a stored value it
    // never needed.
    let limits = ParseLimits::from_server(config)?;
    if !can_change_the_server(cli, limits) {
        return Ok(());
    }

    Err(crate::error::Failure::validation(
        "validation.target_not_written",
        "this command can change the server and no destination was named on the call",
    )
    .with_hint(
        "name the destination with --profile or --dsn, or turn off conn.require_explicit_target",
    ))
}

/// Whether this invocation can leave the server different from how it found it.
///
/// The bounds are handed in rather than taken from the defaults, and the reason
/// is that this reads a statement the execution path is about to read under the
/// bounds the caller configured. Reading it under different ones answers about a
/// statement nobody will run: a text above the configured ceiling parses here,
/// is called a reading, and is then refused by the work itself. The prediction
/// has to be made under the same bounds as the thing predicted.
///
/// They are read through `from_server` rather than rebuilt from the two stored
/// keys, because that function settles which of the two ceilings applies, and
/// settling it a second time here would be the same decision written twice — the
/// shape `gaps.md` records under G-015, where the second copy is never the one
/// that receives the correction.
///
/// # Why no proof runs the binary at this, and what that costs
///
/// The divergence this closes is real and is today unreachable from outside,
/// which is worth writing down rather than leaving for somebody to rediscover
/// as an unprovable claim.
///
/// Below the configured ceiling nothing reaches here at all: `refuse_early`
/// judges soundness first, and that judgement already uses the configured
/// bounds, so an oversized statement leaves as `sql.too_large` before the
/// destination is ever considered. Above it, the case needs a statement larger
/// than the one mebibyte the defaults allow, and a statement arrives either on
/// the standard input — where it is not read here at all — or as one argument,
/// which this system stops at 131072 bytes. Measured, not assumed.
///
/// So the fix is a correction without an observable symptom, and it is made
/// anyway: the two paths judging the same text under different bounds is a
/// disagreement waiting for the day a statement arrives from a third place. The
/// proof below measures the property at this function, where it is reachable.
///
/// The decision NOT to write an end-to-end proof of this crossing, and what
/// stands in its place, is recorded as `G-032` in `gaps.md`. It is recorded
/// there and not only here because a reason kept where the work happened is
/// found only by whoever is already reading this function, and the reader who
/// needs it is the one asking why the crossing has no proof at all.
fn can_change_the_server(cli: &Cli, limits: ParseLimits) -> bool {
    match &cli.command {
        Command::Query(command) => match command {
            QueryCommand::Sample(_)
            | QueryCommand::Explain(_)
            | QueryCommand::Lineage(_)
            | QueryCommand::Plan(_) => false,
            // Measuring a plan for real runs the statement, which is why the
            // manual treats it as a change rather than as a reading.
            QueryCommand::Run(args) => args
                .statement
                .statement
                .as_deref()
                .and_then(|text| crate::sql::classify::classify(text, limits).ok())
                .is_none_or(|kind| !kind.is_read()),
            // Keeping, listing and forgetting a named statement touch the
            // settings location and never the server. Only running one does,
            // and it is the one action here that opens a destination at all.
            QueryCommand::Named(args) => {
                matches!(args.action, crate::cli::query::NamedAction::Run { .. })
            }
            _ => true,
        },
        Command::Data(_) => true,
        Command::Server(command) => matches!(command, crate::cli::server::ServerCommand::Kill(_)),
        _ => false,
    }
}

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

    fn parse(args: &[&str]) -> Cli {
        let command_line: Vec<String> = std::iter::once("mariadb-cli")
            .chain(args.iter().copied())
            .map(ToOwned::to_owned)
            .collect();
        Cli::try_parse_from(command_line).expect("the sample invocation parses")
    }

    fn context() -> Context {
        let scratch = tempfile::tempdir().expect("scratch directory");
        let config = crate::config::Config::load(Some(scratch.path())).expect("loads");
        super::super::context::query_context(
            &config,
            &parse(&["query", "run", "SELECT 1"]),
            tokio_util::sync::CancellationToken::new(),
        )
        .expect("builds")
    }

    /// Settings with nothing stored, so every key answers with its default.
    fn settings() -> crate::config::Config {
        let scratch = tempfile::tempdir().expect("scratch directory");
        crate::config::Config::load(Some(scratch.path())).expect("loads")
    }

    /// The bounds handed in are the ones the judgement is made under.
    ///
    /// This is the whole of the defect that was measured: the judgement was made
    /// under the defaults while the work that follows it is made under what the
    /// caller configured, so the two could disagree about the same text. A
    /// reading longer than the configured ceiling does not parse, and what does
    /// not parse is treated as a change, which is the conservative direction.
    ///
    /// The assertion is a FLIP rather than a value, and that is what gives it
    /// teeth: the day this function goes back to ignoring what it is handed,
    /// both halves answer the same and the flip is gone. A proof that only
    /// checked the tight case would still pass over a function that had stopped
    /// reading its own parameter.
    ///
    /// The caller's own wiring is not measured here, and the reason is written
    /// above the function: building the bounds from settings writes a ceiling
    /// the whole process shares, so a unit test that built them would decide the
    /// result of whichever neighbour happened to be running beside it.
    #[test]
    fn the_bounds_handed_in_decide_the_judgement_and_not_the_defaults() {
        let call = parse(&["query", "run", "SELECT 'a long reading' AS note"]);

        assert!(
            !can_change_the_server(&call, ParseLimits::default()),
            "a reading under generous bounds is a reading"
        );
        assert!(
            can_change_the_server(
                &call,
                ParseLimits::new(8, crate::sql::parse::DEFAULT_PARSER_STACK_BYTES)
            ),
            "the same reading above the configured ceiling does not parse, and \
             what cannot be read is treated as a change"
        );
    }

    /// A change with no destination on the call is refused before connecting.
    ///
    /// FR-144. The same change with the destination written passes the same
    /// gate, so what is refused is the silence and not the statement.
    /// A rule that names several destinations counts as writing one.
    ///
    /// `--all-profiles` conflicts with both ways of naming a single
    /// destination, so the origin used to fall through to the stored default
    /// and this guard refused a call that had been perfectly explicit. The only
    /// way through was turning `conn.require_explicit_target` off, which turns
    /// it off for every other command as well — a guard weakened everywhere to
    /// admit the one call that never needed weakening.
    ///
    /// Nothing is opened by this: a change still meets the confirmation guard,
    /// which is where a change across every stored destination belongs.
    #[test]
    fn a_rule_that_names_several_destinations_is_a_destination_written() {
        let context = context();
        let config = settings();

        refuse_early(
            &parse(&[
                "--all-profiles",
                "query",
                "run",
                "DELETE FROM t WHERE id = 1",
            ]),
            &config,
            &context,
        )
        .expect("the call named which destinations it wanted");
    }

    #[test]
    fn a_change_with_no_destination_written_is_refused() {
        let context = context();
        let config = settings();

        let failure = refuse_early(
            &parse(&["query", "run", "DELETE FROM t WHERE id = 1"]),
            &config,
            &context,
        )
        .expect_err("an unwritten destination must be refused");
        assert_eq!(failure.category(), crate::error::Category::Validation);

        assert!(
            refuse_early(
                &parse(&[
                    "--profile",
                    "producao",
                    "query",
                    "run",
                    "DELETE FROM t WHERE id = 1"
                ]),
                &config,
                &context,
            )
            .is_ok(),
            "the same change passes once the call names where it goes"
        );
    }

    /// A statement that condemns itself is named before the missing destination.
    ///
    /// The order of the three guards in `refuse_early` is not decoration. The
    /// comment above `can_change_the_server` argues that the divergence it
    /// closes has no observable symptom from outside, and the whole argument
    /// rests on soundness being judged first: a statement the text alone already
    /// condemns leaves as its own refusal before the destination is ever
    /// considered. Swap the two calls and that argument becomes false, quietly,
    /// with nothing in this suite turning red.
    ///
    /// The specimen is chosen so that BOTH guards would answer it. Two commands
    /// in one text are refused by the gate, and the same call is a change with
    /// no destination written, so the target guard has every reason to speak.
    /// Only the order decides which of the two the caller is sent after, which
    /// is what makes this an assertion about the order rather than about either
    /// guard on its own. A specimen only the first guard refused would pass over
    /// any order at all, and would therefore guard nothing.
    #[test]
    fn a_statement_that_condemns_itself_is_named_before_the_missing_destination() {
        let context = context();
        let config = settings();

        let failure = refuse_early(
            &parse(&[
                "query",
                "run",
                "DELETE FROM t WHERE id = 1; DELETE FROM u WHERE id = 1",
            ]),
            &config,
            &context,
        )
        .expect_err("two commands carried in one text must be refused");

        assert_eq!(
            failure.code(),
            "sql.multiple_statements",
            "the statement's own refusal must answer first; \
             `validation.target_not_written` here would send the caller after \
             the wrong problem, and would mean the guards had been reordered"
        );
    }

    /// A kept statement nobody kept is named before the missing destination.
    ///
    /// The proof above pins the first guard ahead of the third and leaves the
    /// middle one, `refuse_a_named_query_that_cannot_run`, free to slide to the
    /// end with nothing in this suite turning red. This closes that half, so
    /// the whole sequence is held rather than its two ends.
    ///
    /// The specimen is again one that BOTH guards would answer. A name that was
    /// never kept is refused by the catalogue, and running a kept statement is
    /// a change with no destination written, so the target guard has every
    /// reason to speak. Only the order decides which of the two failures the
    /// caller is handed, which is what makes this an assertion about the order.
    ///
    /// # Why the first two guards are not ordered against each other
    ///
    /// They cannot be, and that was measured rather than assumed.
    /// `refuse_an_unsound_statement` leaves without judging anything for every
    /// command except `run`, `explain`, `analyze` and `lineage`, and this guard
    /// leaves without judging anything for everything except `named run`. The
    /// two families are disjoint, so no invocation exists that both would
    /// answer, and swapping those two calls changes no answer this product can
    /// give. The orderable part is proved; the part that is not is written down
    /// here rather than left behind as an untestable claim.
    #[test]
    fn a_kept_statement_nobody_kept_is_named_before_the_missing_destination() {
        let context = context();
        let config = settings();

        let failure = refuse_early(
            &parse(&["query", "named", "run", "relatorio-do-mes"]),
            &config,
            &context,
        )
        .expect_err("a name that was never kept must be refused");

        assert_eq!(
            failure.code(),
            "absence.unknown_named_statement",
            "the catalogue's own refusal must answer first; \
             `validation.target_not_written` here would send the caller after \
             the wrong problem, and would mean the guards had been reordered"
        );
    }

    /// A read still inherits the stored default, which is what FR-001 designed.
    ///
    /// FR-144. The limit is declared in the requirement itself, so a proof that
    /// only showed the refusal would leave the limit unmeasured.
    #[test]
    fn a_read_still_inherits_the_stored_default() {
        assert!(
            refuse_early(
                &parse(&["query", "run", "SELECT 1"]),
                &settings(),
                &context()
            )
            .is_ok(),
            "reading is allowed to inherit"
        );
        assert!(
            refuse_early(&parse(&["schema", "tables"]), &settings(), &context()).is_ok(),
            "a structure listing changes nothing and may inherit"
        );
    }

    /// A statement still on the stream is treated as a change rather than read.
    ///
    /// FR-144. Failing closed costs the caller one flag. Failing open would
    /// cost them a change on a server they never named.
    #[test]
    fn a_statement_nobody_can_read_yet_is_treated_as_a_change() {
        let failure = refuse_early(
            &parse(&["query", "run", "--stdin"]),
            &settings(),
            &context(),
        )
        .expect_err("an unreadable statement must not inherit its destination");
        assert_eq!(failure.category(), crate::error::Category::Validation);
    }

    /// The three refusals that must never cost a connection.
    #[test]
    fn a_refused_statement_never_reaches_the_network() {
        let context = context();
        for statement in [
            "SELECT 1; SELECT 2;",
            "SELECT LOAD_FILE('/etc/passwd')",
            "SELEC 1",
        ] {
            let failure = refuse_early(&parse(&["query", "run", statement]), &settings(), &context)
                .expect_err("must refuse before connecting");
            assert_eq!(
                failure.category(),
                crate::error::Category::Validation,
                "`{statement}` must be refused by analysis, not by the network",
            );
        }
    }

    #[test]
    fn a_sound_statement_passes_through_untouched() {
        assert!(refuse_early(
            &parse(&["query", "run", "SELECT 1"]),
            &settings(),
            &context()
        )
        .is_ok());
    }

    #[test]
    fn a_command_without_statement_text_is_left_to_the_server() {
        let context = context();
        assert!(refuse_early(&parse(&["schema", "tables"]), &settings(), &context).is_ok());
        assert!(refuse_early(&parse(&["server", "status"]), &settings(), &context).is_ok());
        assert!(
            refuse_early(
                &parse(&["query", "sample", "--table", "t"]),
                &settings(),
                &context
            )
            .is_ok(),
            "naming a table is not statement text"
        );
    }

    /// Consuming the stream here would leave nothing for the work that follows.
    ///
    /// The destination is written on the call so that the target guard has
    /// nothing to say, leaving this proof about the stream and only the stream.
    #[test]
    fn a_statement_still_on_the_input_stream_is_not_consumed() {
        assert!(refuse_early(
            &parse(&["--profile", "producao", "query", "run", "--stdin"]),
            &settings(),
            &context()
        )
        .is_ok());
    }
}