pub mod capabilities;
pub mod kill;
pub mod locks;
pub mod processes;
pub mod queries;
pub mod replica;
pub mod status;
pub mod variables;
use crate::conn::OrFailure;
use crate::error::{Category, Failure, Result};
use crate::output::Row;
use crate::types::value;
use indexmap::IndexMap;
use mysql_async::{Conn, Params, Row as DriverRow, Value as Wire};
use serde_json::Value;
use std::time::Duration;
use tokio_util::sync::CancellationToken;
#[derive(Debug, Clone, Copy)]
pub struct ServerSettings {
pub status_interval_secs: u64,
pub default_top: usize,
pub confirmed: bool,
pub observability_visible: bool,
pub kill_foreign_requires_yes: bool,
}
pub async fn fetch(connection: &mut Conn, sql: &str, params: Params) -> Result<Vec<Row>> {
use mysql_async::prelude::Queryable;
let raw: Vec<DriverRow> = connection.exec(sql, params).await.or_failure()?;
raw.iter().map(shape).collect()
}
fn shape(row: &DriverRow) -> Result<Row> {
let columns = row.columns();
let mut shaped = Row::new();
for (index, column) in columns.iter().enumerate() {
let wire = row.as_ref(index).cloned().unwrap_or(Wire::NULL);
shaped.insert(
column.name_str().into_owned(),
value::convert(&wire, column, &crate::types::Conversion::stable())?,
);
}
Ok(shaped)
}
#[must_use]
pub fn cell<'row>(row: &'row Row, name: &str) -> Option<&'row Value> {
row.iter()
.find(|(key, _)| key.eq_ignore_ascii_case(name))
.map(|(_, value)| value)
}
#[must_use]
pub fn first_cell<'row>(row: &'row Row, names: &[&str]) -> Option<&'row Value> {
names.iter().find_map(|name| cell(row, name))
}
#[must_use]
pub fn text_of(value: Option<&Value>) -> String {
match value {
None | Some(Value::Null) => String::new(),
Some(Value::String(text)) => text.clone(),
Some(other) => other.to_string(),
}
}
#[must_use]
pub fn number_of(value: Option<&Value>) -> Option<i64> {
match value {
Some(Value::Number(number)) => number.as_i64(),
Some(Value::String(text)) => text.trim().parse().ok(),
_ => None,
}
}
#[must_use]
pub fn pairs(rows: &[Row]) -> IndexMap<String, String> {
let mut collected = IndexMap::with_capacity(rows.len());
for row in rows {
let mut cells = row.values();
let (name, value) = (cells.next(), cells.next());
if let Some(Value::String(name)) = name {
collected.insert(name.clone(), text_of(value));
}
}
collected
}
#[must_use]
pub fn missing_observation(privilege: &str, subject: &str) -> Failure {
Failure::permission("permission.observation_denied", subject.to_owned())
.with_detail("detail", subject.to_owned())
.with_detail("privilege", privilege.to_owned())
.with_hint(format!(
"grant the {privilege} right to this credential, or use one that already has it"
))
}
#[must_use]
pub fn is_permission(failure: &Failure) -> bool {
failure.category() == Category::Permission
}
#[must_use]
pub fn observation_failure(failure: Failure, privilege: &str, subject: &str) -> Failure {
if is_permission(&failure) {
return missing_observation(privilege, subject);
}
failure
}
#[must_use]
pub fn is_absent_structure(failure: &Failure) -> bool {
failure.category() == Category::Absence || failure.category() == Category::Server
}
pub async fn wait_interval(seconds: u64, token: &CancellationToken) -> Result<()> {
tokio::select! {
() = token.cancelled() => Err(Failure::interrupted(
"interrupted.during_interval",
"the work was stopped while waiting between two readings",
)
.with_hint("run again once the destination is free")),
() = tokio::time::sleep(Duration::from_secs(seconds)) => Ok(()),
}
}
#[must_use]
pub fn matches_pattern(pattern: &str, name: &str) -> bool {
let subject: Vec<char> = name.to_lowercase().chars().collect();
let wanted: Vec<char> = pattern.to_lowercase().chars().collect();
let (mut at, mut want, mut star, mut resume) = (0_usize, 0_usize, None, 0_usize);
while at < subject.len() {
match wanted.get(want) {
Some('%') => {
star = Some(want);
resume = at;
want += 1;
}
Some('_') => {
at += 1;
want += 1;
}
Some(character) if *character == subject[at] => {
at += 1;
want += 1;
}
_ => match star {
Some(position) => {
want = position + 1;
resume += 1;
at = resume;
}
None => return false,
},
}
}
wanted[want..].iter().all(|character| *character == '%')
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn a_pattern_matches_the_way_the_server_would() {
assert!(matches_pattern("max_%", "max_connections"));
assert!(matches_pattern("%connections%", "Max_Connections"));
assert!(matches_pattern(
"innodb_buffer_pool_size",
"innodb_buffer_pool_size"
));
assert!(matches_pattern("max_connection_", "max_connections"));
assert!(!matches_pattern("max_%", "min_connections"));
assert!(!matches_pattern("absent_%", "max_connections"));
}
#[test]
fn a_cell_is_found_whatever_case_the_server_chose() {
let mut row = Row::new();
row.insert("Seconds_Behind_Master".to_owned(), json!(2));
assert_eq!(number_of(cell(&row, "seconds_behind_master")), Some(2));
assert_eq!(
number_of(first_cell(
&row,
&["Seconds_Behind_Source", "Seconds_Behind_Master"]
)),
Some(2)
);
assert!(cell(&row, "absent").is_none());
}
#[test]
fn a_missing_right_names_the_right_that_is_missing() {
let failure = missing_observation("PROCESS", "other-connections");
assert!(is_permission(&failure));
assert_eq!(failure.exit_number().code(), 7);
assert!(failure.hint().is_some_and(|hint| hint.contains("PROCESS")));
}
#[tokio::test]
async fn a_stopped_caller_never_leaves_the_process_asleep() {
let token = CancellationToken::new();
token.cancel();
let failure = wait_interval(3600, &token)
.await
.expect_err("a stopped caller must not wait");
assert_eq!(failure.category(), Category::Interrupted);
}
}