mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The commands that only read.
//!
//! Not one of these may leave anything behind. They are gathered here so that
//! is visible at a glance: a command in this file that changed the server would
//! be in the wrong file, which is a cheaper mistake to see than to reason out.

use super::query::{envelope, kept_name, offline_only, statement_text, Context};
use crate::cli::query::{ExplainArgs, NamedAction, NamedArgs, PlanArgs, SampleArgs, StatementArgs};
use crate::error::{Failure, Result};
use crate::exec::{lineage, named, plan, prepare, read, Gated, Policy};
use crate::output::{Envelope, Gap};
use mysql_async::Conn;
use serde_json::json;

/// Answers a statement that returns rows.
pub(super) async fn reading(
    command: &'static str,
    gated: Gated,
    conn: &mut Conn,
    policy: &Policy,
    ceiling: usize,
    conversion: &crate::types::Conversion,
    passed_over: usize,
) -> Result<Envelope> {
    let (data, gaps) =
        read::serve(gated, conn, policy.parse, ceiling, conversion, passed_over).await?;
    Ok(envelope(command, data, gaps))
}
/// Returns the first rows of a table, without the caller writing a statement.
pub(super) async fn sample(
    args: &SampleArgs,
    conn: &mut Conn,
    context: &Context,
) -> Result<Envelope> {
    let table = sampled_table(args)?;
    // The table may name its own database, which is the form every listing
    // writes, and that database wins over the one in force. Without this the
    // whole `database.table` arrived as the table and was quoted inside the
    // database in force, which named nothing.
    let split = crate::introspect::names::split(&table);
    let wanted = args.rows.unwrap_or(context.policy.max_rows);
    let request = read::sample_request(
        &split.name,
        split.database.as_deref().or(context.database.as_deref()),
        wanted,
        context.policy.max_rows,
    )?;
    let gated = prepare::gate(&request, &[], &context.policy)?;
    reading(
        "query sample",
        gated,
        conn,
        &context.policy,
        wanted,
        &context.conversion,
        context.passed_over,
    )
    .await
}
/// Asks the server how it would answer, without running the statement.
pub(super) async fn explain(
    args: &ExplainArgs,
    conn: &mut Conn,
    context: &Context,
) -> Result<Envelope> {
    let text = statement_text(
        &args.statement,
        context.refuses_to_ask,
        context.policy.max_input_bytes,
    )?;
    let gated = prepare::gate(&text, &args.statement.params, &context.policy)?;
    plan::refuse_unplannable(&gated)?;
    let request = plan::explain(&gated, args.trace)?;
    let rows = prepare::exec_rows(conn, &request, gated.params(), &context.conversion).await?;

    let gaps = if args.trace && rows.is_empty() {
        vec![plan::absent_trace()]
    } else {
        Vec::new()
    };
    Ok(envelope(
        "query explain",
        json!({"rows": rows, "measured": false, "trace_requested": args.trace}),
        gaps,
    ))
}
/// Asks for the plan of a statement running on another connection.
pub(super) async fn running_plan(
    args: &PlanArgs,
    conn: &mut Conn,
    context: &Context,
) -> Result<Envelope> {
    let id = observed_connection(args)?;
    let (request, values) = plan::running(id);
    let gated = prepare::gate(&request, &values, &context.policy)?;
    let rows = prepare::exec_rows(conn, gated.sql(), gated.params(), &context.conversion).await?;

    let gaps = if rows.is_empty() {
        vec![Gap::new(
            "plan",
            "not_observable",
            "the statement on that connection has no plan the server can show",
        )]
    } else {
        Vec::new()
    };
    Ok(envelope(
        "query plan",
        json!({"connection": id, "rows": rows}),
        gaps,
    ))
}
/// Runs a statement kept under a name.
pub(super) async fn named_run(
    args: &NamedArgs,
    conn: &mut Conn,
    context: &Context,
) -> Result<Envelope> {
    let NamedAction::Run { name, args: given } = &args.action else {
        return Err(offline_only("query named"));
    };
    let name = kept_name(name)?;
    let catalogue = named::Catalogue::open(&context.config_dir)?;
    let stored = catalogue.get(name)?;
    let values = named::arguments(stored, given)?;

    let gated = prepare::gate(&stored.statement, &values, &context.policy)?;
    read::refuse_if_not_a_read(&gated)?;
    let ceiling = stored.max_rows.unwrap_or(context.policy.max_rows);
    reading(
        "query named",
        gated,
        conn,
        &context.policy,
        ceiling,
        &context.conversion,
        context.passed_over,
    )
    .await
}
/// Demands the table the argument layer is allowed to leave out.
///
/// # Errors
///
/// Returns a usage failure naming the flag that carries the table. The argument
/// layer lets it be absent so that publishing the contract costs nothing, which
/// makes this the place the requirement is really enforced.
fn sampled_table(args: &SampleArgs) -> Result<String> {
    args.table.clone().ok_or_else(|| {
        Failure::usage("query.table_missing", "sampling needs a table to read from")
            .with_hint("name one with --table, as in `query sample --table clientes`")
    })
}

/// Demands the connection the argument layer is allowed to leave out.
///
/// # Errors
///
/// Returns a usage failure naming the flag that carries the connection, for the
/// reason given on [`sampled_table`].
fn observed_connection(args: &PlanArgs) -> Result<u64> {
    args.id.ok_or_else(|| {
        Failure::usage(
            "query.connection_missing",
            "asking for a running plan needs the connection running it",
        )
        .with_hint("name one with --id, as in `query plan --id 42`; `server processes` lists them")
    })
}

/// Resolves every result column of a statement to its physical origin.
pub(super) fn origins(args: &StatementArgs, context: &Context) -> Result<Envelope> {
    let text = statement_text(args, context.refuses_to_ask, context.policy.max_input_bytes)?;
    let gated = prepare::gate(&text, &args.params, &context.policy)?;
    let columns = lineage::resolve(gated.admission().analysis().statements())?;
    Ok(Envelope::new("query lineage", lineage::as_value(&columns)))
}

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

    /// Publishing the contract must cost nothing, so the table is optional to
    /// the argument layer. That moves the requirement here, where a sampling
    /// with no table has to be refused with a code and told which flag carries
    /// it, rather than reaching the server without a subject.
    #[test]
    fn a_sampling_without_a_table_is_refused_with_a_code() {
        let failure = sampled_table(&SampleArgs {
            table: None,
            rows: None,
        })
        .expect_err("must refuse");

        assert_eq!(failure.code(), "query.table_missing");
        assert_eq!(failure.exit_number().code(), 2);
        assert!(
            failure.hint().is_some_and(|hint| hint.contains("--table")),
            "the refusal names the flag that carries the table"
        );
    }

    /// Asking for the plan of a statement without saying whose statement it is
    /// is refused for the same reason.
    #[test]
    fn a_running_plan_without_a_connection_is_refused_with_a_code() {
        let failure = observed_connection(&PlanArgs { id: None }).expect_err("must refuse");

        assert_eq!(failure.code(), "query.connection_missing");
        assert_eq!(failure.exit_number().code(), 2);
        assert!(failure.hint().is_some_and(|hint| hint.contains("--id")));
    }
}