mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The nineteen structure commands.
//!
//! Every one of them reads metadata and none of them changes anything, so a
//! destination marked read-only answers all nineteen, unless its policy was
//! deliberately widened to cover discovery as well. This module holds no
//! reading logic of its own: it turns a command into a descriptor and a scope
//! and hands both to the one reader in [`crate::introspect::query`].

mod args;
mod read;

use crate::cli::schema::{AdvisableTableArgs, Detail, SchemaCommand};
use crate::conn::Session;
use crate::error::{Failure, Result};
use crate::introspect::kinds::Kind;
use crate::introspect::{grants, Ceilings};
use crate::output::Envelope;

/// How far a destination's own refusal of change reaches.
///
/// A destination put into refuse-every-change mode still answers discovery by
/// default, because discovery is what explains why the policy refused a
/// statement. Taking it away leaves the caller refused and unable to find out
/// why, which is the one thing they need next. A caller who wants the
/// destination closed to reading as well asks for it, and never gets it as a
/// side effect of asking for the change refusal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PolicyScope {
    /// The refusal covers statements only, and never discovery.
    Change,
    /// The refusal covers discovery too.
    All,
}

impl PolicyScope {
    /// Reads the scope from the word stored under `sql.policy_scope`.
    ///
    /// There is no fallback branch on purpose. The registry is the one place
    /// the default of that key lives, and a fallback here would be a second
    /// one, silently winning wherever the two disagreed.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the word is outside the domain the
    /// registry publishes for that key.
    pub fn parse(word: &str) -> Result<Self> {
        match word {
            "change" => Ok(Self::Change),
            "all" => Ok(Self::All),
            other => Err(Failure::config(
                "config.unknown_policy_scope",
                format!("`{other}` is not a reach a policy can have"),
            )
            .with_detail("detail", other)
            .with_hint("set sql.policy_scope to change or to all")),
        }
    }

    /// Whether discovery is covered by the refusal.
    #[must_use]
    pub const fn covers_discovery(self) -> bool {
        matches!(self, Self::All)
    }
}

/// Where the invocation is pointed and what it may spend.
#[derive(Debug, Clone)]
pub struct Target {
    /// The database to use when the command names none.
    pub database: Option<String>,
    /// Every ceiling these commands obey.
    pub ceilings: Ceilings,
    /// Whether this invocation refuses every change.
    pub read_only: bool,
    /// How far that refusal reaches.
    pub policy_scope: PolicyScope,
    /// Whether the structural warning is on without the mark asking for it.
    ///
    /// The warning costs two extra readings of the catalogue, so it is off
    /// until somebody asks. The mark asks for one invocation and this key asks
    /// for every one of them.
    pub index_advice: bool,
}

/// Serves one structure command.
///
/// # Errors
///
/// Returns an absence failure when a named object is not visible, a validation
/// failure when a supplied name is not writable or when the destination's own
/// policy reaches discovery, a limit failure when an exact count would cost
/// more than the ceiling allows, and the mapped driver failure when a reading
/// cannot be answered.
pub async fn execute(
    command: &SchemaCommand,
    session: &mut Session,
    target: &Target,
) -> Result<Envelope> {
    let name = command.published_name();
    admit_discovery(name, target)?;
    match command {
        SchemaCommand::Map(args) => read::compact_map(name, args, session, target).await,
        SchemaCommand::Databases => {
            read::listing(name, Kind::Database, session, None, None, true).await
        }
        SchemaCommand::Tables(args) => read::tables(name, args, session, target).await,
        SchemaCommand::Columns(args) => {
            let deep = Detail::or_default(args.detail, Detail::Full);
            read::on_table(name, Kind::Column, args, deep, session, target).await
        }
        SchemaCommand::Keys(args) => {
            read::advised(name, Kind::ForeignKey, args, session, target).await
        }
        SchemaCommand::Indexes(args) => {
            read::advised(name, Kind::Index, args, session, target).await
        }
        SchemaCommand::Checks(args) => {
            let deep = Detail::or_default(args.detail, Detail::Full);
            read::on_table(name, Kind::Check, args, deep, session, target).await
        }
        SchemaCommand::Views(args) => read::views(name, args, session, target).await,
        SchemaCommand::Routines(args) => {
            read::in_database(name, Kind::Routine, args, session, target).await
        }
        SchemaCommand::Triggers(args) => {
            read::in_database(name, Kind::Trigger, args, session, target).await
        }
        SchemaCommand::Events(args) => read::events(name, args, session, target).await,
        SchemaCommand::Sequences(args) => read::sequences(name, args, session, target).await,
        SchemaCommand::Partitions(args) => {
            let deep = Detail::or_default(args.detail, Detail::Summary);
            read::on_table(name, Kind::Partition, args, deep, session, target).await
        }
        SchemaCommand::Search(args) => read::find(name, args, session, target).await,
        SchemaCommand::Stats(args) => read::stats(name, args, session, target).await,
        SchemaCommand::Ddl(args) => read::definition(name, args, session, target).await,
        SchemaCommand::Count(args) => read::count(name, args, session, target).await,
        SchemaCommand::Size(args) => read::size(name, args, session, target).await,
        SchemaCommand::Grants => Ok(Envelope::new(
            name,
            grants::effective(session.connection()).await?,
        )),
    }
}

