mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Running a statement kept under a name.
//!
//! # Why the declaration matters
//!
//! A caller who runs an operation by name never writes the statement, so the
//! only description of what the operation accepts is the declaration stored
//! with it. Every value is therefore checked against its declared kind before
//! anything else happens, which is why a wrong kind costs no connection.
//!
//! The file those declarations live in is [`super::named_store`].

pub use super::named_store::{Catalogue, Declared, Stored, FILE_NAME};

use crate::error::{Failure, Result};
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::path::Path;

/// Counts the value markers a statement carries, over its blanked text.
///
/// The count runs over the blanked text, so a marker that is really a character
/// inside a text literal is not counted as one.
#[must_use]
pub fn count_markers(statement: &str) -> usize {
    crate::sql::strip(statement)
        .text()
        .chars()
        .filter(|character| *character == '?')
        .count()
}

/// Matches the values given against the parameters declared.
///
/// Every check here happens before a connection is opened, so a missing value
/// or a wrong kind costs nothing but the check itself.
///
/// # Errors
///
/// Returns a usage failure when a value is missing, when a value is not of its
/// declared kind, or when a value was given under a name that is not declared.
pub fn arguments(stored: &Stored, given: &[String]) -> Result<Vec<String>> {
    let mut supplied = BTreeMap::new();
    for pair in given {
        let (name, value) = pair.split_once('=').ok_or_else(|| {
            Failure::usage(
                "usage.malformed_argument",
                format!("`{pair}` does not give a name and a value"),
            )
            .with_detail("detail", pair.clone())
            .with_hint("write the argument as name=value")
        })?;
        supplied.insert(name.trim().to_owned(), value.to_owned());
    }

    let mut ordered = Vec::with_capacity(stored.params.len());
    for declared in &stored.params {
        let value = supplied.remove(&declared.name).ok_or_else(|| {
            Failure::usage(
                "usage.missing_argument",
                format!("`{}` was declared and no value was given", declared.name),
            )
            .with_detail("detail", declared.name.clone())
            .with_hint("give every declared parameter as --arg name=value")
        })?;
        let kind = declared.kind()?;
        if !kind.accepts(&value) {
            return Err(Failure::usage(
                "usage.argument_kind",
                format!(
                    "`{}` was declared as {} and the value given is not one",
                    declared.name,
                    kind.as_str()
                ),
            )
            .with_detail("detail", format!("{}:{}", declared.name, kind.as_str()))
            .with_hint("give a value of the declared kind"));
        }
        ordered.push(value);
    }

    if let Some(extra) = supplied.keys().next() {
        return Err(Failure::usage(
            "usage.undeclared_argument",
            format!("`{extra}` was given and this statement declares no such parameter"),
        )
        .with_detail("detail", extra.clone())
        .with_hint("run `query named list` to see what this statement accepts"));
    }
    Ok(ordered)
}

/// Keeps one statement under a name, after proving it admissible.
///
/// The statement is put through the same defences now rather than at the moment
/// somebody runs it by name, because whoever runs it by name never sees its
/// text and could not tell why it was refused.
///
/// # Errors
///
/// Returns the refusal the statement earned, a usage failure when a declaration
/// is malformed, and a configuration failure when the catalogue cannot be
/// written.
pub fn keep(
    catalogue: &mut Catalogue,
    name: &str,
    statement: &str,
    declarations: &[String],
    max_rows: Option<usize>,
    policy: &crate::exec::Policy,
) -> Result<()> {
    let params = declarations
        .iter()
        .map(|text| Declared::parse(text))
        .collect::<Result<Vec<_>>>()?;
    let markers = vec![String::new(); count_markers(statement)];
    crate::exec::prepare::gate(statement, &markers, policy)?;

    catalogue.put(
        name,
        Stored {
            statement: statement.to_owned(),
            params,
            max_rows,
        },
    );
    // The refusal above has already read the statement, so a simulation answers
    // the question a caller actually asked — whether this statement may be kept
    // under this name — and withholds only the keeping. The catalogue in hand
    // dies with this process; `save` is what outlives it.
    if policy.dry_run {
        return Ok(());
    }
    catalogue.save()
}

