mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Where a statement kept under a name lives between invocations.
//!
//! This module owns the file and nothing else: it reads it, writes it and says
//! plainly when a name was never stored. Deciding whether a call matches the
//! declaration, and whether the statement may be kept at all, is
//! [`super::named`].
//!
//! # The statement is stored, never the values
//!
//! What is kept on disk is the text and the shape of its parameters. A value is
//! given at the moment of the call and travels bound, exactly as it does for a
//! statement written by hand. Storing values would put whatever they carry into
//! a file that outlives the invocation.

use super::prepare::Kind;
use crate::error::{Failure, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

/// The file the stored statements live in, inside the settings location.
pub const FILE_NAME: &str = "named.toml";

/// One declared parameter.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Declared {
    /// The name a caller gives the value under.
    pub name: String,
    /// The kind the value must be, by its stable name.
    pub kind: String,
}

impl Declared {
    /// Reads a declaration written as a name and a kind.
    ///
    /// # Errors
    ///
    /// Returns a usage failure when the shape is wrong or the kind is unknown.
    pub fn parse(text: &str) -> Result<Self> {
        let (name, kind) = text.split_once(':').ok_or_else(|| {
            Failure::usage(
                "usage.malformed_declaration",
                format!("`{text}` does not declare a name and a kind"),
            )
            .with_detail("detail", text)
            .with_hint("write the declaration as name:kind, such as mes:date")
        })?;
        if name.trim().is_empty() {
            return Err(Failure::usage(
                "usage.malformed_declaration",
                "a declared parameter has no name",
            )
            .with_detail("detail", text)
            .with_hint("write the declaration as name:kind"));
        }
        Ok(Self {
            name: name.trim().to_owned(),
            kind: Kind::parse(kind)?.as_str().to_owned(),
        })
    }

    /// The kind this declaration names.
    ///
    /// # Errors
    ///
    /// Returns a usage failure when the stored kind is not one that exists,
    /// which is how a hand-edited file is caught.
    pub fn kind(&self) -> Result<Kind> {
        Kind::parse(&self.kind)
    }
}

/// One statement kept under a name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Stored {
    /// The statement itself, with a marker where each value goes.
    pub statement: String,
    /// The parameters it accepts, in the order the markers appear.
    #[serde(default)]
    pub params: Vec<Declared>,
    /// A ceiling of its own on the rows it may return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_rows: Option<usize>,
}

/// Every statement kept under a name.
#[derive(Debug, Default)]
pub struct Catalogue {
    file: PathBuf,
    entries: BTreeMap<String, Stored>,
}

impl Catalogue {
    /// Reads the stored statements from a settings location.
    ///
    /// A location with no such file yet is an empty catalogue and never a
    /// failure, because nothing has been stored yet.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the file exists and cannot be read
    /// or does not hold what this product wrote.
    pub fn open(directory: &Path) -> Result<Self> {
        let file = directory.join(FILE_NAME);
        if !file.exists() {
            return Ok(Self {
                file,
                entries: BTreeMap::new(),
            });
        }
        let text = std::fs::read_to_string(&file).map_err(|cause| {
            Failure::config(
                "config.named_unreadable",
                "the stored statements could not be read",
            )
            .with_cause(cause.to_string())
        })?;
        let entries = toml::from_str(&text).map_err(|cause| {
            Failure::config(
                "config.named_malformed",
                "the stored statements are not in the form this product writes",
            )
            .with_cause(cause.to_string())
        })?;
        Ok(Self { file, entries })
    }

    /// Where the stored statements live.
    #[must_use]
    pub fn file(&self) -> &Path {
        &self.file
    }

    /// Keeps one statement under a name, replacing any statement of that name.
    pub fn put(&mut self, name: &str, stored: Stored) {
        self.entries.insert(name.to_owned(), stored);
    }

    /// The statement kept under one name.
    ///
    /// # Errors
    ///
    /// Returns an absence failure when nothing is stored under that name.
    pub fn get(&self, name: &str) -> Result<&Stored> {
        self.entries.get(name).ok_or_else(|| unknown(name))
    }

    /// Removes the statement kept under one name.
    ///
    /// # Errors
    ///
    /// Returns an absence failure when nothing is stored under that name.
    pub fn remove(&mut self, name: &str) -> Result<Stored> {
        self.entries.remove(name).ok_or_else(|| unknown(name))
    }

    /// Every stored statement, in a fixed order so two runs agree.
    #[must_use]
    pub fn list(&self) -> Vec<Value> {
        self.entries
            .iter()
            .map(|(name, stored)| {
                json!({
                    "name": name,
                    "statement": stored.statement,
                    "params": stored.params,
                    "max_rows": stored.max_rows,
                })
            })
            .collect()
    }

    /// Writes the catalogue back.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the location cannot be created or
    /// the file cannot be written.
    pub fn save(&self) -> Result<()> {
        if let Some(parent) = self.file.parent() {
            std::fs::create_dir_all(parent).map_err(unwritable)?;
        }
        let text = toml::to_string_pretty(&self.entries).map_err(unwritable)?;
        std::fs::write(&self.file, text).map_err(unwritable)
    }
}

/// The failure a name nothing was ever stored under produces.
fn unknown(name: &str) -> Failure {
    Failure::absence(
        "absence.unknown_named_statement",
        format!("nothing is stored under the name `{name}`"),
    )
    .with_detail("detail", name)
    .with_hint("run `query named list` to see what is stored")
}

/// The failure every way of not writing the catalogue produces.
fn unwritable(cause: impl std::fmt::Display) -> Failure {
    Failure::config(
        "config.named_unwritable",
        "the stored statements could not be written",
    )
    .with_cause(cause.to_string())
}

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

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

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

    #[test]
    fn a_stored_statement_survives_being_written_and_read_back() {
        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");
        assert_eq!(reopened.get("pedidos_do_mes").expect("stored"), &stored());
    }

    #[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"]);
    }

    /// A declaration that names a kind this product does not have is refused
    /// when it is written, not when somebody runs the statement by name.
    #[test]
    fn a_declaration_is_refused_when_it_is_malformed() {
        assert_eq!(
            Declared::parse("mes:date").expect("reads").kind,
            Kind::Date.as_str()
        );
        for (text, code) in [
            ("mes", "usage.malformed_declaration"),
            ("mes:colour", "usage.unknown_parameter_kind"),
        ] {
            assert_eq!(Declared::parse(text).expect_err("must refuse").code(), code);
        }
    }
}