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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
//! Sending a caller's statement to the server, and everything that guards it.
//!
//! # Every statement travels as a prepared statement
//!
//! This is not a preference and it is not a performance choice. It is the
//! structural defence of the whole product, and it is the only one that does
//! not depend on this tool reading the caller's text correctly.
//!
//! The server manual states that the text of a prepared statement must
//! represent one single statement, never several. So the server itself refuses
//! a text carrying more than one command, and that refusal holds even if every
//! textual guard in [`mod@crate::sql`] were wrong.
//!
//! Concretely: every round trip here uses the driver's `exec_*` family, which
//! speaks the binary prepared protocol, and never the `query_*` family, which
//! speaks the text protocol and would hand the server a text it is free to
//! split. Replacing an `exec_*` call with a `query_*` call removes the defence
//! silently, which is why it is written down here.
//!
//! # The order of the layers
//!
//! For every caller statement, in this order and never another:
//!
//! 1. [`crate::sql::guard::admit`] refuses a multiple command and any reach for
//!    the server's own filesystem, before a single byte is sent.
//! 2. [`crate::sql::classify()`] decides from the syntax tree whether the
//!    statement reads, changes, defines or administers. A shape it does not
//!    recognise is refused and is never treated as a read.
//! 3. Only then does the prepared statement reach the server.
//!
//! # The parts
//!
//! - [`prepare`] is the single gateway every statement passes through.
//! - [`read`] serves a statement that returns rows, without ever persisting.
//! - [`change`] serves a statement that alters data, with its ceilings.
//! - [`plan`] serves the plan of a statement, estimated or measured.
//! - [`script`] serves a file of statements and the atomic block.
//! - [`routine`] serves a stored routine and its output parameters.
//! - [`named`] serves a statement stored under a name.
//! - [`lineage`] resolves result columns to their physical origin, offline.

pub mod change;
pub mod lineage;
pub mod named;
pub mod named_store;
pub mod plan;
pub mod prepare;
pub mod read;
pub mod routine;
pub mod script;
pub mod script_split;

pub use change::ChangeOutcome;
pub use plan::Estimate;
pub use prepare::{bind, gate, Gated};

use crate::cli::globals::RowCountMode;
use crate::error::{Failure, Result};
use crate::sql::ParseLimits;
use serde_json::{json, Value};
use std::time::Duration;

/// The two counts a change produces, and which of them the caller asked for.
///
/// They differ, and the difference answers the commonest question a caller has
/// about a change: writing a row the value it already holds matches one row and
/// alters none, so a zero here is not a miss. Reporting a single number leaves
/// the caller unable to tell those two apart, so both always travel.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChangeCounts {
    /// Rows the restriction matched.
    pub matched: u64,
    /// Rows the server actually altered.
    pub changed: u64,
    /// Which of the two the caller asked to be the headline count.
    pub requested: RowCountMode,
}

impl ChangeCounts {
    /// Reads both counts from what the server reported.
    ///
    /// The server's own remark carries both numbers for a statement that has
    /// both. When it does not, the count the server reported is the one the
    /// session was opened to produce, and the other is reported equal to it
    /// rather than invented as a different number.
    #[must_use]
    pub fn read(affected: u64, info: &str, requested: RowCountMode) -> Self {
        match (labelled(info, "rows matched:"), labelled(info, "changed:")) {
            (Some(matched), Some(changed)) => Self {
                matched,
                changed,
                requested,
            },
            _ => Self {
                matched: affected,
                changed: affected,
                requested,
            },
        }
    }

    /// The count the caller asked to be the headline one.
    #[must_use]
    pub const fn headline(self) -> u64 {
        match self.requested {
            RowCountMode::Matched => self.matched,
            RowCountMode::Changed => self.changed,
        }
    }

    /// Both counts, and the mark of which one was asked for.
    #[must_use]
    pub fn as_value(self) -> Value {
        json!({
            "matched": self.matched,
            "changed": self.changed,
            "requested": match self.requested {
                RowCountMode::Matched => "matched",
                RowCountMode::Changed => "changed",
            },
            "affected": self.headline(),
        })
    }
}

