use super::plan::{self, Estimate, Target};
use super::prepare::{self, Gated};
use super::{ChangeCounts, Policy, WriteState};
use crate::conn::OrFailure;
use crate::error::{Failure, Result};
use crate::output::envelope::Gap;
use mysql_async::prelude::Queryable;
use mysql_async::Conn;
use serde_json::{json, Value};
use sqlparser::ast::Statement;
pub fn refuse_without_restriction(gated: &Gated) -> Result<()> {
let Some(statement) = gated.admission().analysis().statements().first() else {
return Ok(());
};
if !matches!(statement, Statement::Delete(_) | Statement::Update(_))
|| plan::restriction_of(statement).is_some()
{
return Ok(());
}
let named =
plan::target_of(statement).map_or_else(|| "the target table".to_owned(), |t| t.table);
Err(Failure::validation(
"safety.no_restriction",
format!("this change would reach every row of `{named}`"),
)
.with_detail("detail", named)
.with_hint("add a restriction, or set sql.require_where to false to allow the whole table"))
}
#[must_use]
pub fn over_ceiling(would_affect: u64, ceiling: u64) -> Failure {
Failure::limit(
"limit.affected_rows",
format!("this change would affect {would_affect} rows and the ceiling is {ceiling}"),
)
.with_detail("detail", format!("{would_affect} > {ceiling}"))
.with_hint("narrow the restriction, or raise --max-affected")
}
pub async fn admit_scale(
conn: &mut Conn,
gated: &Gated,
ceiling: u64,
) -> Result<(Option<u64>, Option<Gap>)> {
let Some(statement) = gated.admission().analysis().statements().first() else {
return Ok((None, None));
};
let predicted = match plan::estimate(statement) {
Estimate::Known(rows) => rows,
Estimate::Unavailable(reason) => return Ok((None, Some(plan::undecidable_gap(reason)))),
Estimate::Derived(count_sql) => {
let values = plan::count_values(&count_sql, gated.values());
prepare::exec_count(conn, &count_sql, prepare::bind(values)).await?
}
};
if predicted > ceiling {
return Err(over_ceiling(predicted, ceiling));
}
Ok((Some(predicted), None))
}
pub async fn has_unique_key(conn: &mut Conn, target: &Target) -> Result<Option<bool>> {
const QUERY: &str = "SELECT COUNT(*) FROM information_schema.table_constraints \
WHERE table_schema = COALESCE(NULLIF(?, ''), DATABASE()) \
AND table_name = ? \
AND constraint_type IN ('PRIMARY KEY', 'UNIQUE')";
let values = vec![
target.database.clone().unwrap_or_default(),
target.table.clone(),
];
match prepare::exec_count(conn, QUERY, prepare::bind(&values)).await {
Ok(count) => Ok(Some(count > 0)),
Err(failure) if failure.category() == crate::error::Category::Server => Ok(None),
Err(other) => Err(other),
}
}
pub fn report_missing_unique_key(target: &Target, policy: &Policy) -> Result<()> {
if policy.require_unique_key {
return Err(Failure::validation(
"safety.no_unique_key",
format!(
"`{}` has no primary or unique key, so this change cannot be repeated safely",
target.table
),
)
.with_detail("detail", target.table.clone())
.with_hint("set sql.require_unique_key to false to proceed with a warning instead"));
}
crate::i18n::report::safety_no_unique_key(&target.table);
Ok(())
}
pub async fn conditions(conn: &mut Conn) -> Vec<String> {
let Ok(result) = conn.query_iter("SHOW WARNINGS").await else {
return Vec::new();
};
let collected: std::result::Result<Vec<(String, u32, String)>, _> =
result.collect_and_drop().await;
collected.map_or_else(
|_| Vec::new(),
|rows| {
rows.into_iter()
.map(|(level, code, text)| format!("{level} {code}: {text}"))
.collect()
},
)
}
#[must_use]
pub fn with_conditions(failure: Failure, conditions: &[String]) -> Failure {
conditions
.iter()
.skip(1)
.fold(failure, |carried, condition| {
carried.with_extra_condition(condition.clone())
})
}
#[derive(Debug, Default)]
pub struct ChangeOutcome {
pub counts: Option<ChangeCounts>,
pub predicted: Option<u64>,
pub last_insert_id: Option<u64>,
pub conditions: Vec<String>,
pub gaps: Vec<Gap>,
pub simulated: bool,
}
impl ChangeOutcome {
#[must_use]
pub fn as_value(&self) -> Value {
let mut data = json!({ "simulated": self.simulated });
if let Some(counts) = self.counts {
data["rows"] = counts.as_value();
}
if let Some(predicted) = self.predicted {
data["predicted_rows"] = json!(predicted);
}
if let Some(identifier) = self.last_insert_id {
data["generated_id"] = json!(identifier);
}
if !self.conditions.is_empty() {
data["conditions"] = json!(self.conditions);
}
data
}
}
pub async fn apply(
gated: &Gated,
conn: &mut Conn,
policy: &Policy,
write_state: &mut WriteState,
server_read_only: bool,
) -> Result<ChangeOutcome> {
policy.admit_change(gated.kind())?;
write_state.admit(server_read_only)?;
if policy.require_where {
refuse_without_restriction(gated)?;
}
let mut gaps = Vec::new();
if let Some(target) = gated
.admission()
.analysis()
.statements()
.first()
.and_then(plan::target_of)
{
match has_unique_key(conn, &target).await? {
Some(false) => report_missing_unique_key(&target, policy)?,
Some(true) => {}
None => gaps.push(Gap::new(
"unique_key_check",
"unreadable",
"whether the target table can name a row again could not be established",
)),
}
}
let (predicted, gap) = admit_scale(conn, gated, policy.max_affected).await?;
gaps.extend(gap);
if policy.dry_run {
return Ok(ChangeOutcome {
predicted,
gaps,
simulated: true,
..ChangeOutcome::default()
});
}
let mut outcome = send(conn, gated, policy).await?;
outcome.predicted = predicted;
outcome.gaps.extend(gaps);
Ok(outcome)
}
#[must_use]
pub fn describe(gated: &Gated, outcome: &ChangeOutcome) -> Value {
let mut data = outcome.as_value();
if let Some(state) = super::Ephemeral::detect(gated.kind(), gated.admission().stripped().text())
{
data["ephemeral"] = json!({"state": state.as_str(), "notice": state.notice()});
crate::i18n::report::ephemeral_state(state.as_str());
}
data
}
pub fn note_session_is_ephemeral(data: &mut Value) {
let Some(map) = data.as_object_mut() else {
return;
};
if map.contains_key("ephemeral") {
return;
}
map.insert(
"ephemeral".to_owned(),
json!({
"state": "session",
"notice": "this invocation holds its own session, and every piece of \
state in it dies when the process ends",
}),
);
}
pub async fn send(conn: &mut Conn, gated: &Gated, policy: &Policy) -> Result<ChangeOutcome> {
crate::i18n::report::statement_sending(
gated.sql(),
gated.values().len(),
gated.classification().as_str(),
);
let outcome = conn.exec_iter(gated.sql(), gated.params()).await;
let result = match outcome {
Ok(result) => result,
Err(error) => {
let failure = crate::conn::map_driver_error(&error);
let reported = conditions(conn).await;
return Err(with_conditions(failure, &reported));
}
};
result.drop_result().await.or_failure()?;
let counts = ChangeCounts::read(conn.affected_rows(), &conn.info(), policy.row_count_mode);
let last_insert_id = conn.last_insert_id();
Ok(ChangeOutcome {
counts: Some(counts),
last_insert_id,
conditions: conditions(conn).await,
..ChangeOutcome::default()
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::globals::RowCountMode;
use crate::exec::prepare;
use crate::sql::ParseLimits;
use std::time::Duration;
fn policy() -> Policy {
let mut policy = Policy::new(
ParseLimits::default(),
100,
50,
RowCountMode::Changed,
";".to_owned(),
Duration::from_secs(30),
);
policy.read_only = false;
policy.confirmed = true;
policy
}
fn gated(sql: &str) -> Gated {
prepare::gate(sql, &[], &policy()).expect("admitted")
}
#[test]
fn a_change_reaching_every_row_is_refused_and_the_table_is_named() {
for sql in ["DELETE FROM pedidos", "UPDATE pedidos SET pago = 1"] {
let failure = refuse_without_restriction(&gated(sql)).expect_err("must refuse");
assert_eq!(failure.code(), "safety.no_restriction", "input {sql:?}");
assert!(failure.message().contains("pedidos"), "input {sql:?}");
assert_eq!(failure.exit_number().code(), 3);
}
for sql in [
"DELETE FROM pedidos WHERE id = 7",
"INSERT INTO t (a) VALUES (1)",
"DELETE /* note */ FROM t WHERE a = 1",
] {
assert!(
refuse_without_restriction(&gated(sql)).is_ok(),
"input {sql:?}"
);
}
}
#[test]
fn a_change_over_the_ceiling_is_a_limit_failure_naming_both_numbers() {
let failure = over_ceiling(5000, 100);
assert_eq!(failure.code(), "limit.affected_rows");
assert_eq!(failure.exit_number().code(), 10);
assert!(failure.message().contains("5000") && failure.message().contains("100"));
}
#[test]
fn a_table_without_a_unique_key_warns_by_default_and_refuses_only_on_request() {
let target = Target {
database: None,
table: "eventos".to_owned(),
};
assert!(
report_missing_unique_key(&target, &policy()).is_ok(),
"the default warns, so a legitimate change is not blocked"
);
let mut strict = policy();
strict.require_unique_key = true;
let failure =
report_missing_unique_key(&target, &strict).expect_err("the stricter rule refuses");
assert_eq!(failure.code(), "safety.no_unique_key");
assert!(failure.message().contains("eventos"));
}
#[test]
fn every_condition_the_server_reported_reaches_the_caller() {
let reported = vec![
"Warning 1264: out of range for column `a`".to_owned(),
"Warning 1264: out of range for column `b`".to_owned(),
"Warning 1265: data truncated for column `c`".to_owned(),
];
let failure = with_conditions(
Failure::server("server.condition", reported[0].clone()),
&reported,
);
assert_eq!(failure.extra_conditions().len(), 2);
assert!(failure.extra_conditions()[1].contains("1265"));
let only = vec!["Warning 1264: out of range".to_owned()];
let single = with_conditions(Failure::server("server.condition", "x"), &only);
assert!(single.extra_conditions().is_empty());
}
#[test]
fn the_blanket_notice_yields_to_the_one_the_statement_earned() {
let mut plain = json!({"simulated": false});
note_session_is_ephemeral(&mut plain);
assert_eq!(plain["ephemeral"]["state"], "session");
assert!(plain["ephemeral"]["notice"]
.as_str()
.is_some_and(|notice| notice.contains("process ends")));
let mut earned = json!({"ephemeral": {"state": "temporary_table"}});
note_session_is_ephemeral(&mut earned);
assert_eq!(earned["ephemeral"]["state"], "temporary_table");
let mut not_an_object = json!([1, 2]);
note_session_is_ephemeral(&mut not_an_object);
assert_eq!(not_an_object, json!([1, 2]));
}
#[test]
fn a_simulation_reports_its_prediction_and_a_change_reports_its_measurement() {
let simulated = ChangeOutcome {
simulated: true,
predicted: Some(12),
..ChangeOutcome::default()
}
.as_value();
assert_eq!(simulated["simulated"], true);
assert_eq!(simulated["predicted_rows"], 12);
assert!(simulated.get("rows").is_none());
let applied = ChangeOutcome {
counts: Some(ChangeCounts::read(
1,
"Rows matched: 2 Changed: 1 Warnings: 0",
RowCountMode::Changed,
)),
last_insert_id: Some(77),
..ChangeOutcome::default()
}
.as_value();
assert_eq!(applied["rows"]["matched"], 2);
assert_eq!(applied["rows"]["changed"], 1);
assert_eq!(applied["generated_id"], 77);
assert_eq!(applied["simulated"], false);
}
}