mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The commands that change the server.
//!
//! Every one of these goes through [`crate::exec::change`] or through the guard
//! that admits a change, so none of them can reach the server without the
//! ceilings that guard a change. Measuring a plan for real is here and not with
//! the reads, because the server produces those numbers by running the
//! statement.

use super::query::{envelope, read_standard_input, statement_text, Context};
use crate::cli::query::{CallArgs, FileArgs, StatementArgs, TxArgs};
use crate::error::{Failure, Result};
use crate::exec::{change, plan, prepare, routine, script};
use crate::output::Envelope;
use mysql_async::Conn;
use serde_json::json;

/// Asks the server for the same plan with measured rather than estimated
/// numbers, which it produces by running the statement.
///
/// That makes this a change in every sense that matters, so it is confirmed
/// like one and obeys the same ceiling.
pub(super) async fn measure(
    args: &StatementArgs,
    conn: &mut Conn,
    context: &mut Context,
    server_read_only: bool,
) -> 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)?;
    plan::refuse_unplannable(&gated)?;

    context.policy.admit_change("query analyze")?;
    // The measured plan is measured BY running the statement, so a preview of
    // it is the statement. `query explain` is the reading that does not run.
    context.policy.admit_simulation("query analyze")?;
    context.write_state.admit(server_read_only)?;
    let (predicted, gap) = change::admit_scale(conn, &gated, context.policy.max_affected).await?;

    let request = plan::measure(&gated)?;
    let rows = prepare::exec_rows(conn, &request, gated.params(), &context.conversion).await?;
    Ok(envelope(
        "query analyze",
        json!({"rows": rows, "measured": true, "predicted_rows": predicted}),
        gap.into_iter().collect(),
    ))
}
/// Reads the file a run was given, with the separator that cuts it.
///
/// The whole-answer path and the continuous path take the same file the same
/// way, so neither can drift into reading it differently from the other.
///
/// # Errors
///
/// Returns a usage failure when no file was named or the separator is empty,
/// and an absence failure when the file could not be read.
pub(crate) fn script_to_run(
    args: &FileArgs,
    policy: &crate::exec::Policy,
) -> Result<(String, String)> {
    let path = file_to_run(args)?;
    let delimiter = args
        .delimiter
        .clone()
        .unwrap_or_else(|| policy.delimiter.clone());
    script::validate_delimiter(&delimiter)?;

    // Measured before it is read, not after. The size ceiling below this one
    // bounds a statement, and a statement was only ever measured once the whole
    // file was already resident.
    let text = super::input::file_within(&path, policy.max_input_bytes)?;
    Ok((text, delimiter))
}

/// Runs a file of statements, stopping at the first one that fails.
pub(super) async fn file(
    args: &FileArgs,
    conn: &mut Conn,
    context: &mut Context,
    server_read_only: bool,
) -> Result<Envelope> {
    let (text, delimiter) = script_to_run(args, &context.policy)?;
    // The cut is a walk and not a list: the statements arrive one at a time,
    // so a long script costs its longest statement rather than its whole self.
    let statements = script::split(&text, &delimiter)?;
    let mut run = script::Run {
        conn,
        policy: &context.policy,
        write_state: &mut context.write_state,
        server_read_only,
        conversion: &context.conversion,
        stop_on_failure: stops_at_the_first_failure(args),
    };
    let data = script::run_file(statements, &mut run).await?;
    Ok(Envelope::new("query file", data))
}
/// Whether a failed statement ends the file, which is what it does unless the
/// caller asked otherwise.
///
/// # Why the default is to stop
///
/// A statement that failed may well be the one the rest depended on, so
/// carrying on would apply a script whose first half never happened. Carrying
/// on is therefore something a caller asks for about a file they know is a
/// list of independent statements.
#[must_use]
pub fn stops_at_the_first_failure(args: &FileArgs) -> bool {
    args.on_error.is_none_or(crate::cli::data::OnError::stops)
}

/// Runs statements together, so they are confirmed or undone as one.
pub(super) async fn block(
    args: &TxArgs,
    conn: &mut Conn,
    context: &mut Context,
    server_read_only: bool,
) -> Result<Envelope> {
    let statements =
        block_statements(args, context.refuses_to_ask, context.policy.max_input_bytes)?;
    context.policy.admit_change("query tx")?;
    context.write_state.admit(server_read_only)?;

    let (gated, gaps) = script::gate_block(&statements, &context.policy)?;
    let mut run = script::Run {
        conn,
        policy: &context.policy,
        write_state: &mut context.write_state,
        server_read_only,
        conversion: &context.conversion,
        // A block is confirmed or undone whole, so skipping inside one would
        // confirm a script that half happened.
        stop_on_failure: true,
    };
    let data = script::run_block(&gated, &mut run).await?;
    Ok(envelope("query tx", data, gaps))
}