/// Reads one labelled number out of the server's own remark.
fn labelled(info: &str, label: &str) -> Option<u64> {
    let lowered = info.to_ascii_lowercase();
    let start = lowered.find(label)? + label.len();
    lowered[start..]
        .split_whitespace()
        .next()?
        .parse::<u64>()
        .ok()
}

/// What one invocation will read before judging any of it, absent a setting.
///
/// The same number the registry publishes as the default of
/// `limits.max_input_bytes`. The pair is held together by
/// `every_published_setting_changes_what_the_work_obeys`, which stores two
/// different values for the key and demands the work differ.
pub const DEFAULT_MAX_INPUT_BYTES: usize = 16_777_216;

/// Every ceiling and every guard one invocation runs under.
///
/// Not one of these values is written into the code that uses it. A ceiling
/// compiled into a call site cannot be changed by whoever owns the host, so all
/// of them arrive here from the settings layer or from a flag.
// Allowed: every switch here is one published setting, resolved once
// and handed over together. A nested type would be a second name for
// a grouping the registry does not have, and the registry is the one
// place a setting is declared.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone)]
pub struct Policy {
    /// The bounds the statement parser runs inside.
    pub parse: ParseLimits,
    /// Whether the caller confirmed a destructive operation.
    pub confirmed: bool,
    /// Whether the caller asked to see the effect without causing it.
    pub dry_run: bool,
    /// Whether the caller asked for a count instead of the rows themselves.
    ///
    /// Carried here rather than only in the output layer because a count is a
    /// question about a READING, and asking it of a change is a contradiction
    /// the call can be refused for before anything is opened. FR-037 publishes
    /// that refusal and gives it the usage number.
    pub count_only: bool,
    /// Whether every change is refused before the connection is opened.
    pub read_only: bool,
    /// Whether a change without a restriction is refused.
    pub require_where: bool,
    /// Whether a change against a table with no unique key is refused.
    ///
    /// When this is off the absence is reported on the auxiliary channel and
    /// the change proceeds, because the absence makes a repeat unsafe without
    /// making this change wrong.
    pub require_unique_key: bool,
    /// Ceiling on rows one change may affect.
    pub max_affected: u64,
    /// Ceiling on rows one read may return.
    pub max_rows: usize,
    /// What a change count means.
    pub row_count_mode: RowCountMode,
    /// The separator between statements inside a file.
    pub delimiter: String,
    /// Ceiling for one operation.
    pub timeout: Duration,
    /// Ceiling on what one invocation will READ before judging any of it.
    ///
    /// Distinct from `parse.max_statement_bytes`, which bounds how large a
    /// single statement may be. This bounds how much reaches memory at all: the
    /// entry points used to take a whole file or the whole standard input in
    /// with `read_to_string` and measure statements afterwards, so the cost was
    /// paid before any ceiling existed to refuse it.
    pub max_input_bytes: usize,
}

impl Policy {
    /// Builds a policy from explicit values.
    ///
    /// There is no constructor without arguments on purpose: a policy assembled
    /// from nothing would carry ceilings this module invented.
    #[must_use]
    pub fn new(
        parse: ParseLimits,
        max_affected: u64,
        max_rows: usize,
        row_count_mode: RowCountMode,
        delimiter: String,
        timeout: Duration,
    ) -> Self {
        Self {
            parse,
            confirmed: false,
            dry_run: false,
            count_only: false,
            read_only: true,
            require_where: true,
            require_unique_key: false,
            max_affected,
            max_rows,
            row_count_mode,
            delimiter,
            timeout,
            // Not an argument, for the reason the other four booleans above are
            // not: the settings layer sets it, and adding a seventh parameter
            // would make every caller that does not care about it restate it.
            // The compiled value matches the registry's own default, so a
            // policy built without the settings layer refuses the same input a
            // configured one refuses by default.
            max_input_bytes: DEFAULT_MAX_INPUT_BYTES,
        }
    }

