mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The one operation every structure command performs.
//!
//! A descriptor says what to read; a scope says how far. This module turns the
//! pair into a statement, runs it and converts the rows. There is one reader
//! here and every command goes through it, so a fix to quoting, ordering or
//! conversion reaches all of them at once.
//!
//! A caller-supplied name never enters the statement text. It travels as a
//! bound value, and it is still put through the sanctioned quoting check first,
//! so a name the product would refuse to write is refused before it is sent.

use super::kinds::{fields, Descriptor};
use crate::conn::OrFailure;
use crate::error::Result;
use crate::output::envelope::Row;
use crate::sql::ident;
use mysql_async::prelude::Queryable;
use mysql_async::{Conn, Params, Value as Wire};
use serde_json::Value;

/// How far a reading reaches.
#[derive(Debug, Clone, Default)]
pub struct Scope {
    /// Restrict to this database.
    pub database: Option<String>,
    /// Restrict to this table.
    pub table: Option<String>,
    /// Keep only names matching this pattern.
    pub name_pattern: Option<String>,
    /// Return every field instead of the short form.
    pub detailed: bool,
    /// Ceiling on rows read from the server.
    pub limit: Option<usize>,
}

impl Scope {
    /// A reading of one database.
    #[must_use]
    pub fn in_database(database: Option<String>) -> Self {
        Self {
            database,
            ..Self::default()
        }
    }

    /// A reading of one table inside one database.
    #[must_use]
    pub fn on_table(database: Option<String>, table: Option<String>) -> Self {
        Self {
            database,
            table,
            ..Self::default()
        }
    }

    /// The same reading at full depth.
    #[must_use]
    pub const fn detailed(mut self, detailed: bool) -> Self {
        self.detailed = detailed;
        self
    }

    /// The same reading with a ceiling on rows.
    #[must_use]
    pub const fn limited(mut self, limit: Option<usize>) -> Self {
        self.limit = limit;
        self
    }
}

/// A statement together with the values it binds.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Statement {
    /// The statement text, built only from this crate's own strings.
    pub text: String,
    /// The values the statement binds, in order.
    pub values: Vec<String>,
}

impl Statement {
    /// The bound values in the form the driver expects.
    #[must_use]
    fn params(&self) -> Params {
        Params::Positional(
            self.values
                .iter()
                .map(|value| Wire::Bytes(value.clone().into_bytes()))
                .collect(),
        )
    }
}

/// Builds the reading a descriptor and a scope describe.
///
/// # Errors
///
/// Returns a validation failure when a supplied name could not be written as
/// an object name, so a name carrying a control character is refused here
/// rather than being sent to the server.
pub fn build(descriptor: &Descriptor, scope: &Scope) -> Result<Statement> {
    let mut projection = String::new();
    for (position, field) in fields(descriptor, scope.detailed).iter().enumerate() {
        if position > 0 {
            projection.push_str(", ");
        }
        projection.push_str(field.source);
        projection.push_str(" AS ");
        projection.push_str(&ident::quote(field.alias)?);
    }

    let mut text = format!("SELECT {projection} FROM {}", descriptor.source);
    let mut conditions: Vec<String> = descriptor
        .predicate
        .map(ToOwned::to_owned)
        .into_iter()
        .collect();
    let mut values = Vec::new();

    push_equality(
        &mut conditions,
        &mut values,
        descriptor.database_column,
        scope.database.as_deref(),
    )?;
    push_equality(
        &mut conditions,
        &mut values,
        descriptor.table_column,
        scope.table.as_deref(),
    )?;
    if let Some(pattern) = scope.name_pattern.as_deref() {
        conditions.push(format!("{} LIKE ?", descriptor.name_column));
        values.push(pattern.to_owned());
    }

    if !conditions.is_empty() {
        text.push_str(" WHERE ");
        text.push_str(&conditions.join(" AND "));
    }
    if let Some(group) = descriptor.group_by {
        text.push_str(" GROUP BY ");
        text.push_str(group);
    }
    text.push_str(" ORDER BY ");
    text.push_str(descriptor.order_by);
    if let Some(limit) = scope.limit {
        use std::fmt::Write as _;
        // Written straight into the statement rather than through a second
        // string that is built only to be copied in and dropped.
        let _ = write!(text, " LIMIT {limit}");
    }

    Ok(Statement { text, values })
}

/// Adds one equality condition, binding the value rather than writing it.
fn push_equality(
    conditions: &mut Vec<String>,
    values: &mut Vec<String>,
    column: Option<&'static str>,
    supplied: Option<&str>,
) -> Result<()> {
    let (Some(column), Some(supplied)) = (column, supplied) else {
        return Ok(());
    };
    // The value is bound, not written, but a name this product would refuse to
    // write is refused here too, so one rule governs every name.
    ident::quote(supplied)?;
    conditions.push(format!("{column} = ?"));
    values.push(supplied.to_owned());
    Ok(())
}

/// Reads the rows a descriptor and a scope describe.
///
/// # Errors
///
/// Returns a validation failure when a supplied name is not writable, and the
/// mapped driver failure when the server refuses or cannot answer the reading.
pub async fn read(
    connection: &mut Conn,
    descriptor: &Descriptor,
    scope: &Scope,
) -> Result<Vec<Row>> {
    let statement = build(descriptor, scope)?;
    run(connection, &statement).await
}