/// Reads the statements a block was given.
///
/// # Errors
///
/// Returns a usage failure when the block carries no statement, and a
/// configuration failure when the standard input could not be read.
fn block_statements(args: &TxArgs, refuses_to_ask: bool, ceiling: usize) -> Result<Vec<String>> {
    if !args.statements.is_empty() {
        return Ok(args.statements.clone());
    }
    if let Some(path) = &args.file {
        // The same absence a file of statements answers with, and not a code of
        // this block's own. One unreadable file is one condition, and a second
        // name for it would make a caller branch on where the path was written
        // rather than on what went wrong.
        let text = super::input::file_within(path, ceiling)?;
        return Ok(lines_of(&text));
    }
    if !args.stdin {
        return Err(
            Failure::usage("usage.no_statement", "the block carries no statement")
                .with_hint("give each statement with --statement, with --file, or pass --stdin"),
        );
    }
    Ok(lines_of(&read_standard_input(refuses_to_ask, ceiling)?))
}

/// The statements a block file or a standard input carries, one per line.
///
/// Blank lines are dropped rather than sent, because an empty statement is not
/// a statement and the server would refuse the whole block over it.
fn lines_of(text: &str) -> Vec<String> {
    text.lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(ToOwned::to_owned)
        .collect()
}
/// Calls a stored routine and keeps every result set apart.
pub(super) async fn call(
    args: &CallArgs,
    conn: &mut Conn,
    context: &mut Context,
    server_read_only: bool,
) -> Result<Envelope> {
    let routine_name = routine_to_call(args)?;
    // The routine may name its own database, which is the form `schema
    // routines` writes, and that database wins over the one in force. This
    // server calls `other.routine` from a session on another database, so a
    // caller pasting the listed name expects the same.
    let split = crate::introspect::names::split(&routine_name);
    let data = routine::serve(
        routine::Call {
            routine: &split.name,
            database: split.database.as_deref().or(context.database.as_deref()),
            values: &args.params,
            outputs: &args.outputs,
        },
        conn,
        &context.policy,
        &mut context.write_state,
        server_read_only,
        &context.conversion,
    )
    .await?;
    Ok(Envelope::new("query call", data))
}

/// Demands the file the argument layer is allowed to leave out.
///
/// # Errors
///
/// Returns a usage failure showing the form that carries the file. 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 file_to_run(args: &FileArgs) -> Result<std::path::PathBuf> {
    args.path.clone().ok_or_else(|| {
        Failure::usage(
            "query.path_missing",
            "running a file of statements needs the file to run",
        )
        .with_hint("name one as the first word, as in `query file carga.sql`")
    })
}

/// Demands the routine the argument layer is allowed to leave out.
///
/// # Errors
///
/// Returns a usage failure showing the form that carries the routine, for the
/// reason given on [`file_to_run`].
fn routine_to_call(args: &CallArgs) -> Result<String> {
    args.routine.clone().ok_or_else(|| {
        Failure::usage(
            "query.routine_missing",
            "calling a routine needs the routine to call",
        )
        .with_hint("name one as the first word, as in `query call recalcular_saldo`")
    })
}

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

    /// Publishing the contract must cost nothing, so the file is optional to
    /// the argument layer. That moves the requirement here, where a run with no
    /// file has to be refused with a code and shown the form that carries one.
    #[test]
    fn a_run_of_a_file_without_the_file_is_refused_with_a_code() {
        let failure = file_to_run(&FileArgs {
            on_error: None,
            path: None,
            delimiter: None,
        })
        .expect_err("must refuse");

        assert_eq!(failure.code(), "query.path_missing");
        assert_eq!(failure.exit_number().code(), 2);
        assert!(failure
            .hint()
            .is_some_and(|hint| hint.contains("query file")));
    }

    /// A call with nothing to call is refused for the same reason.
    #[test]
    fn a_call_without_a_routine_is_refused_with_a_code() {
        let failure = routine_to_call(&CallArgs {
            outputs: Vec::new(),
            routine: None,
            params: Vec::new(),
        })
        .expect_err("must refuse");

        assert_eq!(failure.code(), "query.routine_missing");
        assert_eq!(failure.exit_number().code(), 2);
        assert!(failure
            .hint()
            .is_some_and(|hint| hint.contains("query call")));
    }

    /// A block with nothing in it is refused before the block is ever opened,
    /// so an empty run never leaves an atomic block on the server.
    #[test]
    fn a_block_with_no_statement_is_refused_before_the_block_is_opened() {
        let empty = TxArgs {
            file: None,
            statements: Vec::new(),
            stdin: false,
        };
        let failure = block_statements(&empty, false, crate::exec::DEFAULT_MAX_INPUT_BYTES)
            .expect_err("must refuse");
        assert_eq!(failure.code(), "usage.no_statement");
        assert_eq!(failure.exit_number().code(), 2);
    }

    #[test]
    fn statements_given_on_the_command_line_are_taken_in_the_order_written() {
        let written = TxArgs {
            file: None,
            statements: vec!["SELECT 1".to_owned(), "SELECT 2".to_owned()],
            stdin: false,
        };
        assert_eq!(
            block_statements(&written, false, crate::exec::DEFAULT_MAX_INPUT_BYTES)
                .expect("both given"),
            vec!["SELECT 1".to_owned(), "SELECT 2".to_owned()]
        );
    }
}