Skip to main content

mariadb_cli/exec/
mod.rs

1//! Sending a caller's statement to the server, and everything that guards it.
2//!
3//! # Every statement travels as a prepared statement
4//!
5//! This is not a preference and it is not a performance choice. It is the
6//! structural defence of the whole product, and it is the only one that does
7//! not depend on this tool reading the caller's text correctly.
8//!
9//! The server manual states that the text of a prepared statement must
10//! represent one single statement, never several. So the server itself refuses
11//! a text carrying more than one command, and that refusal holds even if every
12//! textual guard in [`mod@crate::sql`] were wrong.
13//!
14//! Concretely: every round trip here uses the driver's `exec_*` family, which
15//! speaks the binary prepared protocol, and never the `query_*` family, which
16//! speaks the text protocol and would hand the server a text it is free to
17//! split. Replacing an `exec_*` call with a `query_*` call removes the defence
18//! silently, which is why it is written down here.
19//!
20//! # The order of the layers
21//!
22//! For every caller statement, in this order and never another:
23//!
24//! 1. [`crate::sql::guard::admit`] refuses a multiple command and any reach for
25//!    the server's own filesystem, before a single byte is sent.
26//! 2. [`crate::sql::classify()`] decides from the syntax tree whether the
27//!    statement reads, changes, defines or administers. A shape it does not
28//!    recognise is refused and is never treated as a read.
29//! 3. Only then does the prepared statement reach the server.
30//!
31//! # The parts
32//!
33//! - [`prepare`] is the single gateway every statement passes through.
34//! - [`read`] serves a statement that returns rows, without ever persisting.
35//! - [`change`] serves a statement that alters data, with its ceilings.
36//! - [`plan`] serves the plan of a statement, estimated or measured.
37//! - [`script`] serves a file of statements and the atomic block.
38//! - [`routine`] serves a stored routine and its output parameters.
39//! - [`named`] serves a statement stored under a name.
40//! - [`lineage`] resolves result columns to their physical origin, offline.
41
42pub mod change;
43pub mod lineage;
44pub mod named;
45pub mod named_store;
46pub mod plan;
47pub mod prepare;
48pub mod read;
49pub mod routine;
50pub mod script;
51pub mod script_split;
52
53pub use change::ChangeOutcome;
54pub use plan::Estimate;
55pub use prepare::{bind, gate, Gated};
56
57use crate::cli::globals::RowCountMode;
58use crate::error::{Failure, Result};
59use crate::sql::ParseLimits;
60use serde_json::{json, Value};
61use std::time::Duration;
62
63/// The two counts a change produces, and which of them the caller asked for.
64///
65/// They differ, and the difference answers the commonest question a caller has
66/// about a change: writing a row the value it already holds matches one row and
67/// alters none, so a zero here is not a miss. Reporting a single number leaves
68/// the caller unable to tell those two apart, so both always travel.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub struct ChangeCounts {
71    /// Rows the restriction matched.
72    pub matched: u64,
73    /// Rows the server actually altered.
74    pub changed: u64,
75    /// Which of the two the caller asked to be the headline count.
76    pub requested: RowCountMode,
77}
78
79impl ChangeCounts {
80    /// Reads both counts from what the server reported.
81    ///
82    /// The server's own remark carries both numbers for a statement that has
83    /// both. When it does not, the count the server reported is the one the
84    /// session was opened to produce, and the other is reported equal to it
85    /// rather than invented as a different number.
86    #[must_use]
87    pub fn read(affected: u64, info: &str, requested: RowCountMode) -> Self {
88        match (labelled(info, "rows matched:"), labelled(info, "changed:")) {
89            (Some(matched), Some(changed)) => Self {
90                matched,
91                changed,
92                requested,
93            },
94            _ => Self {
95                matched: affected,
96                changed: affected,
97                requested,
98            },
99        }
100    }
101
102    /// The count the caller asked to be the headline one.
103    #[must_use]
104    pub const fn headline(self) -> u64 {
105        match self.requested {
106            RowCountMode::Matched => self.matched,
107            RowCountMode::Changed => self.changed,
108        }
109    }
110
111    /// Both counts, and the mark of which one was asked for.
112    #[must_use]
113    pub fn as_value(self) -> Value {
114        json!({
115            "matched": self.matched,
116            "changed": self.changed,
117            "requested": match self.requested {
118                RowCountMode::Matched => "matched",
119                RowCountMode::Changed => "changed",
120            },
121            "affected": self.headline(),
122        })
123    }
124}
125
126/// Reads one labelled number out of the server's own remark.
127fn labelled(info: &str, label: &str) -> Option<u64> {
128    let lowered = info.to_ascii_lowercase();
129    let start = lowered.find(label)? + label.len();
130    lowered[start..]
131        .split_whitespace()
132        .next()?
133        .parse::<u64>()
134        .ok()
135}
136
137/// What one invocation will read before judging any of it, absent a setting.
138///
139/// The same number the registry publishes as the default of
140/// `limits.max_input_bytes`. The pair is held together by
141/// `every_published_setting_changes_what_the_work_obeys`, which stores two
142/// different values for the key and demands the work differ.
143pub const DEFAULT_MAX_INPUT_BYTES: usize = 16_777_216;
144
145/// Every ceiling and every guard one invocation runs under.
146///
147/// Not one of these values is written into the code that uses it. A ceiling
148/// compiled into a call site cannot be changed by whoever owns the host, so all
149/// of them arrive here from the settings layer or from a flag.
150// Allowed: every switch here is one published setting, resolved once
151// and handed over together. A nested type would be a second name for
152// a grouping the registry does not have, and the registry is the one
153// place a setting is declared.
154#[allow(clippy::struct_excessive_bools)]
155#[derive(Debug, Clone)]
156pub struct Policy {
157    /// The bounds the statement parser runs inside.
158    pub parse: ParseLimits,
159    /// Whether the caller confirmed a destructive operation.
160    pub confirmed: bool,
161    /// Whether the caller asked to see the effect without causing it.
162    pub dry_run: bool,
163    /// Whether the caller asked for a count instead of the rows themselves.
164    ///
165    /// Carried here rather than only in the output layer because a count is a
166    /// question about a READING, and asking it of a change is a contradiction
167    /// the call can be refused for before anything is opened. FR-037 publishes
168    /// that refusal and gives it the usage number.
169    pub count_only: bool,
170    /// Whether every change is refused before the connection is opened.
171    pub read_only: bool,
172    /// Whether a change without a restriction is refused.
173    pub require_where: bool,
174    /// Whether a change against a table with no unique key is refused.
175    ///
176    /// When this is off the absence is reported on the auxiliary channel and
177    /// the change proceeds, because the absence makes a repeat unsafe without
178    /// making this change wrong.
179    pub require_unique_key: bool,
180    /// Ceiling on rows one change may affect.
181    pub max_affected: u64,
182    /// Ceiling on rows one read may return.
183    pub max_rows: usize,
184    /// What a change count means.
185    pub row_count_mode: RowCountMode,
186    /// The separator between statements inside a file.
187    pub delimiter: String,
188    /// Ceiling for one operation.
189    pub timeout: Duration,
190    /// Ceiling on what one invocation will READ before judging any of it.
191    ///
192    /// Distinct from `parse.max_statement_bytes`, which bounds how large a
193    /// single statement may be. This bounds how much reaches memory at all: the
194    /// entry points used to take a whole file or the whole standard input in
195    /// with `read_to_string` and measure statements afterwards, so the cost was
196    /// paid before any ceiling existed to refuse it.
197    pub max_input_bytes: usize,
198}
199
200impl Policy {
201    /// Builds a policy from explicit values.
202    ///
203    /// There is no constructor without arguments on purpose: a policy assembled
204    /// from nothing would carry ceilings this module invented.
205    #[must_use]
206    pub fn new(
207        parse: ParseLimits,
208        max_affected: u64,
209        max_rows: usize,
210        row_count_mode: RowCountMode,
211        delimiter: String,
212        timeout: Duration,
213    ) -> Self {
214        Self {
215            parse,
216            confirmed: false,
217            dry_run: false,
218            count_only: false,
219            read_only: true,
220            require_where: true,
221            require_unique_key: false,
222            max_affected,
223            max_rows,
224            row_count_mode,
225            delimiter,
226            timeout,
227            // Not an argument, for the reason the other four booleans above are
228            // not: the settings layer sets it, and adding a seventh parameter
229            // would make every caller that does not care about it restate it.
230            // The compiled value matches the registry's own default, so a
231            // policy built without the settings layer refuses the same input a
232            // configured one refuses by default.
233            max_input_bytes: DEFAULT_MAX_INPUT_BYTES,
234        }
235    }
236
237    /// Whether this policy refuses changes outright.
238    ///
239    /// # Why this is separate from the rest of admitting a change
240    ///
241    /// It is the one part of the decision that needs nothing but the statement,
242    /// so it is the one part that can be made before a connection is opened —
243    /// which FR-071 requires and the field's own documentation already claimed.
244    /// Confirmation is not like that in practice: the same call that changes
245    /// the server also carries the mark, and refusing early on that would move
246    /// a second guard without being asked to.
247    ///
248    /// # Errors
249    ///
250    /// Returns a validation failure when this invocation refuses every change.
251    pub fn admit_read_only(&self, what: &str) -> crate::error::Result<()> {
252        if self.read_only {
253            return Err(crate::error::Failure::validation(
254                "safety.read_only",
255                format!("this invocation refuses every change, and `{what}` is one"),
256            )
257            .with_detail("detail", what)
258            .with_hint("drop --read-only, or set sql.read_only to false"));
259        }
260        Ok(())
261    }
262
263    /// Whether a change may be attempted at all under this policy.
264    ///
265    /// # Errors
266    ///
267    /// Returns a validation failure when changes are refused outright, or when
268    /// the caller did not confirm a destructive operation.
269    pub fn admit_change(&self, what: &str) -> crate::error::Result<()> {
270        self.admit_read_only(what)?;
271        // Costs nothing and needs nobody, so it comes before the refusal that
272        // does. A count is a question about a READING — how many rows would
273        // come back — and of a change there is no such number.
274        //
275        // This lives in the guard rather than in the one place that applies a
276        // change, which is where it was written first. Three commands ask this
277        // guard for permission and only one of them was reading the flag, so
278        // the other two went on ignoring it in silence and changing the server
279        // for a caller who had asked only to be told a size. FR-037 publishes
280        // the refusal with the usage number.
281        if self.count_only {
282            return Err(crate::error::Failure::usage(
283                "usage.count_of_a_change",
284                format!("`{what}` changes the server, and a count is asked of a reading"),
285            )
286            .with_detail("detail", what)
287            .with_hint(
288                "drop --count-only, or ask the count of the reading that selects the same rows",
289            ));
290        }
291        // A simulation causes nothing, so the confirmation meant for a real
292        // change does not apply to it. The hint below has offered `--dry-run`
293        // as the alternative to `--yes` since it was written, and the guard
294        // never read the field beside `confirmed` that carries the answer, so
295        // the product refused the very remedy it named.
296        if !self.confirmed && !self.dry_run {
297            return Err(crate::error::Failure::validation(
298                "safety.unconfirmed",
299                format!("`{what}` changes the server and was not confirmed"),
300            )
301            .with_detail("detail", what)
302            .with_hint("add --yes to confirm, or --dry-run to see the effect first"));
303        }
304        Ok(())
305    }
306
307    /// Whether a command that cannot simulate may run under a simulation.
308    ///
309    /// # Why this is a second question and not part of the one above
310    ///
311    /// `admit_change` admits a simulation, because the command that APPLIES a
312    /// change honours it and returns before anything is sent. Two others ask
313    /// the same guard and then execute regardless: a stored routine cannot be
314    /// called halfway, and the measured plan is measured BY running the
315    /// statement.
316    ///
317    /// While the confirmation was demanded of every change, those two were held
318    /// back by a mark they never needed. Relaxing it for simulations handed
319    /// them a way through, and `--dry-run` alone began reaching the server —
320    /// measured on `query call`, which answered with the server's own condition
321    /// for a routine that does not exist, which only an attempted call produces.
322    ///
323    /// So the commands that cannot simulate say so. Refusing is the honest
324    /// answer: the alternative is serving a real effect under the name of a
325    /// preview.
326    ///
327    /// # Errors
328    ///
329    /// Returns a validation failure when this invocation is a simulation.
330    pub fn admit_simulation(&self, what: &str) -> crate::error::Result<()> {
331        if self.dry_run {
332            return Err(crate::error::Failure::validation(
333                "safety.cannot_simulate",
334                format!("`{what}` has no simulation, because running it is the only way to learn what it does"),
335            )
336            .with_detail("detail", what)
337            .with_hint(
338                "drop --dry-run; for a statement, `query explain` reads the plan without running it",
339            ));
340        }
341        Ok(())
342    }
343}
344
345/// How often the destination is asked whether it accepts a change.
346///
347/// The answer cannot change while one connection is open, so asking once and
348/// keeping the answer is the honest reading and costs nothing. A caller who
349/// distrusts that, because the destination may be promoted or demoted while a
350/// file of statements is running, asks for it to be consulted before every
351/// change and pays for it.
352///
353/// Neither value keeps anything across invocations. Nothing survives this
354/// process, so there is nothing to carry over even if it were wanted.
355#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
356pub enum ReadOnlyProbe {
357    /// Asked before the first change, and that answer serves the rest.
358    #[default]
359    Once,
360    /// Asked again before every change.
361    Always,
362}
363
364impl ReadOnlyProbe {
365    /// Reads the frequency from the word stored under `server.readonly_probe`.
366    ///
367    /// There is no fallback branch on purpose. The registry is the one place
368    /// the default of that key lives, and a fallback here would be a second
369    /// one, silently winning wherever the two disagreed.
370    ///
371    /// # Errors
372    ///
373    /// Returns a configuration failure when the word is outside the domain the
374    /// registry publishes for that key.
375    pub fn parse(word: &str) -> Result<Self> {
376        match word {
377            "once" => Ok(Self::Once),
378            "always" => Ok(Self::Always),
379            other => Err(Failure::config(
380                "config.unknown_readonly_probe",
381                format!("`{other}` is not a frequency the destination can be asked at"),
382            )
383            .with_detail("detail", other)
384            .with_hint("set server.readonly_probe to once or to always")),
385        }
386    }
387
388    /// Whether the kept answer is discarded before each change.
389    #[must_use]
390    pub const fn asks_every_time(self) -> bool {
391        matches!(self, Self::Always)
392    }
393}
394
395/// Whether the destination refuses changes of its own accord.
396///
397/// The answer is read once per invocation and kept, because it cannot change
398/// while one connection is open. It is never read for a statement that only
399/// reads, since a read-only destination serves a read perfectly well.
400///
401/// A caller who asked for the destination to be consulted before every change
402/// gets exactly that: the kept answer is discarded first, so the next reading
403/// is the destination's and not the memory of it.
404#[derive(Debug, Default)]
405pub struct WriteState {
406    known: Option<bool>,
407    probe: ReadOnlyProbe,
408}
409
410impl WriteState {
411    /// Starts a state that asks the destination as often as the caller wants.
412    #[must_use]
413    pub const fn new(probe: ReadOnlyProbe) -> Self {
414        Self { known: None, probe }
415    }
416
417    /// Records what the destination said about itself and answers from then on.
418    ///
419    /// The refusal names the destination's own mode rather than the permission
420    /// failure the server would eventually produce, because the caller's next
421    /// step is to point somewhere else and not to ask for a right.
422    ///
423    /// # Errors
424    ///
425    /// Returns a validation failure when the destination accepts no change.
426    pub fn admit(&mut self, server_read_only: bool) -> Result<()> {
427        if self.probe.asks_every_time() {
428            self.known = None;
429        }
430        if *self.known.get_or_insert(server_read_only) {
431            return Err(Failure::validation(
432                "safety.server_read_only",
433                "the destination is a read-only server and accepts no change",
434            )
435            .with_hint("point at a destination that accepts writes"));
436        }
437        Ok(())
438    }
439
440    /// Whether the destination has been consulted yet.
441    ///
442    /// Exposed so a test can show the answer is read once and then reused.
443    #[must_use]
444    pub const fn was_checked(&self) -> bool {
445        self.known.is_some()
446    }
447}
448
449/// State an invocation created that dies with the process.
450///
451/// A session variable, a temporary table, an open atomic block and a named
452/// prepared statement all vanish when the connection closes at the end of this
453/// invocation. Whoever comes from a client with a persistent session expects
454/// otherwise, so the product says so rather than letting them assume.
455///
456/// The notice is raised only when the invocation actually created such state.
457/// A plain read creates none, and warning on every read would be noise that
458/// teaches the caller to ignore the notice that matters.
459#[derive(Debug, Clone, Copy, PartialEq, Eq)]
460pub enum Ephemeral {
461    /// A variable that lives on the session.
462    SessionVariable,
463    /// A table that lives on the session.
464    TemporaryTable,
465    /// An atomic block left open.
466    OpenBlock,
467    /// A statement prepared under a name on the session.
468    NamedStatement,
469}
470
471impl Ephemeral {
472    /// The stable identifier emitted with the notice.
473    #[must_use]
474    pub const fn as_str(self) -> &'static str {
475        match self {
476            Self::SessionVariable => "session_variable",
477            Self::TemporaryTable => "temporary_table",
478            Self::OpenBlock => "open_block",
479            Self::NamedStatement => "named_statement",
480        }
481    }
482
483    /// What the invocation created, read from the statement shape.
484    ///
485    /// Returns `None` for a statement that leaves nothing behind, which is what
486    /// keeps the notice off a plain read.
487    #[must_use]
488    pub fn detect(kind: &str, stripped_text: &str) -> Option<Self> {
489        let lowered = stripped_text.to_ascii_lowercase();
490        match kind {
491            "set" if lowered.contains('@') => Some(Self::SessionVariable),
492            "prepare" => Some(Self::NamedStatement),
493            "start_transaction" => Some(Self::OpenBlock),
494            _ if lowered.contains("temporary") => Some(Self::TemporaryTable),
495            _ => None,
496        }
497    }
498
499    /// The notice this state carries to the caller.
500    #[must_use]
501    pub const fn notice(self) -> &'static str {
502        match self {
503            Self::SessionVariable => {
504                "this invocation set a session variable, which dies when the process ends"
505            }
506            Self::TemporaryTable => {
507                "this invocation created a temporary table, which dies when the process ends"
508            }
509            Self::OpenBlock => {
510                "this invocation left an atomic block open, which is discarded when the process ends"
511            }
512            Self::NamedStatement => {
513                "this invocation prepared a named statement, which dies when the process ends"
514            }
515        }
516    }
517}
518
519#[cfg(test)]
520mod tests {
521    use super::*;
522
523    fn policy() -> Policy {
524        Policy::new(
525            ParseLimits::default(),
526            100,
527            50,
528            RowCountMode::Changed,
529            ";".to_owned(),
530            Duration::from_secs(30),
531        )
532    }
533
534    #[test]
535    fn a_change_is_refused_outright_when_this_invocation_reads_only() {
536        let failure = policy().admit_change("delete").expect_err("must refuse");
537        assert_eq!(failure.code(), "safety.read_only");
538        assert_eq!(failure.exit_number().code(), 3);
539    }
540
541    #[test]
542    fn a_change_without_confirmation_is_refused_before_the_server_is_touched() {
543        let mut allowed = policy();
544        allowed.read_only = false;
545        let failure = allowed.admit_change("delete").expect_err("must refuse");
546        assert_eq!(failure.code(), "safety.unconfirmed");
547    }
548
549    #[test]
550    fn a_confirmed_change_is_admitted() {
551        let mut allowed = policy();
552        allowed.read_only = false;
553        allowed.confirmed = true;
554        assert!(allowed.admit_change("delete").is_ok());
555    }
556
557    /// A simulation needs no confirmation, because it causes nothing.
558    ///
559    /// # The contradiction this closes
560    ///
561    /// The refusal above hands the caller two ways forward, `--yes` and
562    /// `--dry-run`, and the guard read only the first. So the product named a
563    /// remedy and then refused it: `--dry-run` alone was answered with
564    /// `safety.unconfirmed`, and the effect could only be seen by also passing
565    /// the confirmation meant for causing it. FR-025 says the flag shows what
566    /// would happen without doing it, which is exactly the case that needs no
567    /// permission to proceed.
568    #[test]
569    fn a_simulation_needs_no_confirmation_because_it_causes_nothing() {
570        let mut simulated = policy();
571        simulated.read_only = false;
572        simulated.dry_run = true;
573        assert!(
574            simulated.admit_change("delete").is_ok(),
575            "a dry run changes nothing, so the guard against changing must not stop it"
576        );
577    }
578
579    /// A count of a change is refused whoever asks, and with the usage number.
580    ///
581    /// # Why the guard and not the caller
582    ///
583    /// This refusal was written first inside the one place that APPLIES a
584    /// change, and three commands ask this guard for permission. The other two
585    /// went on dropping the flag in silence and changing the server for a
586    /// caller who had asked only to be told a size. Asserting it here, of the
587    /// guard itself, is what makes the answer the same for all three.
588    #[test]
589    fn a_count_of_a_change_is_refused_whichever_command_asks() {
590        for what in ["update", "query call", "query analyze"] {
591            let mut counted = policy();
592            counted.read_only = false;
593            counted.confirmed = true;
594            counted.count_only = true;
595            let failure = counted.admit_change(what).expect_err("must refuse");
596            assert_eq!(failure.code(), "usage.count_of_a_change", "for `{what}`");
597            assert_eq!(
598                failure.exit_number().code(),
599                2,
600                "FR-037 publishes the usage number for this combination"
601            );
602        }
603    }
604
605    /// A command with no simulation says so instead of running for real.
606    ///
607    /// # The hole this closes
608    ///
609    /// While every change demanded confirmation, the commands that cannot
610    /// simulate were held back by a mark they never needed. Admitting a
611    /// simulation in `admit_change` handed them a way through, and `--dry-run`
612    /// alone began reaching the server: `query call` answered with the
613    /// destination's own condition for a routine that does not exist, which
614    /// only an attempted call produces.
615    #[test]
616    fn a_command_that_cannot_simulate_refuses_instead_of_running_for_real() {
617        let mut simulated = policy();
618        simulated.read_only = false;
619        simulated.dry_run = true;
620        let failure = simulated
621            .admit_simulation("query call")
622            .expect_err("must refuse");
623        assert_eq!(failure.code(), "safety.cannot_simulate");
624        assert_eq!(failure.exit_number().code(), 3);
625    }
626
627    /// The same question lets an ordinary call through untouched.
628    ///
629    /// Without this the refusal above could be unconditional and nothing would
630    /// notice, which would take two working commands away to close a hole.
631    #[test]
632    fn a_call_that_is_not_a_simulation_is_admitted() {
633        let mut real = policy();
634        real.read_only = false;
635        real.confirmed = true;
636        assert!(real.admit_simulation("query call").is_ok());
637    }
638
639    /// Refusing every change still refuses a simulation of one.
640    ///
641    /// The two guards are ordered, and only the inner one is relaxed above. An
642    /// invocation that refuses changes outright is answering a different
643    /// question — whether this call may touch the server at all — and a
644    /// simulation that slipped past it would report an effect the caller had
645    /// already said it did not want computed.
646    #[test]
647    fn a_read_only_invocation_still_refuses_to_simulate_a_change() {
648        let mut simulated = policy();
649        simulated.dry_run = true;
650        let failure = simulated.admit_change("delete").expect_err("must refuse");
651        assert_eq!(failure.code(), "safety.read_only");
652    }
653
654    /// The destination is consulted once and the answer is kept, because it
655    /// cannot change while one connection is open.
656    #[test]
657    fn a_read_only_destination_is_refused_by_its_own_mode_and_asked_only_once() {
658        let mut state = WriteState::default();
659        assert!(
660            !state.was_checked(),
661            "nothing is asked before the first change"
662        );
663        let failure = state.admit(true).expect_err("must refuse");
664        assert_eq!(failure.code(), "safety.server_read_only");
665        assert_eq!(failure.exit_number().code(), 3, "never a permission number");
666        assert!(state.was_checked());
667
668        // The kept answer decides every later change; the argument is ignored.
669        assert_eq!(
670            state
671                .admit(false)
672                .expect_err("the kept answer decides")
673                .code(),
674            "safety.server_read_only"
675        );
676
677        let mut accepting = WriteState::default();
678        assert!(accepting.admit(false).is_ok());
679        assert!(
680            accepting.admit(true).is_ok(),
681            "the first answer is the one kept, in both directions"
682        );
683    }
684
685    /// Asking every time is the whole point of the second value: a destination
686    /// demoted while a file of statements runs must stop the next statement,
687    /// and the kept answer would let it through.
688    #[test]
689    fn asking_every_time_reads_the_destination_and_never_the_kept_answer() {
690        let mut every_time = WriteState::new(ReadOnlyProbe::Always);
691        assert!(every_time.admit(false).is_ok());
692        assert_eq!(
693            every_time
694                .admit(true)
695                .expect_err("the destination decides again")
696                .code(),
697            "safety.server_read_only"
698        );
699        assert!(
700            every_time.admit(false).is_ok(),
701            "and it decides again in the other direction too"
702        );
703
704        // The same sequence under the kept answer never notices the change.
705        let mut kept = WriteState::new(ReadOnlyProbe::Once);
706        assert!(kept.admit(false).is_ok());
707        assert!(kept.admit(true).is_ok());
708    }
709
710    /// The word stored under the key decides the frequency, and a word outside
711    /// the published domain is refused rather than read as the default.
712    #[test]
713    fn the_frequency_of_the_question_is_read_from_its_own_word() {
714        assert_eq!(
715            ReadOnlyProbe::parse("once").expect("published"),
716            ReadOnlyProbe::Once
717        );
718        assert_eq!(
719            ReadOnlyProbe::parse("always").expect("published"),
720            ReadOnlyProbe::Always
721        );
722        assert!(!ReadOnlyProbe::Once.asks_every_time());
723        assert!(ReadOnlyProbe::Always.asks_every_time());
724        assert_eq!(
725            ReadOnlyProbe::parse("twice")
726                .expect_err("outside the domain")
727                .code(),
728            "config.unknown_readonly_probe"
729        );
730    }
731
732    /// A plain read leaves nothing behind, so warning about it would be noise
733    /// on every single call.
734    #[test]
735    fn a_plain_read_raises_no_ephemeral_notice() {
736        assert_eq!(Ephemeral::detect("select", "SELECT a FROM t"), None);
737        assert_eq!(
738            Ephemeral::detect("insert", "INSERT INTO t VALUES (1)"),
739            None
740        );
741    }
742
743    #[test]
744    fn state_that_dies_with_the_process_is_named() {
745        assert_eq!(
746            Ephemeral::detect("set", "SET @total = 1"),
747            Some(Ephemeral::SessionVariable)
748        );
749        assert_eq!(
750            Ephemeral::detect("create_table", "CREATE TEMPORARY TABLE t (a INT)"),
751            Some(Ephemeral::TemporaryTable)
752        );
753        assert_eq!(
754            Ephemeral::detect("start_transaction", "START TRANSACTION"),
755            Some(Ephemeral::OpenBlock)
756        );
757        assert_eq!(
758            Ephemeral::detect("prepare", "PREPARE s FROM 'SELECT 1'"),
759            Some(Ephemeral::NamedStatement)
760        );
761    }
762
763    #[test]
764    fn every_ephemeral_state_carries_its_own_notice_and_identifier() {
765        for state in [
766            Ephemeral::SessionVariable,
767            Ephemeral::TemporaryTable,
768            Ephemeral::OpenBlock,
769            Ephemeral::NamedStatement,
770        ] {
771            assert!(!state.as_str().is_empty());
772            assert!(
773                state.notice().contains("process ends") || state.notice().contains("discarded")
774            );
775        }
776    }
777
778    /// A session adjustment that touches no variable of the caller's own is not
779    /// state the caller has to be told about.
780    #[test]
781    fn a_session_adjustment_without_a_variable_is_not_reported() {
782        assert_eq!(Ephemeral::detect("set", "SET autocommit = 0"), None);
783    }
784
785    /// The whole reason both counts exist: writing the value a row already
786    /// holds matches that row and alters nothing.
787    #[test]
788    fn a_row_written_the_value_it_already_holds_matches_one_and_alters_none() {
789        let counts = ChangeCounts::read(
790            1,
791            "Rows matched: 1  Changed: 0  Warnings: 0",
792            RowCountMode::Changed,
793        );
794        assert_eq!(counts.matched, 1);
795        assert_eq!(counts.changed, 0);
796        assert_eq!(counts.headline(), 0);
797
798        let asked_for_matched = ChangeCounts::read(
799            1,
800            "Rows matched: 1  Changed: 0  Warnings: 0",
801            RowCountMode::Matched,
802        );
803        assert_eq!(asked_for_matched.headline(), 1);
804    }
805
806    #[test]
807    fn both_counts_and_the_mark_of_which_was_asked_for_reach_the_caller() {
808        let value = ChangeCounts::read(
809            3,
810            "Rows matched: 5  Changed: 3  Warnings: 0",
811            RowCountMode::Changed,
812        )
813        .as_value();
814        assert_eq!(value["matched"], 5);
815        assert_eq!(value["changed"], 3);
816        assert_eq!(value["requested"], "changed");
817        assert_eq!(value["affected"], 3);
818    }
819
820    /// A statement carrying one count only, such as a removal, reports it as
821    /// both rather than inventing a second number.
822    #[test]
823    fn a_statement_with_a_single_count_reports_it_without_inventing_another() {
824        let counts = ChangeCounts::read(4, "", RowCountMode::Changed);
825        assert_eq!((counts.matched, counts.changed), (4, 4));
826    }
827}