mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! What a kind of object is, and what shape its description takes.
//!
//! This module holds the vocabulary; [`super::catalog`] holds the entries
//! written in it. Keeping them apart means a new kind of object is one entry
//! of data, and a change to how a description is shaped is one change here.
//!
//! A descriptor carries the short field list and, apart from it, the fields
//! the detailed form adds. The detailed form is therefore the short one plus
//! its extras by construction, and the two can never drift apart into telling
//! a caller different things about the same object.

/// One projected field: where the catalog keeps it and how it is published.
#[derive(Debug, Clone, Copy)]
pub struct Field {
    /// The catalog expression that produces the value.
    pub source: &'static str,
    /// The name the value carries in the answer.
    pub alias: &'static str,
}

/// Declares one projected field.
#[must_use]
pub const fn field(source: &'static str, alias: &'static str) -> Field {
    Field { source, alias }
}

/// The kinds of object this product can read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    /// A database.
    Database,
    /// A base table.
    Table,
    /// A column of a table or view.
    Column,
    /// A link from one table to another.
    ForeignKey,
    /// An index, one row per indexed column.
    Index,
    /// A restriction on the values a row may carry.
    Check,
    /// A view.
    View,
    /// A stored function or procedure.
    Routine,
    /// A trigger.
    Trigger,
    /// A scheduled event.
    Event,
    /// A number generator.
    Sequence,
    /// One partition of a table.
    Partition,
    /// The cheap, estimated figures of a table.
    Statistic,
    /// Space totalled per database.
    DatabaseSpace,
    /// Space per object, largest first.
    ObjectSpace,
}

/// Every kind, so a rule about all of them can be stated once.
pub static ALL: &[Kind] = &[
    Kind::Database,
    Kind::Table,
    Kind::Column,
    Kind::ForeignKey,
    Kind::Index,
    Kind::Check,
    Kind::View,
    Kind::Routine,
    Kind::Trigger,
    Kind::Event,
    Kind::Sequence,
    Kind::Partition,
    Kind::Statistic,
    Kind::DatabaseSpace,
    Kind::ObjectSpace,
];

/// The kinds a name search looks through, in the order it reports them.
///
/// A column is here because half of what a caller half-remembers is a column
/// name, and a database is here because a search narrowed to no database has
/// to be able to find the database itself.
pub static SEARCHABLE: &[Kind] = &[
    Kind::Database,
    Kind::Table,
    Kind::Column,
    Kind::View,
    Kind::Routine,
    Kind::Trigger,
    Kind::Event,
    Kind::Sequence,
    Kind::Index,
];

impl Kind {
    /// The stable name of this kind, as published and as accepted on input.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Database => "database",
            Self::Table => "table",
            Self::Column => "column",
            Self::ForeignKey => "key",
            Self::Index => "index",
            Self::Check => "check",
            Self::View => "view",
            Self::Routine => "routine",
            Self::Trigger => "trigger",
            Self::Event => "event",
            Self::Sequence => "sequence",
            Self::Partition => "partition",
            Self::Statistic => "statistic",
            Self::DatabaseSpace => "database_space",
            Self::ObjectSpace => "object_space",
        }
    }

    /// The kind that goes by this published name.
    #[must_use]
    pub fn parse(name: &str) -> Option<Self> {
        ALL.iter().copied().find(|kind| kind.as_str() == name)
    }
}

/// Everything the generic reader needs to know about one kind.
#[derive(Debug, Clone, Copy)]
pub struct Descriptor {
    /// The kind this describes.
    pub kind: Kind,
    /// The metadata table, with any join it needs.
    pub source: &'static str,
    /// The fields every form returns.
    pub short: &'static [Field],
    /// The fields the detailed form adds to the short ones.
    pub extra: &'static [Field],
    /// The catalog column holding the owning database, when there is one.
    pub database_column: Option<&'static str>,
    /// The catalog column holding the owning table, when there is one.
    pub table_column: Option<&'static str>,
    /// The catalog column holding the object's own name.
    pub name_column: &'static str,
    /// A condition that always applies to this kind.
    pub predicate: Option<&'static str>,
    /// The grouping this kind needs, when it aggregates.
    pub group_by: Option<&'static str>,
    /// The ordering, so two runs return the same rows in the same order.
    pub order_by: &'static str,
}

/// What a descriptor is before it says anything of its own.
///
/// Every kind states only what makes it different, so a field nobody set
/// cannot quietly mean something.
pub const PLAIN: Descriptor = Descriptor {
    kind: Kind::Table,
    source: "",
    short: &[],
    extra: &[],
    database_column: None,
    table_column: None,
    name_column: "",
    predicate: None,
    group_by: None,
    order_by: "",
};

/// The fields a kind returns at the asked-for depth.
///
/// The detailed form is the short form plus the extras, so asking for more
/// never returns less.
#[must_use]
pub fn fields(descriptor: &Descriptor, detailed: bool) -> Vec<Field> {
    let extra = if detailed { descriptor.extra } else { &[] };
    descriptor.short.iter().chain(extra).copied().collect()
}

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

    /// Every kind answers to its own name and to nobody else's.
    #[test]
    fn every_kind_answers_to_its_own_name() {
        for kind in ALL.iter().copied() {
            assert_eq!(Kind::parse(kind.as_str()), Some(kind));
        }
        assert_eq!(ALL.len(), 15, "the published set has a fixed size");
        assert_eq!(Kind::parse("not_a_kind"), None);
    }

    /// Every kind a search looks through is a kind this product knows.
    #[test]
    fn every_searchable_kind_is_a_published_kind() {
        for kind in SEARCHABLE {
            assert!(ALL.contains(kind), "{}", kind.as_str());
        }
    }

    /// Asking for more never returns less, and what the short form said keeps
    /// saying the same thing in the same place.
    #[test]
    fn the_detailed_form_is_the_short_one_plus_its_extras() {
        static SHORT: &[Field] = &[field("A", "a")];
        static EXTRA: &[Field] = &[field("B", "b")];
        let descriptor = Descriptor {
            short: SHORT,
            extra: EXTRA,
            ..PLAIN
        };
        let short = fields(&descriptor, false);
        let detailed = fields(&descriptor, true);
        assert_eq!(short.len(), 1);
        assert_eq!(detailed.len(), 2);
        assert_eq!(short[0].alias, detailed[0].alias);
        assert_eq!(detailed[1].alias, "b");
    }

    /// A kind with nothing of its own returns nothing, rather than inheriting
    /// a reading that would belong to another kind.
    #[test]
    fn a_kind_that_states_nothing_reads_nothing() {
        assert!(fields(&PLAIN, true).is_empty());
        assert!(PLAIN.source.is_empty());
    }
}