    /// Whether this policy refuses changes outright.
    ///
    /// # Why this is separate from the rest of admitting a change
    ///
    /// It is the one part of the decision that needs nothing but the statement,
    /// so it is the one part that can be made before a connection is opened —
    /// which FR-071 requires and the field's own documentation already claimed.
    /// Confirmation is not like that in practice: the same call that changes
    /// the server also carries the mark, and refusing early on that would move
    /// a second guard without being asked to.
    ///
    /// # Errors
    ///
    /// Returns a validation failure when this invocation refuses every change.
    pub fn admit_read_only(&self, what: &str) -> crate::error::Result<()> {
        if self.read_only {
            return Err(crate::error::Failure::validation(
                "safety.read_only",
                format!("this invocation refuses every change, and `{what}` is one"),
            )
            .with_detail("detail", what)
            .with_hint("drop --read-only, or set sql.read_only to false"));
        }
        Ok(())
    }

    /// Whether a change may be attempted at all under this policy.
    ///
    /// # Errors
    ///
    /// Returns a validation failure when changes are refused outright, or when
    /// the caller did not confirm a destructive operation.
    pub fn admit_change(&self, what: &str) -> crate::error::Result<()> {
        self.admit_read_only(what)?;
        // Costs nothing and needs nobody, so it comes before the refusal that
        // does. A count is a question about a READING — how many rows would
        // come back — and of a change there is no such number.
        //
        // This lives in the guard rather than in the one place that applies a
        // change, which is where it was written first. Three commands ask this
        // guard for permission and only one of them was reading the flag, so
        // the other two went on ignoring it in silence and changing the server
        // for a caller who had asked only to be told a size. FR-037 publishes
        // the refusal with the usage number.
        if self.count_only {
            return Err(crate::error::Failure::usage(
                "usage.count_of_a_change",
                format!("`{what}` changes the server, and a count is asked of a reading"),
            )
            .with_detail("detail", what)
            .with_hint(
                "drop --count-only, or ask the count of the reading that selects the same rows",
            ));
        }
        // A simulation causes nothing, so the confirmation meant for a real
        // change does not apply to it. The hint below has offered `--dry-run`
        // as the alternative to `--yes` since it was written, and the guard
        // never read the field beside `confirmed` that carries the answer, so
        // the product refused the very remedy it named.
        if !self.confirmed && !self.dry_run {
            return Err(crate::error::Failure::validation(
                "safety.unconfirmed",
                format!("`{what}` changes the server and was not confirmed"),
            )
            .with_detail("detail", what)
            .with_hint("add --yes to confirm, or --dry-run to see the effect first"));
        }
        Ok(())
    }

    /// Whether a command that cannot simulate may run under a simulation.
    ///
    /// # Why this is a second question and not part of the one above
    ///
    /// `admit_change` admits a simulation, because the command that APPLIES a
    /// change honours it and returns before anything is sent. Two others ask
    /// the same guard and then execute regardless: a stored routine cannot be
    /// called halfway, and the measured plan is measured BY running the
    /// statement.
    ///
    /// While the confirmation was demanded of every change, those two were held
    /// back by a mark they never needed. Relaxing it for simulations handed
    /// them a way through, and `--dry-run` alone began reaching the server —
    /// measured on `query call`, which answered with the server's own condition
    /// for a routine that does not exist, which only an attempted call produces.
    ///
    /// So the commands that cannot simulate say so. Refusing is the honest
    /// answer: the alternative is serving a real effect under the name of a
    /// preview.
    ///
    /// # Errors
    ///
    /// Returns a validation failure when this invocation is a simulation.
    pub fn admit_simulation(&self, what: &str) -> crate::error::Result<()> {
        if self.dry_run {
            return Err(crate::error::Failure::validation(
                "safety.cannot_simulate",
                format!("`{what}` has no simulation, because running it is the only way to learn what it does"),
            )
            .with_detail("detail", what)
            .with_hint(
                "drop --dry-run; for a statement, `query explain` reads the plan without running it",
            ));
        }
        Ok(())
    }
}

