mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The contract one command publishes about itself.
//!
//! Split out of the self-description module when that module went past the
//! ceiling this project holds every file to. The cut is where the seam already
//! was: `meta.rs` decides *which* command is being asked about, and this decides
//! *what is said* about it — its inputs, its effect, the failures it can travel
//! in and the envelope that carries the answer.

use serde_json::{json, Value};

/// What one command accepts, read from the argument layer itself.
///
/// FR-053 promises inputs, and the contract carried none: a caller asking what
/// a command takes was told the shape of the envelope and nothing about the
/// command. So the arguments are read from the same tree `clap` builds the
/// parser from, never from a list written beside it, because a list written
/// beside it is a list that parts company with the parser.
///
/// The invocation-wide flags are left out on purpose. They belong to every
/// command equally and are published once, under `meta commands --with-globals`.
/// Repeating them under all sixty-three would bury the handful that actually
/// distinguish one command from another.
#[must_use]
pub fn inputs_of(root: &clap::Command, wanted: &str) -> Value {
    let Some(leaf) = leaf_of(root, wanted) else {
        return Value::Array(Vec::new());
    };

    let mut inputs: Vec<Value> = leaf
        .get_arguments()
        .filter(|arg| !arg.is_global_set())
        .map(|arg| {
            let positional = arg.is_positional();
            json!({
                "name": arg.get_long().unwrap_or_else(|| arg.get_id().as_str()),
                "kind": if positional {
                    "positional"
                } else if matches!(
                    arg.get_action(),
                    clap::ArgAction::Set | clap::ArgAction::Append
                ) {
                    // Read from the action rather than from the count of
                    // values: the count is left unset on an ordinary option, so
                    // asking it called `--param` a switch when it carries the
                    // value a statement is bound to.
                    "option"
                } else {
                    "flag"
                },
                "required": arg.is_required_set(),
                "repeats": matches!(arg.get_action(), clap::ArgAction::Append),
                "about": arg.get_help().map(ToString::to_string).unwrap_or_default(),
            })
        })
        .collect();
    inputs.sort_by(|left, right| left["name"].as_str().cmp(&right["name"].as_str()));
    Value::Array(inputs)
}

/// The published command a full name points at, or nothing when there is none.
#[must_use]
pub fn leaf_of<'tree>(root: &'tree clap::Command, wanted: &str) -> Option<&'tree clap::Command> {
    let mut here = root;
    for step in wanted.split(' ') {
        here = here.get_subcommands().find(|sub| sub.get_name() == step)?;
    }
    Some(here)
}