/// Keeps, lists or removes a statement stored under a name.
///
/// None of these reaches the server: the catalogue lives beside the settings,
/// so listing what is stored and removing an entry cost no connection.
///
/// # Errors
///
/// Returns the refusal a statement earned when it is kept, an absence failure
/// when a name that was never stored is removed, and a usage failure when the
/// action asked for is the one that does reach the server.
pub fn serve(
    action: &crate::cli::query::NamedAction,
    directory: &Path,
    policy: &crate::exec::Policy,
) -> Result<Value> {
    use crate::cli::query::NamedAction;

    let mut catalogue = Catalogue::open(directory)?;
    match action {
        NamedAction::Save {
            name,
            statement,
            params,
            max_rows,
        } => {
            keep(&mut catalogue, name, statement, params, *max_rows, policy)?;
            Ok(json!({"stored": true, "name": name, "simulated": policy.dry_run}))
        }
        NamedAction::List => Ok(json!({"rows": catalogue.list()})),
        NamedAction::Remove { name } => {
            // Removing from the catalogue in hand is what refuses a name that
            // was never stored, so a simulation earns the same absence failure
            // the real removal would. Only the saving is withheld.
            catalogue.remove(name)?;
            if !policy.dry_run {
                catalogue.save()?;
            }
            Ok(json!({"removed": true, "name": name, "simulated": policy.dry_run}))
        }
        NamedAction::Run { .. } => Err(Failure::usage(
            "usage.needs_a_connection",
            "running a stored statement reaches the server",
        )
        .with_hint("route this action through the path that opens a connection")),
    }
}

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

    fn stored() -> Stored {
        Stored {
            statement: "SELECT * FROM pedidos WHERE mes = ? AND pago = ?".to_owned(),
            params: vec![
                Declared {
                    name: "mes".to_owned(),
                    kind: "date".to_owned(),
                },
                Declared {
                    name: "pago".to_owned(),
                    kind: "boolean".to_owned(),
                },
            ],
            max_rows: Some(100),
        }
    }

    fn scratch() -> tempfile::TempDir {
        tempfile::tempdir().expect("scratch directory")
    }

    /// Running by name must never require the statement text, or the whole
    /// point of storing it is lost.
    #[test]
    fn running_by_name_needs_only_the_name_and_the_declared_values() {
        let dir = scratch();
        let mut catalogue = Catalogue::open(dir.path()).expect("opens");
        catalogue.put("pedidos_do_mes", stored());
        catalogue.save().expect("saves");

        let reopened = Catalogue::open(dir.path()).expect("reopens");
        let found = reopened.get("pedidos_do_mes").expect("stored");
        assert_eq!(
            found,
            &stored(),
            "the statement survives being written back"
        );
        assert_eq!(
            arguments(
                found,
                &["mes=2026-01-31".to_owned(), "pago=true".to_owned()]
            )
            .expect("both values are of their kind"),
            vec!["2026-01-31".to_owned(), "true".to_owned()]
        );
    }

    /// Every one of these is caught before a connection is opened, so a wrong
    /// call costs nothing but the check itself.
    #[test]
    fn a_call_that_does_not_match_the_declaration_is_refused_before_connecting() {
        let cases = [
            (
                vec!["mes=janeiro".to_owned(), "pago=true".to_owned()],
                "usage.argument_kind",
                "date",
            ),
            (
                vec!["mes=2026-01-31".to_owned()],
                "usage.missing_argument",
                "pago",
            ),
            (
                vec![
                    "mes=2026-01-31".to_owned(),
                    "pago=true".to_owned(),
                    "outro=1".to_owned(),
                ],
                "usage.undeclared_argument",
                "outro",
            ),
        ];
        for (given, code, mentioned) in cases {
            let failure = arguments(&stored(), &given).expect_err("must refuse");
            assert_eq!(failure.code(), code, "given {given:?}");
            assert_eq!(failure.exit_number().code(), 2);
            assert!(failure.message().contains(mentioned), "given {given:?}");
        }
    }

    /// The markers are positional, so the order that matters is the one the
    /// declaration fixed and never the one the caller happened to type.
    #[test]
    fn the_values_are_ordered_by_the_declaration_and_not_by_the_call() {
        let ordered = arguments(
            &stored(),
            &["pago=false".to_owned(), "mes=2026-01-31".to_owned()],
        )
        .expect("both given");
        assert_eq!(ordered, vec!["2026-01-31".to_owned(), "false".to_owned()]);
    }

    #[test]
    fn an_argument_without_a_value_is_refused_with_the_shape_it_should_have() {
        let failure = arguments(&stored(), &["mes".to_owned()]).expect_err("must refuse");
        assert_eq!(failure.code(), "usage.malformed_argument");
        assert!(failure
            .hint()
            .is_some_and(|hint| hint.contains("name=value")));
    }

    #[test]
    fn a_name_that_was_never_stored_is_an_absence_and_not_a_failure_of_use() {
        let dir = scratch();
        let mut catalogue = Catalogue::open(dir.path()).expect("opens");
        let failure = catalogue.get("nao_existe").expect_err("must refuse");
        assert_eq!(failure.code(), "absence.unknown_named_statement");
        assert_eq!(failure.exit_number().code(), 8);
        assert_eq!(
            catalogue
                .remove("nao_existe")
                .expect_err("must refuse")
                .code(),
            "absence.unknown_named_statement"
        );
        assert!(catalogue.list().is_empty());
        assert!(catalogue.file().ends_with(FILE_NAME));
    }

    #[test]
    fn the_listing_is_ordered_so_two_runs_produce_the_same_bytes() {
        let dir = scratch();
        let mut catalogue = Catalogue::open(dir.path()).expect("opens");
        for name in ["zebra", "alfa", "meio"] {
            catalogue.put(name, stored());
        }
        let names: Vec<String> = catalogue
            .list()
            .iter()
            .filter_map(|entry| entry["name"].as_str().map(ToOwned::to_owned))
            .collect();
        assert_eq!(names, vec!["alfa", "meio", "zebra"]);
    }

    #[test]
    fn the_markers_of_a_statement_are_counted_over_its_blanked_text() {
        assert_eq!(count_markers("SELECT * FROM t WHERE a = ? AND b = ?"), 2);
        assert_eq!(
            count_markers("SELECT 'why?' FROM t WHERE a = ?"),
            1,
            "a marker inside a literal is not a marker"
        );
    }
}