/// How often the destination is asked whether it accepts a change.
///
/// The answer cannot change while one connection is open, so asking once and
/// keeping the answer is the honest reading and costs nothing. A caller who
/// distrusts that, because the destination may be promoted or demoted while a
/// file of statements is running, asks for it to be consulted before every
/// change and pays for it.
///
/// Neither value keeps anything across invocations. Nothing survives this
/// process, so there is nothing to carry over even if it were wanted.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ReadOnlyProbe {
    /// Asked before the first change, and that answer serves the rest.
    #[default]
    Once,
    /// Asked again before every change.
    Always,
}

impl ReadOnlyProbe {
    /// Reads the frequency from the word stored under `server.readonly_probe`.
    ///
    /// There is no fallback branch on purpose. The registry is the one place
    /// the default of that key lives, and a fallback here would be a second
    /// one, silently winning wherever the two disagreed.
    ///
    /// # 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 {
            "once" => Ok(Self::Once),
            "always" => Ok(Self::Always),
            other => Err(Failure::config(
                "config.unknown_readonly_probe",
                format!("`{other}` is not a frequency the destination can be asked at"),
            )
            .with_detail("detail", other)
            .with_hint("set server.readonly_probe to once or to always")),
        }
    }

    /// Whether the kept answer is discarded before each change.
    #[must_use]
    pub const fn asks_every_time(self) -> bool {
        matches!(self, Self::Always)
    }
}

/// Whether the destination refuses changes of its own accord.
///
/// The answer is read once per invocation and kept, because it cannot change
/// while one connection is open. It is never read for a statement that only
/// reads, since a read-only destination serves a read perfectly well.
///
/// A caller who asked for the destination to be consulted before every change
/// gets exactly that: the kept answer is discarded first, so the next reading
/// is the destination's and not the memory of it.
#[derive(Debug, Default)]
pub struct WriteState {
    known: Option<bool>,
    probe: ReadOnlyProbe,
}

impl WriteState {
    /// Starts a state that asks the destination as often as the caller wants.
    #[must_use]
    pub const fn new(probe: ReadOnlyProbe) -> Self {
        Self { known: None, probe }
    }

    /// Records what the destination said about itself and answers from then on.
    ///
    /// The refusal names the destination's own mode rather than the permission
    /// failure the server would eventually produce, because the caller's next
    /// step is to point somewhere else and not to ask for a right.
    ///
    /// # Errors
    ///
    /// Returns a validation failure when the destination accepts no change.
    pub fn admit(&mut self, server_read_only: bool) -> Result<()> {
        if self.probe.asks_every_time() {
            self.known = None;
        }
        if *self.known.get_or_insert(server_read_only) {
            return Err(Failure::validation(
                "safety.server_read_only",
                "the destination is a read-only server and accepts no change",
            )
            .with_hint("point at a destination that accepts writes"));
        }
        Ok(())
    }

    /// Whether the destination has been consulted yet.
    ///
    /// Exposed so a test can show the answer is read once and then reused.
    #[must_use]
    pub const fn was_checked(&self) -> bool {
        self.known.is_some()
    }
}

/// State an invocation created that dies with the process.
///
/// A session variable, a temporary table, an open atomic block and a named
/// prepared statement all vanish when the connection closes at the end of this
/// invocation. Whoever comes from a client with a persistent session expects
/// otherwise, so the product says so rather than letting them assume.
///
/// The notice is raised only when the invocation actually created such state.
/// A plain read creates none, and warning on every read would be noise that
/// teaches the caller to ignore the notice that matters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ephemeral {
    /// A variable that lives on the session.
    SessionVariable,
    /// A table that lives on the session.
    TemporaryTable,
    /// An atomic block left open.
    OpenBlock,
    /// A statement prepared under a name on the session.
    NamedStatement,
}