/// What each served leaf can do to the world beyond this process.
///
/// FR-053 promises effects, and this is the one part of that promise the
/// argument layer cannot answer: whether a command changes anything is decided
/// by what it sends, not by what it accepts.
///
/// So it is written here, by hand — and a hand-written list is exactly what
/// rots. What keeps this one from rotting quietly is that a proof holds it to
/// the same names and the same length as [`super::SERVED_LEAVES`], so a command
/// added to the build cannot arrive here missing. The list can still be wrong
/// about one command; it can no longer be silent about one.
///
/// `may_change` is the honest word for the statement families: `query run` with
/// a reading statement changes nothing, but the command is the one through
/// which a change travels, and a caller deciding whether to allow it needs the
/// worst case rather than the common one.
const EFFECTS: &[(&str, &str)] = &[
    ("config doctor", "local"),
    ("config get", "local"),
    ("config list", "local"),
    ("config path", "local"),
    ("config set", "local"),
    ("config unset", "local"),
    ("conn add", "local"),
    ("conn default", "local"),
    ("conn edit", "local"),
    ("conn list", "local"),
    ("conn remove", "local"),
    ("conn show", "local"),
    ("conn test", "reads"),
    ("data export", "reads"),
    ("data import", "may_change"),
    ("history as-of", "reads"),
    ("history between", "reads"),
    ("history tables", "reads"),
    ("meta commands", "local"),
    ("meta completions", "local"),
    ("meta manual", "local"),
    ("meta schema", "local"),
    ("meta version", "local"),
    ("query analyze", "reads"),
    ("query call", "may_change"),
    ("query explain", "reads"),
    ("query file", "may_change"),
    ("query lineage", "local"),
    ("query named list", "local"),
    ("query named remove", "local"),
    ("query named run", "may_change"),
    ("query named save", "local"),
    ("query plan", "reads"),
    ("query run", "may_change"),
    ("query sample", "reads"),
    ("query tx", "may_change"),
    ("schema columns", "reads"),
    ("schema checks", "reads"),
    ("schema count", "reads"),
    ("schema databases", "reads"),
    ("schema ddl", "reads"),
    ("schema events", "reads"),
    ("schema grants", "reads"),
    ("schema indexes", "reads"),
    ("schema keys", "reads"),
    ("schema map", "reads"),
    ("schema partitions", "reads"),
    ("schema routines", "reads"),
    ("schema search", "reads"),
    ("schema sequences", "reads"),
    ("schema size", "reads"),
    ("schema stats", "reads"),
    ("schema tables", "reads"),
    ("schema triggers", "reads"),
    ("schema views", "reads"),
    ("server capabilities", "reads"),
    ("server kill", "may_change"),
    ("server locks", "reads"),
    ("server processes", "reads"),
    ("server queries", "reads"),
    ("server replica", "reads"),
    ("server status", "reads"),
    ("server variables", "reads"),
];

/// The effect published for one command, in the closed set of three words.
///
/// Published so a caller can decide before invoking rather than after: `local`
/// touches only this host, `reads` reaches the server and leaves it as it was,
/// and `may_change` is the door a change can travel through.
#[must_use]
pub fn effect_of(command: &str) -> &'static str {
    EFFECTS
        .iter()
        .find(|(name, _)| *name == command)
        .map_or("unpublished", |(_, effect)| *effect)
}

mod payload;

// Re-exported so a caller asks the contract about a command in one place,
// whichever of the two files happens to hold the answer. The split is about
// where the source sits, and a split that leaked into every call site would
// have been a worse trade than the ceiling it was made to respect.
pub use payload::{
    commands_whose_data_varies, commands_with_published_data, conditional_fields, data_shape_of,
    field_is_conditional,
};

/// The failure contract: the shape one travels in, and the closed category set.
///
/// The fields of a command's answer that carry the absence marker.
///
/// A field named here answers with the absence marker when the object has
/// nothing to give, and never with empty text. The two are different answers:
/// empty text is what somebody wrote, absence is that nobody wrote anything,
/// and a catalogue that keeps both as the empty string loses the difference
/// unless it is made before the answer leaves.
///
/// Published so a caller can be told which fields carry the distinction without
/// having to find a case of each and compare.
///
/// The two `conn` entries were missing until a generated schema met a live
/// answer: `conn list` emits `default` as the absence marker when no profile is
/// the default, while the contract typed it as text. A parser written from the
/// published contract would have said `String` and met a null on its first run
/// against a fresh configuration.
const MARKS_ABSENCE: &[(&str, &[&str])] = &[
    ("conn list", &["default"]),
    ("conn remove", &["default"]),
    ("schema tables", &["comment"]),
    ("schema views", &["comment"]),
    ("schema indexes", &["comment"]),
    ("schema routines", &["comment"]),
];

/// The fields this command marks absence in, empty when it marks none.
///
/// Lives beside the rest of the contract rather than beside the command that
/// prints it, because this is the same kind of question as [`failure_shape`]
/// and [`envelope_shape`]: what the contract of a command says, asked once and
/// answered from one place.
#[must_use]
pub fn marks_absence(command: &str) -> &'static [&'static str] {
    MARKS_ABSENCE
        .iter()
        .find(|(name, _)| *name == command)
        .map_or(&[], |(_, fields)| *fields)
}

