mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Server diagnosis: what the server is doing right now.
//!
//! These commands stay on the published surface even when the credential
//! lacks the observation permission. Missing permission is reported as a
//! failure with a hint, so the command tree never differs between
//! destinations.

use clap::{Args, Subcommand, ValueEnum};

/// What a listed connection is doing right now.
///
/// A domain rather than free text, because a word the server never writes
/// would narrow the listing to nothing and read exactly like a quiet server.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum ConnectionState {
    /// Working on a statement.
    Running,
    /// Holding the connection open and doing nothing.
    Sleeping,
}

impl ConnectionState {
    /// The word the server writes in its own command column.
    #[must_use]
    pub const fn command_word(self) -> &'static str {
        match self {
            Self::Running => "Query",
            Self::Sleeping => "Sleep",
        }
    }
}

/// The eight server commands.
#[derive(Debug, Clone, Subcommand)]
pub enum ServerCommand {
    /// Activity counters, with the difference between two readings.
    Status(StatusArgs),
    /// Configuration variables.
    Variables(PatternArgs),
    /// Active connections.
    Processes(ProcessesArgs),
    /// Replica situation.
    Replica,
    /// End the work of another connection.
    Kill(KillArgs),
    /// Server variant and the conditional features available.
    Capabilities,
    /// Costliest statements, grouped by signature.
    Queries(TopArgs),
    /// Locks, waits and open transactions.
    Locks,
}

/// Reading the activity counters.
///
/// A counter only means something as a difference between two readings, so the
/// command takes two by default, separated by a declared interval.
#[derive(Debug, Clone, Args)]
pub struct StatusArgs {
    /// Seconds between the two readings; defaults to the stored key.
    #[arg(long)]
    pub interval: Option<u64>,
    /// Keep only counters whose name matches this pattern.
    #[arg(long)]
    pub pattern: Option<String>,
}

/// A listing narrowed by a name pattern.
#[derive(Debug, Clone, Args)]
pub struct PatternArgs {
    /// Keep only names matching this pattern.
    ///
    /// Published as `--like`, which is the name the manual carries, with
    /// `--pattern` kept as an alias for the form this build served first.
    #[arg(long = "like", alias = "pattern")]
    pub pattern: Option<String>,
}

/// Listing active connections.
#[derive(Debug, Clone, Args)]
pub struct ProcessesArgs {
    /// Keep only connections of this user.
    #[arg(long)]
    pub user: Option<String>,
    /// Keep only connections busy for at least this many seconds.
    #[arg(long)]
    pub min_seconds: Option<u64>,
    /// Keep only connections in this state.
    #[arg(long, value_name = "STATE")]
    pub state: Option<ConnectionState>,
}

/// Ending the work of another connection.
///
/// Ending a connection of another user cannot be undone and takes away work
/// that is not yours, so it needs a mark of its own beyond the usual
/// confirmation.
#[derive(Debug, Clone, Args)]
pub struct KillArgs {
    /// Connection identifier to end.
    ///
    /// The argument layer no longer demands it, so publishing the contract of
    /// this command costs nothing. Zero stands for absence, because no server
    /// hands out a connection under that number, and the refusal is raised
    /// where the connection would actually be ended.
    ///
    /// Published as `--connection`, which is the name the manual carries, with
    /// `--id` kept as an alias for the form this build served first.
    #[arg(long = "connection", alias = "id", default_value_t = 0)]
    pub id: u64,
    /// End only the running statement, keeping the connection open.
    ///
    /// Published as `--query` for the same reason, with `--query-only` kept.
    #[arg(long = "query", alias = "query-only")]
    pub query_only: bool,
    /// Allow ending a connection that belongs to another user.
    #[arg(long)]
    pub kill_other: bool,
}

/// What a ranking of statements is ordered by.
///
/// A closed domain rather than free text, and the reason is the defect this
/// repairs (FR-127): the manual promised a criterion, the command had none, and
/// the global output ordering silently accepted a field the answer never
/// carried. A no-op that ends in success is worse than a refusal, because the
/// caller reads the ranking as though it had been ordered.
///
/// Every name is ONE word, so the spelling on the command line and the spelling
/// in the answer cannot drift apart. The pair that was already wrong here —
/// `total-time` in the manual against `total_time` in the answer — is exactly
/// what two-word names cost, and the product has no third convention to fall
/// back on.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum QueryRanking {
    /// Time the signature accounts for in total.
    Total,
    /// How many times the signature was called.
    Calls,
    /// Time one call of the signature costs on average.
    Average,
    /// Rows the server examined for the signature.
    Rows,
}

impl QueryRanking {
    /// The column of the server's own collection this orders by.
    ///
    /// Named here rather than built where the statement is, so the statement
    /// can only ever carry one of these four and never anything a caller wrote.
    #[must_use]
    pub const fn column(self) -> &'static str {
        match self {
            Self::Total => "SUM_TIMER_WAIT",
            Self::Calls => "COUNT_STAR",
            Self::Average => "AVG_TIMER_WAIT",
            Self::Rows => "SUM_ROWS_EXAMINED",
        }
    }

    /// The name the answer declares this ranking under.
    ///
    /// The same word the command line accepts, which is the whole point: a
    /// caller reading `sorted_by` back learns the value it would have to write
    /// to ask for the same ranking again.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Total => "total",
            Self::Calls => "calls",
            Self::Average => "average",
            Self::Rows => "rows",
        }
    }
}

/// Ranking the costliest statements.
#[derive(Debug, Clone, Args)]
pub struct TopArgs {
    /// How many signatures to return.
    #[arg(long)]
    pub top: Option<usize>,
    /// What the ranking is ordered by; defaults to total time.
    ///
    /// Deliberately not spelled `--sort`, which is the GLOBAL ordering of the
    /// output and a different thing: this one orders on the SERVER, inside the
    /// statement, so the ceiling on rows keeps the costliest signatures by the
    /// criterion asked for. Ordering afterwards would return the ten costliest
    /// by time, merely rearranged.
    #[arg(long, value_enum, default_value_t = QueryRanking::Total)]
    pub rank_by: QueryRanking,
}