/// Runs one already-built reading.
///
/// # Errors
///
/// Returns the mapped driver failure when the server refuses or cannot answer,
/// and a limit failure when a value exceeds the ceiling for raw content.
pub async fn run(connection: &mut Conn, statement: &Statement) -> Result<Vec<Row>> {
    let rows: Vec<mysql_async::Row> = connection
        .exec(statement.text.clone(), statement.params())
        .await
        .or_failure()?;
    rows.iter().map(convert_row).collect()
}

/// Converts one server row into the published shape.
fn convert_row(row: &mysql_async::Row) -> Result<Row> {
    let columns = row.columns();
    let mut converted = Row::new();
    for (index, column) in columns.iter().enumerate() {
        let value = row.as_ref(index).cloned().unwrap_or(Wire::NULL);
        converted.insert(
            column.name_str().into_owned(),
            // Catalogue readings carry no byte column, so the published output
            // settings have nothing to apply to. See the note on
            // `Conversion::stable`.
            crate::types::value::convert(&value, column, &crate::types::Conversion::stable())?,
        );
    }
    Ok(converted)
}

/// Reads one number the server keeps about itself.
///
/// # Errors
///
/// Returns the mapped driver failure when the setting cannot be read.
pub async fn setting(connection: &mut Conn, statement: &'static str) -> Result<Option<Value>> {
    let found: Option<String> = connection.query_first(statement).await.or_failure()?;
    Ok(found.map(Value::from))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::introspect::kinds::Kind;

    fn text_for(kind: Kind, scope: &Scope) -> String {
        build(kind.descriptor(), scope).expect("builds").text
    }

    /// A supplied name is bound, never written into the statement, so a name
    /// carrying a separator cannot change what the statement means.
    #[test]
    fn a_supplied_name_is_bound_and_never_written_into_the_statement() {
        let scope = Scope::in_database(Some("shop`; DROP TABLE users; --".to_owned()));
        let statement = build(Kind::Table.descriptor(), &scope).expect("builds");
        assert!(
            !statement.text.contains("DROP TABLE"),
            "the name reached the statement text: {}",
            statement.text
        );
        assert_eq!(
            statement.values,
            vec!["shop`; DROP TABLE users; --".to_owned()]
        );
        assert!(statement.text.contains("TABLE_SCHEMA = ?"));
    }

    /// A name the product would refuse to write is refused before it is sent,
    /// even though it would have travelled as a value.
    #[test]
    fn an_unwritable_name_is_refused_before_the_server_is_reached() {
        let scope = Scope::in_database(Some("bad\nname".to_owned()));
        let failure = build(Kind::Table.descriptor(), &scope).expect_err("must refuse");
        assert_eq!(failure.code(), "ident.control_character");
    }

    /// The condition a kind always carries survives alongside the scope, so a
    /// sequence listing never turns into a table listing.
    #[test]
    fn the_condition_of_a_kind_survives_the_scope() {
        let text = text_for(Kind::Sequence, &Scope::in_database(Some("shop".to_owned())));
        assert!(text.contains("TABLE_TYPE = 'SEQUENCE'"), "{text}");
        assert!(text.contains("TABLE_SCHEMA = ?"), "{text}");
    }

    /// Depth changes the fields and nothing else about the reading.
    #[test]
    fn depth_changes_the_fields_and_not_the_scope() {
        let short = text_for(Kind::Table, &Scope::default());
        let detailed = text_for(Kind::Table, &Scope::default().detailed(true));
        assert!(detailed.len() > short.len());
        assert!(short.contains("`name`") && detailed.contains("`engine`"));
    }

    /// Every reading is ordered, so two runs return the same bytes.
    #[test]
    fn every_reading_is_ordered() {
        for kind in [Kind::Database, Kind::Table, Kind::Column, Kind::Index] {
            assert!(text_for(kind, &Scope::default()).contains(" ORDER BY "));
        }
    }

    /// A grouped kind groups before it orders.
    #[test]
    fn a_grouped_kind_groups_before_it_orders() {
        let text = text_for(Kind::DatabaseSpace, &Scope::default());
        let group = text.find(" GROUP BY ").expect("groups");
        let order = text.find(" ORDER BY ").expect("orders");
        assert!(group < order, "{text}");
    }

    /// A ceiling reaches the server, so a huge catalog is never fully read.
    #[test]
    fn a_ceiling_reaches_the_server() {
        let text = text_for(Kind::ObjectSpace, &Scope::default().limited(Some(10)));
        assert!(text.ends_with(" LIMIT 10"), "{text}");
    }

    /// A pattern narrows by name and travels as a value like any other name.
    #[test]
    fn a_pattern_narrows_by_name_and_travels_as_a_value() {
        let mut scope = Scope::in_database(None);
        scope.name_pattern = Some("ped%".to_owned());
        let statement = build(Kind::Table.descriptor(), &scope).expect("builds");
        assert!(statement.text.contains("TABLE_NAME LIKE ?"));
        assert_eq!(statement.values, vec!["ped%".to_owned()]);
    }

    /// Every published field arrives under a quoted name, so an alias that is
    /// also a reserved word does not break the statement.
    #[test]
    fn every_alias_is_quoted() {
        let text = text_for(Kind::Column, &Scope::default());
        assert!(text.contains(" AS `table`"), "{text}");
        assert!(text.contains(" AS `key`"), "{text}");
    }
}