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;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChangeCounts {
pub matched: u64,
pub changed: u64,
pub requested: RowCountMode,
}
impl ChangeCounts {
#[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,
},
}
}
#[must_use]
pub const fn headline(self) -> u64 {
match self.requested {
RowCountMode::Matched => self.matched,
RowCountMode::Changed => self.changed,
}
}
#[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(),
})
}
}
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()
}
pub const DEFAULT_MAX_INPUT_BYTES: usize = 16_777_216;
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone)]
pub struct Policy {
pub parse: ParseLimits,
pub confirmed: bool,
pub dry_run: bool,
pub count_only: bool,
pub read_only: bool,
pub require_where: bool,
pub require_unique_key: bool,
pub max_affected: u64,
pub max_rows: usize,
pub row_count_mode: RowCountMode,
pub delimiter: String,
pub timeout: Duration,
pub max_input_bytes: usize,
}
impl Policy {
#[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,
max_input_bytes: DEFAULT_MAX_INPUT_BYTES,
}
}
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(())
}
pub fn admit_change(&self, what: &str) -> crate::error::Result<()> {
self.admit_read_only(what)?;
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",
));
}
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(())
}
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(())
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ReadOnlyProbe {
#[default]
Once,
Always,
}
impl ReadOnlyProbe {
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")),
}
}
#[must_use]
pub const fn asks_every_time(self) -> bool {
matches!(self, Self::Always)
}
}
#[derive(Debug, Default)]
pub struct WriteState {
known: Option<bool>,
probe: ReadOnlyProbe,
}
impl WriteState {
#[must_use]
pub const fn new(probe: ReadOnlyProbe) -> Self {
Self { known: None, probe }
}
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(())
}
#[must_use]
pub const fn was_checked(&self) -> bool {
self.known.is_some()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ephemeral {
SessionVariable,
TemporaryTable,
OpenBlock,
NamedStatement,
}
impl Ephemeral {
#[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",
}
}
#[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,
}
}
#[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());
}
#[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"
);
}
#[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"
);
}
}
#[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);
}
#[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());
}
#[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");
}
#[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());
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"
);
}
#[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"
);
let mut kept = WriteState::new(ReadOnlyProbe::Once);
assert!(kept.admit(false).is_ok());
assert!(kept.admit(true).is_ok());
}
#[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"
);
}
#[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")
);
}
}
#[test]
fn a_session_adjustment_without_a_variable_is_not_reported() {
assert_eq!(Ephemeral::detect("set", "SET autocommit = 0"), None);
}
#[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);
}
#[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));
}
}