/// FR-053 promises failures, and the contract carried none of them either. Two
/// things can be published without a copy that drifts: the fields a failure is
/// written with, and the closed table of categories with the number and the
/// repeat mark each carries. The second is read from [`crate::error::Category::ALL`], so it
/// cannot fall behind the code. The first is written here and held to the real
/// envelope by a proof that causes a failure rather than describing one.
///
/// What is deliberately absent is which of the thirteen a given command can
/// reach. That would be a sixty-three by thirteen table nobody could keep true,
/// and a table that is false is worse than a limit that is stated. So the limit
/// is stated, in the answer itself, where a caller reads it.
#[must_use]
pub fn failure_shape() -> Value {
    use crate::error::Category;

    let categories: Vec<Value> = Category::ALL
        .iter()
        .map(|category| {
            json!({
                "category": category.as_str(),
                "exit": category.exit_number().code(),
                "retryable": category.is_retryable(),
            })
        })
        .collect();

    json!({
        "channel": "the auxiliary channel; the primary channel carries data only",
        "shape": {
            "category": "string, one of the thirteen below, and the field to branch on",
            "code": "string, stable identifier, finer than the category",
            "message": "string, prose for a person, in the reader's language",
            "hint": "string, present only when a concrete next action exists",
            "retryable": "boolean, whether repeating unchanged may succeed",
            "exit": "number, the exit number this failure produces",
            "causes": "array of strings, present only when a dependency explained itself",

            "conditions": "array of strings, present only when the server reported more than one",
        },
        "causes_are_diagnosis_only": "each entry is another library's own sentence, kept verbatim, \
             so it stays in the language of its origin and is never branched on",
        "categories": categories,
        "declared_limit": "which of these categories this command can reach is not published \
             per command; the closed set above is what any command may answer with",
    })
}

/// The shape every answer of this product travels in.
///
/// Written once, because the contract of a group and the contract of a leaf
/// describe the same envelope and must never drift apart.
///
/// A field the product emits and this shape omits is worse than an undocumented
/// one: a reader who trusts the contract concludes the field cannot appear. The
/// destination was emitted for a while without being named here, so a caller
/// following the contract had no way to learn that the answer names where it
/// went — which is the whole point of FR-143.
#[must_use]
pub fn envelope_shape() -> Value {
    json!({
        "command": "string",
        "schema_version": "number",
        "target_resolved": "object, the destination this answer was served from",
        "target_source": "string, how that destination was chosen: `argv` when the call named \
             a profile, `dsn` when the call carried the whole destination, `config` when it \
             was inherited from the stored default; a change refuses to run on an inherited \
             destination unless `conn.require_explicit_target` is turned off",
        "data": "object, the answer of this command; its fields are described under `data` in \
             the contract of the command itself, which either names them or states there that \
             this build does not describe them",
        "gaps": "array, present only when something was not delivered",
        "applied": "object, present only when the output pipeline acted",
        "checksum": "string, present only when a signature was asked for",
        "closing_record": closing_record_shape(),
    })
}

/// The record that closes a continuous flow, and what it lets a reader decide.
///
/// FR-132 asks a reader to tell a whole set from a cut one by whether this
/// record arrived. That is only a contract if the reader can learn its name
/// without reading this source, so the name is published rather than left to be
/// discovered.
///
/// It is published as one conditional entry of the envelope rather than against
/// a list of the commands that can stream. Such a list would be a second copy
/// of a decision the dispatch already makes, and the two copies would part
/// company the first time a command gained or lost a flow. The envelope already
/// carries fields that appear only in some answers, so a conditional entry is
/// the convention here and not an exception to it.
fn closing_record_shape() -> Value {
    use crate::output::format::{END_OF_STREAM_KEY, GAPS_KEY, ROW_COUNT_KEY};
    json!({
        "when": "the last record of a continuous flow, and absent when the flow was cut",
        (END_OF_STREAM_KEY): "true, the mark that the set ended on its own",
        (ROW_COUNT_KEY): "number, the rows this flow emitted",
        (GAPS_KEY): "array, present only when something was left out",
    })
}