mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The three commands that read the past of a table.
//!
//! This file only routes. Every rule and every refusal lives in
//! [`crate::history`], where it can be proved without a server.

use crate::cli::history::HistoryCommand;
use crate::conn::session::Session;
use crate::error::{Failure, Result};
use crate::history::temporal;
use crate::output::Envelope;

/// Demands an argument the contract layer is allowed to leave out.
///
/// The argument layer lets these be absent so that publishing the contract
/// costs nothing, which makes this the place the requirement is enforced.
///
/// # Errors
///
/// Returns a usage failure naming what is missing and showing the form that
/// carries it.
fn required<'a>(given: Option<&'a str>, what: &str, example: &str) -> Result<&'a str> {
    given.ok_or_else(|| {
        Failure::usage(
            "history.argument_missing",
            format!("reading the past needs the {what}"),
        )
        .with_detail("detail", what)
        .with_hint(format!("name it with --{what}, as in `{example}`"))
    })
}

/// Serves one history command.
///
/// # Errors
///
/// Returns a validation failure when the table keeps no history or the instant
/// asked for lies outside what the table still holds, an absence failure when
/// no database is in force or the named one does not exist, and the mapped
/// driver failure for any other server condition.
pub async fn execute(
    command: &HistoryCommand,
    session: &mut Session,
    named: Option<&str>,
) -> Result<Envelope> {
    /// The form a caller is shown when the table or the instant is missing.
    const AS_OF_FORM: &str = "history as-of --table vendas --at '2026-01-10 09:00'";
    /// The form a caller is shown when an end of the interval is missing.
    const BETWEEN_FORM: &str = "history between --table vendas --from 2026-01-01 --to 2026-02-01";

    // The database a caller named comes from the one global `--database`, and
    // the one in force on the session is what applies when nobody named one.
    let in_force = session.facts().database.clone();
    let connection = session.connection();

    match command {
        HistoryCommand::AsOf(args) => {
            temporal::as_of(
                connection,
                required(args.table.as_deref(), "table", AS_OF_FORM)?,
                required(args.at.as_deref(), "at", AS_OF_FORM)?,
                named,
                in_force.as_deref(),
            )
            .await
        }
        HistoryCommand::Between(args) => {
            temporal::between(
                connection,
                required(args.table.as_deref(), "table", BETWEEN_FORM)?,
                required(args.from.as_deref(), "from", BETWEEN_FORM)?,
                required(args.to.as_deref(), "to", BETWEEN_FORM)?,
                named,
                in_force.as_deref(),
            )
            .await
        }
        HistoryCommand::Tables(_) => {
            crate::history::tables(connection, named, in_force.as_deref()).await
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::cli::history::HistoryCommand;
    use crate::cli::Cli;
    use clap::Parser;

    fn parse(args: &[&str]) -> HistoryCommand {
        parse_whole(args).1
    }

    /// The whole invocation, because the database a caller names is a global
    /// flag now and no longer a field of the command's own arguments.
    fn parse_whole(args: &[&str]) -> (Option<String>, HistoryCommand) {
        let command_line: Vec<String> = std::iter::once("mariadb-cli")
            .chain(args.iter().copied())
            .map(ToOwned::to_owned)
            .collect();
        let cli = Cli::try_parse_from(command_line).expect("accepted form");
        let named = cli.globals.destination.database.clone();
        match cli.command {
            crate::cli::Command::History(command) => (named, command),
            other => panic!("expected a history command, got {other:?}"),
        }
    }

    /// A reading of the past always names the table and the instant, because
    /// neither has a sensible default.
    #[test]
    fn a_reading_of_the_past_names_the_table_and_the_instant() {
        let HistoryCommand::AsOf(args) = parse(&[
            "history",
            "as-of",
            "--table",
            "vendas",
            "--at",
            "2026-01-10 09:00",
        ]) else {
            panic!("expected as-of");
        };
        assert_eq!(args.table.as_deref(), Some("vendas"));
        assert_eq!(args.at.as_deref(), Some("2026-01-10 09:00"));
    }

    /// An interval names both of its ends.
    #[test]
    fn an_interval_names_both_of_its_ends() {
        let (named, HistoryCommand::Between(args)) = parse_whole(&[
            "history",
            "between",
            "--table",
            "vendas",
            "--from",
            "2026-01-01",
            "--to",
            "2026-02-01",
            "--database",
            "loja",
        ]) else {
            panic!("expected between");
        };
        assert_eq!(args.from.as_deref(), Some("2026-01-01"));
        assert_eq!(args.to.as_deref(), Some("2026-02-01"));
        assert_eq!(
            named.as_deref(),
            Some("loja"),
            "the one global flag carries the named database"
        );
    }

    /// The listing runs against the database in force when the caller names
    /// none.
    #[test]
    fn the_listing_falls_back_to_the_database_in_force() {
        let (named, HistoryCommand::Tables(_)) = parse_whole(&["history", "tables"]) else {
            panic!("expected tables");
        };
        assert_eq!(named, None, "nothing named means the one in force applies");
    }
}