/// Whether the structural warning is to be computed for this reading.
///
/// The mark asks for this one invocation and the key asks for every one, so
/// either is enough and neither can turn the other off. A key that could be
/// overruled by the absence of a mark would be a key that never worked.
#[must_use]
pub fn advice_wanted(args: &AdvisableTableArgs, target: &Target) -> bool {
    args.advise || target.index_advice
}

/// Refuses discovery when the destination's own policy reaches that far.
///
/// Kept apart from the readings so the refusal is provable without a server,
/// since it is the policy and not the network that refuses. It runs before the
/// command is routed, so no reading is even started.
///
/// # Errors
///
/// Returns a validation failure naming the reading that was refused and the
/// key that widened the policy to cover it.
pub fn admit_discovery(name: &'static str, target: &Target) -> Result<()> {
    if !(target.read_only && target.policy_scope.covers_discovery()) {
        return Ok(());
    }
    Err(Failure::validation(
        "safety.policy_covers_discovery",
        format!("this destination refuses every operation, and `{name}` is one"),
    )
    .with_detail("detail", name)
    .with_hint(
        "set sql.policy_scope to change to keep discovery open, \
         or drop the refusal of change altogether",
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::introspect::map;

    /// The command a caller names decides the database only when the caller
    /// named none of its own.
    /// The database a command works on comes from the target and from nowhere
    /// else.
    ///
    /// There used to be a `wanted` helper choosing between a database named on
    /// the command and the one the target carried. Sixteen commands declared
    /// their own `--database` against the one global flag, so the two were
    /// always the same word typed once, and the choice was between a value and
    /// a copy of itself. The target is now the single source.
    #[test]
    fn the_database_comes_from_the_target_alone() {
        let target = Target {
            database: Some("in_force".to_owned()),
            ..open_target()
        };
        assert_eq!(target.database.clone(), Some("in_force".to_owned()));
        assert_eq!(open_target().database, None);
    }

    /// A destination nothing was said about: discovery open, warning off.
    fn open_target() -> Target {
        Target {
            database: None,
            ceilings: ceilings(),
            read_only: false,
            policy_scope: PolicyScope::Change,
            index_advice: false,
        }
    }

    /// The refusal of change leaves discovery open, because discovery is what
    /// explains the refusal. Widening the policy is what closes it, and that
    /// takes both the refusal and the wider reach.
    #[test]
    fn discovery_is_refused_only_when_the_policy_was_widened_to_reach_it() {
        assert!(admit_discovery("schema tables", &open_target()).is_ok());

        let refusing_change = Target {
            read_only: true,
            ..open_target()
        };
        assert!(
            admit_discovery("schema tables", &refusing_change).is_ok(),
            "refusing change must never take discovery away by itself"
        );

        let widened_but_writable = Target {
            policy_scope: PolicyScope::All,
            ..open_target()
        };
        assert!(
            admit_discovery("schema tables", &widened_but_writable).is_ok(),
            "a wider reach refuses nothing while nothing is refused"
        );

        let closed = Target {
            read_only: true,
            policy_scope: PolicyScope::All,
            ..open_target()
        };
        let failure = admit_discovery("schema tables", &closed).expect_err("must refuse");
        assert_eq!(failure.code(), "safety.policy_covers_discovery");
        assert_eq!(failure.exit_number().code(), 3);
        assert!(failure.message().contains("schema tables"));
        assert!(failure
            .hint()
            .is_some_and(|hint| hint.contains("sql.policy_scope")));
    }

    /// The word stored under the key decides the reach, and a word outside the
    /// published domain is refused rather than quietly read as the default.
    #[test]
    fn the_reach_of_the_policy_is_read_from_its_own_word() {
        assert_eq!(
            PolicyScope::parse("change").expect("published"),
            PolicyScope::Change
        );
        assert_eq!(
            PolicyScope::parse("all").expect("published"),
            PolicyScope::All
        );
        assert!(!PolicyScope::Change.covers_discovery());
        assert!(PolicyScope::All.covers_discovery());

        let failure = PolicyScope::parse("sometimes").expect_err("outside the domain");
        assert_eq!(failure.code(), "config.unknown_policy_scope");
    }

    fn ceilings() -> Ceilings {
        Ceilings {
            map: map::Budget {
                tables: 200,
                rows: 20_000,
            },
            search_rows: 200,
            ranked_objects: 20,
            countable_rows: 10_000_000,
        }
    }
}