impl Ephemeral {
    /// The stable identifier emitted with the notice.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SessionVariable => "session_variable",
            Self::TemporaryTable => "temporary_table",
            Self::OpenBlock => "open_block",
            Self::NamedStatement => "named_statement",
        }
    }

    /// What the invocation created, read from the statement shape.
    ///
    /// Returns `None` for a statement that leaves nothing behind, which is what
    /// keeps the notice off a plain read.
    #[must_use]
    pub fn detect(kind: &str, stripped_text: &str) -> Option<Self> {
        let lowered = stripped_text.to_ascii_lowercase();
        match kind {
            "set" if lowered.contains('@') => Some(Self::SessionVariable),
            "prepare" => Some(Self::NamedStatement),
            "start_transaction" => Some(Self::OpenBlock),
            _ if lowered.contains("temporary") => Some(Self::TemporaryTable),
            _ => None,
        }
    }

    /// The notice this state carries to the caller.
    #[must_use]
    pub const fn notice(self) -> &'static str {
        match self {
            Self::SessionVariable => {
                "this invocation set a session variable, which dies when the process ends"
            }
            Self::TemporaryTable => {
                "this invocation created a temporary table, which dies when the process ends"
            }
            Self::OpenBlock => {
                "this invocation left an atomic block open, which is discarded when the process ends"
            }
            Self::NamedStatement => {
                "this invocation prepared a named statement, which dies when the process ends"
            }
        }
    }
}

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

    fn policy() -> Policy {
        Policy::new(
            ParseLimits::default(),
            100,
            50,
            RowCountMode::Changed,
            ";".to_owned(),
            Duration::from_secs(30),
        )
    }

    #[test]
    fn a_change_is_refused_outright_when_this_invocation_reads_only() {
        let failure = policy().admit_change("delete").expect_err("must refuse");
        assert_eq!(failure.code(), "safety.read_only");
        assert_eq!(failure.exit_number().code(), 3);
    }

    #[test]
    fn a_change_without_confirmation_is_refused_before_the_server_is_touched() {
        let mut allowed = policy();
        allowed.read_only = false;
        let failure = allowed.admit_change("delete").expect_err("must refuse");
        assert_eq!(failure.code(), "safety.unconfirmed");
    }

    #[test]
    fn a_confirmed_change_is_admitted() {
        let mut allowed = policy();
        allowed.read_only = false;
        allowed.confirmed = true;
        assert!(allowed.admit_change("delete").is_ok());
    }

    /// A simulation needs no confirmation, because it causes nothing.
    ///
    /// # The contradiction this closes
    ///
    /// The refusal above hands the caller two ways forward, `--yes` and
    /// `--dry-run`, and the guard read only the first. So the product named a
    /// remedy and then refused it: `--dry-run` alone was answered with
    /// `safety.unconfirmed`, and the effect could only be seen by also passing
    /// the confirmation meant for causing it. FR-025 says the flag shows what
    /// would happen without doing it, which is exactly the case that needs no
    /// permission to proceed.
    #[test]
    fn a_simulation_needs_no_confirmation_because_it_causes_nothing() {
        let mut simulated = policy();
        simulated.read_only = false;
        simulated.dry_run = true;
        assert!(
            simulated.admit_change("delete").is_ok(),
            "a dry run changes nothing, so the guard against changing must not stop it"
        );
    }

    /// A count of a change is refused whoever asks, and with the usage number.
    ///
    /// # Why the guard and not the caller
    ///
    /// This refusal was written first inside the one place that APPLIES a
    /// change, and three commands ask this guard for permission. The other two
    /// went on dropping the flag in silence and changing the server for a
    /// caller who had asked only to be told a size. Asserting it here, of the
    /// guard itself, is what makes the answer the same for all three.
    #[test]
    fn a_count_of_a_change_is_refused_whichever_command_asks() {
        for what in ["update", "query call", "query analyze"] {
            let mut counted = policy();
            counted.read_only = false;
            counted.confirmed = true;
            counted.count_only = true;
            let failure = counted.admit_change(what).expect_err("must refuse");
            assert_eq!(failure.code(), "usage.count_of_a_change", "for `{what}`");
            assert_eq!(
                failure.exit_number().code(),
                2,
                "FR-037 publishes the usage number for this combination"
            );
        }
    }

    /// A command with no simulation says so instead of running for real.
    ///
    /// # The hole this closes
    ///
    /// While every change demanded confirmation, the commands that cannot
    /// simulate were held back by a mark they never needed. Admitting a
    /// simulation in `admit_change` handed them a way through, and `--dry-run`
    /// alone began reaching the server: `query call` answered with the
    /// destination's own condition for a routine that does not exist, which
    /// only an attempted call produces.
    #[test]
    fn a_command_that_cannot_simulate_refuses_instead_of_running_for_real() {
        let mut simulated = policy();
        simulated.read_only = false;
        simulated.dry_run = true;
        let failure = simulated
            .admit_simulation("query call")
            .expect_err("must refuse");
        assert_eq!(failure.code(), "safety.cannot_simulate");
        assert_eq!(failure.exit_number().code(), 3);
    }

    /// The same question lets an ordinary call through untouched.
    ///
    /// Without this the refusal above could be unconditional and nothing would
    /// notice, which would take two working commands away to close a hole.
    #[test]
    fn a_call_that_is_not_a_simulation_is_admitted() {
        let mut real = policy();
        real.read_only = false;
        real.confirmed = true;
        assert!(real.admit_simulation("query call").is_ok());
    }

    /// Refusing every change still refuses a simulation of one.
    ///
    /// The two guards are ordered, and only the inner one is relaxed above. An
    /// invocation that refuses changes outright is answering a different
    /// question — whether this call may touch the server at all — and a
    /// simulation that slipped past it would report an effect the caller had
    /// already said it did not want computed.
    #[test]
    fn a_read_only_invocation_still_refuses_to_simulate_a_change() {
        let mut simulated = policy();
        simulated.dry_run = true;
        let failure = simulated.admit_change("delete").expect_err("must refuse");
        assert_eq!(failure.code(), "safety.read_only");
    }

    /// The destination is consulted once and the answer is kept, because it
    /// cannot change while one connection is open.
    #[test]
    fn a_read_only_destination_is_refused_by_its_own_mode_and_asked_only_once() {
        let mut state = WriteState::default();
        assert!(
            !state.was_checked(),
            "nothing is asked before the first change"
        );
        let failure = state.admit(true).expect_err("must refuse");
        assert_eq!(failure.code(), "safety.server_read_only");
        assert_eq!(failure.exit_number().code(), 3, "never a permission number");
        assert!(state.was_checked());

        // The kept answer decides every later change; the argument is ignored.
        assert_eq!(
            state
                .admit(false)
                .expect_err("the kept answer decides")
                .code(),
            "safety.server_read_only"
        );

        let mut accepting = WriteState::default();
        assert!(accepting.admit(false).is_ok());
        assert!(
            accepting.admit(true).is_ok(),
            "the first answer is the one kept, in both directions"
        );
    }

    /// Asking every time is the whole point of the second value: a destination
    /// demoted while a file of statements runs must stop the next statement,
    /// and the kept answer would let it through.
    #[test]
    fn asking_every_time_reads_the_destination_and_never_the_kept_answer() {
        let mut every_time = WriteState::new(ReadOnlyProbe::Always);
        assert!(every_time.admit(false).is_ok());
        assert_eq!(
            every_time
                .admit(true)
                .expect_err("the destination decides again")
                .code(),
            "safety.server_read_only"
        );
        assert!(
            every_time.admit(false).is_ok(),
            "and it decides again in the other direction too"
        );

        // The same sequence under the kept answer never notices the change.
        let mut kept = WriteState::new(ReadOnlyProbe::Once);
        assert!(kept.admit(false).is_ok());
        assert!(kept.admit(true).is_ok());
    }

    /// The word stored under the key decides the frequency, and a word outside
    /// the published domain is refused rather than read as the default.
    #[test]
    fn the_frequency_of_the_question_is_read_from_its_own_word() {
        assert_eq!(
            ReadOnlyProbe::parse("once").expect("published"),
            ReadOnlyProbe::Once
        );
        assert_eq!(
            ReadOnlyProbe::parse("always").expect("published"),
            ReadOnlyProbe::Always
        );
        assert!(!ReadOnlyProbe::Once.asks_every_time());
        assert!(ReadOnlyProbe::Always.asks_every_time());
        assert_eq!(
            ReadOnlyProbe::parse("twice")
                .expect_err("outside the domain")
                .code(),
            "config.unknown_readonly_probe"
        );
    }

    /// A plain read leaves nothing behind, so warning about it would be noise
    /// on every single call.
    #[test]
    fn a_plain_read_raises_no_ephemeral_notice() {
        assert_eq!(Ephemeral::detect("select", "SELECT a FROM t"), None);
        assert_eq!(
            Ephemeral::detect("insert", "INSERT INTO t VALUES (1)"),
            None
        );
    }

    #[test]
    fn state_that_dies_with_the_process_is_named() {
        assert_eq!(
            Ephemeral::detect("set", "SET @total = 1"),
            Some(Ephemeral::SessionVariable)
        );
        assert_eq!(
            Ephemeral::detect("create_table", "CREATE TEMPORARY TABLE t (a INT)"),
            Some(Ephemeral::TemporaryTable)
        );
        assert_eq!(
            Ephemeral::detect("start_transaction", "START TRANSACTION"),
            Some(Ephemeral::OpenBlock)
        );
        assert_eq!(
            Ephemeral::detect("prepare", "PREPARE s FROM 'SELECT 1'"),
            Some(Ephemeral::NamedStatement)
        );
    }

    #[test]
    fn every_ephemeral_state_carries_its_own_notice_and_identifier() {
        for state in [
            Ephemeral::SessionVariable,
            Ephemeral::TemporaryTable,
            Ephemeral::OpenBlock,
            Ephemeral::NamedStatement,
        ] {
            assert!(!state.as_str().is_empty());
            assert!(
                state.notice().contains("process ends") || state.notice().contains("discarded")
            );
        }
    }

    /// A session adjustment that touches no variable of the caller's own is not
    /// state the caller has to be told about.
    #[test]
    fn a_session_adjustment_without_a_variable_is_not_reported() {
        assert_eq!(Ephemeral::detect("set", "SET autocommit = 0"), None);
    }

    /// The whole reason both counts exist: writing the value a row already
    /// holds matches that row and alters nothing.
    #[test]
    fn a_row_written_the_value_it_already_holds_matches_one_and_alters_none() {
        let counts = ChangeCounts::read(
            1,
            "Rows matched: 1  Changed: 0  Warnings: 0",
            RowCountMode::Changed,
        );
        assert_eq!(counts.matched, 1);
        assert_eq!(counts.changed, 0);
        assert_eq!(counts.headline(), 0);

        let asked_for_matched = ChangeCounts::read(
            1,
            "Rows matched: 1  Changed: 0  Warnings: 0",
            RowCountMode::Matched,
        );
        assert_eq!(asked_for_matched.headline(), 1);
    }

    #[test]
    fn both_counts_and_the_mark_of_which_was_asked_for_reach_the_caller() {
        let value = ChangeCounts::read(
            3,
            "Rows matched: 5  Changed: 3  Warnings: 0",
            RowCountMode::Changed,
        )
        .as_value();
        assert_eq!(value["matched"], 5);
        assert_eq!(value["changed"], 3);
        assert_eq!(value["requested"], "changed");
        assert_eq!(value["affected"], 3);
    }

    /// A statement carrying one count only, such as a removal, reports it as
    /// both rather than inventing a second number.
    #[test]
    fn a_statement_with_a_single_count_reports_it_without_inventing_another() {
        let counts = ChangeCounts::read(4, "", RowCountMode::Changed);
        assert_eq!((counts.matched, counts.changed), (4, 4));
    }
}