mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Aligned plain text, the only shape meant for a person to read.
//!
//! Columns are padded so a reader's eye can follow them down the page. Padding
//! counts characters and never bytes, so an accented name lines up with a
//! plain one. A value is never shortened to fit: a wide value widens its row
//! rather than losing content, because a person reading a truncated value has
//! no way to tell it was truncated.
//!
//! In a continuous flow the widths come from the declared column names, since
//! the rows are not held back to be measured. A value wider than its name
//! pushes that row out; the rest of the page stays aligned.

use super::{emit_line, Formatter, END_OF_STREAM_KEY};
use crate::error::Result;
use crate::output::envelope::{Envelope, Row};
use serde_json::Value;
use std::io::Write;

/// The two spaces that separate one column from the next.
const GAP: &str = "  ";

/// What stands in for absence of value, in the language in force.
///
/// It was an English literal, four lines below the one that became
/// `table-no-rows` after a proof ran the product under `--lang pt-BR` and read
/// `(no rows)` back. That correction moved its neighbour and left this one
/// where it was, so a reader asking for Portuguese still met `(absent)` in
/// every empty cell of the one shape written for a person to read.
///
/// Read through the catalogue on each call rather than cached. This shape is
/// published as the one meant for a human, so the cost is bounded by what a
/// person reads; the shapes an agent consumes carry `null` and never reach
/// here.
fn absent() -> String {
    crate::i18n::report::prose(crate::i18n::report::TABLE_ABSENT, &[])
}

/// The aligned plain text shape.
#[derive(Debug, Default)]
pub struct Text {
    /// The widths a continuous flow pads to.
    widths: Vec<usize>,
}

impl Formatter for Text {
    fn name(&self) -> &'static str {
        "text"
    }

    fn write_envelope(&mut self, writer: &mut dyn Write, envelope: &Envelope) -> Result<()> {
        match envelope.payload_array_key().and_then(|key| {
            envelope
                .data
                .get(key)
                .and_then(Value::as_array)
                .map(|elements| (key, elements))
        }) {
            Some((_, elements)) => Self::write_table(writer, elements)?,
            None => write_fields(writer, &envelope.data)?,
        }
        for gap in &envelope.gaps {
            emit_line(
                writer,
                &crate::i18n::report::prose(
                    crate::i18n::report::ENVELOPE_GAP,
                    &[("object", &gap.object), ("cause", &gap.cause)],
                ),
            )?;
        }
        Ok(())
    }

    fn begin_stream(
        &mut self,
        writer: &mut dyn Write,
        _head: &Envelope,
        columns: &[String],
    ) -> Result<()> {
        self.widths = columns.iter().map(|name| name.chars().count()).collect();
        if columns.is_empty() {
            return Ok(());
        }
        emit_line(writer, &pad_row(columns, &self.widths))?;
        emit_line(writer, &rule(&self.widths))
    }

    fn write_row(&mut self, writer: &mut dyn Write, row: &Row, line: &mut String) -> Result<()> {
        let cells: Vec<String> = row.values().map(render).collect();
        line.clear();
        line.push_str(&pad_row(&cells, &self.widths));
        emit_line(writer, line)
    }

    fn end_stream(
        &mut self,
        writer: &mut dyn Write,
        tail: &Envelope,
        emitted: u64,
        gaps: &[crate::output::envelope::Gap],
        // The one shape a person reads names what it left out in prose, so the
        // pipeline's report arrives here as a sentence rather than as a field.
        applied: Option<&crate::output::envelope::Applied>,
    ) -> Result<()> {
        use std::fmt::Write as _;

        let mut closing = format!("{END_OF_STREAM_KEY}: {emitted} rows");
        // The shapes a program reads answer a cut set by withholding the record
        // that claims completeness. Withholding it from a person would leave
        // them with rows and no way to know the set stopped early, so this shape
        // says it instead. Silence reads as completeness to a reader either way;
        // the difference is only in what each reader can do about it.
        if applied.is_some_and(|applied| applied.output_truncated) {
            let _ = write!(closing, ", cut to fit the volume ceiling");
        }
        let causes = super::causes_of(gaps);
        if !causes.is_empty() {
            // Writing into a string cannot fail, so the outcome carries nothing
            // a caller could act on.
            let _ = write!(closing, ", gaps: {causes}");
        }
        // The one shape a person reads is also the one that used to leave a
        // reader with no idea which server the rows in front of them came from
        // (FR-143).
        if let Some(destination) = super::destination_of(tail) {
            let _ = write!(closing, ", destination: {destination}");
        }
        emit_line(writer, &format!("({closing})"))
    }
}

impl Text {
    /// Writes a set of rows as an aligned table.
    fn write_table(writer: &mut dyn Write, elements: &[Value]) -> Result<()> {
        let columns = super::column_names(elements);
        if columns.is_empty() {
            return emit_line(
                writer,
                &crate::i18n::report::prose(crate::i18n::report::TABLE_NO_ROWS, &[]),
            );
        }
        let cells: Vec<Vec<String>> = elements
            .iter()
            .map(|element| {
                columns
                    .iter()
                    .map(|name| render_at(element, name))
                    .collect()
            })
            .collect();

        let mut widths: Vec<usize> = columns.iter().map(|name| name.chars().count()).collect();
        for row in &cells {
            for (index, text) in row.iter().enumerate() {
                if let Some(width) = widths.get_mut(index) {
                    *width = (*width).max(text.chars().count());
                }
            }
        }

        emit_line(writer, &pad_row(&columns, &widths))?;
        emit_line(writer, &rule(&widths))?;
        for row in &cells {
            emit_line(writer, &pad_row(row, &widths))?;
        }
        Ok(())
    }
}

/// Writes a payload that carries no rows, one field per line.
fn write_fields(writer: &mut dyn Write, payload: &Value) -> Result<()> {
    let Some(fields) = payload.as_object() else {
        return emit_line(writer, &render(payload));
    };
    let width = fields
        .keys()
        .map(|name| name.chars().count())
        .max()
        .unwrap_or(0);
    for (name, value) in fields {
        let padding = " ".repeat(width.saturating_sub(name.chars().count()));
        emit_line(writer, &format!("{name}{padding}{GAP}{}", render(value)))?;
    }
    Ok(())
}

/// Pads each cell to its column width, never shortening one.
fn pad_row(cells: &[String], widths: &[usize]) -> String {
    let mut line = String::new();
    for (index, text) in cells.iter().enumerate() {
        if index > 0 {
            line.push_str(GAP);
        }
        line.push_str(text);
        let width = widths.get(index).copied().unwrap_or(0);
        let used = text.chars().count();
        if index + 1 < cells.len() && used < width {
            line.push_str(&" ".repeat(width - used));
        }
    }
    line
}

/// The line that separates the names from the rows.
fn rule(widths: &[usize]) -> String {
    widths
        .iter()
        .map(|width| "-".repeat(*width))
        .collect::<Vec<String>>()
        .join(GAP)
}

/// Renders one field of one row.
fn render_at(element: &Value, name: &str) -> String {
    element.get(name).map_or_else(absent, render)
}

/// Renders one value for a person.
fn render(value: &Value) -> String {
    match value {
        Value::Null => absent(),
        Value::String(text) => text.clone(),
        other => other.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::super::tests::{
        bare_tail, sample_row, stream_through, stream_through_from, tail_from_a_destination,
    };
    use super::*;
    use serde_json::json;

    /// The shape a person reads says where the rows in front of them came from
    /// (FR-143).
    #[test]
    fn a_whole_flow_says_where_its_rows_came_from() {
        let rows = vec![sample_row("alpha", 1)];
        let text = stream_through_from(&mut Text::default(), &rows, &tail_from_a_destination());
        let last = text.lines().next_back().expect("a last line");
        assert_eq!(
            last,
            "(end_of_stream: 1 rows, destination: producao@192.0.2.10:3306/loja)"
        );
    }

    #[test]
    fn a_table_is_padded_so_the_columns_line_up() {
        let envelope = Envelope::new(
            "schema tables",
            json!({"rows": [
                {"name": "a", "engine": "InnoDB"},
                {"name": "much-longer", "engine": "Aria"}
            ]}),
        );
        let mut out = Vec::new();
        Text::default()
            .write_envelope(&mut out, &envelope)
            .expect("writes");
        let text = String::from_utf8(out).expect("utf8");
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines[0], "name         engine");
        assert_eq!(lines[2], "a            InnoDB");
        assert_eq!(lines[3], "much-longer  Aria");
    }

    #[test]
    fn padding_counts_characters_so_accents_still_line_up() {
        let envelope = Envelope::new(
            "query run",
            json!({"rows": [{"name": "ação", "n": 1}, {"name": "abcd", "n": 2}]}),
        );
        let mut out = Vec::new();
        Text::default()
            .write_envelope(&mut out, &envelope)
            .expect("writes");
        let text = String::from_utf8(out).expect("utf8");
        let lines: Vec<&str> = text.lines().collect();
        let first = lines[2].find('1').expect("value");
        let second = lines[3].find('2').expect("value");
        assert_eq!(
            lines[2][..first].chars().count(),
            lines[3][..second].chars().count(),
            "columns must line up by character and not by byte"
        );
    }

    #[test]
    fn a_wide_value_widens_its_row_rather_than_losing_content() {
        let long = "x".repeat(60);
        let mut out = Vec::new();
        let mut formatter = Text::default();
        formatter
            .begin_stream(
                &mut out,
                &bare_tail(),
                &["name".to_owned(), "size".to_owned()],
            )
            .expect("opens");
        let mut row = indexmap::IndexMap::new();
        row.insert("name".to_owned(), json!(long.clone()));
        row.insert("size".to_owned(), json!(1));
        let mut line = String::new();
        formatter
            .write_row(&mut out, &row, &mut line)
            .expect("writes");
        let text = String::from_utf8(out).expect("utf8");
        assert!(text.contains(&long), "no value may be shortened to fit");
    }

    #[test]
    fn absence_reads_differently_from_empty_text() {
        // Compared against the catalogue rather than against a literal, because
        // a literal here would pass in whichever language the catalogue happens
        // to be serving and so would say nothing about either.
        assert_eq!(render(&Value::Null), absent());
        assert_eq!(render(&json!("")), "");
        assert_ne!(render(&Value::Null), render(&json!("")));
        // The point of the marker: absence and empty text are different answers
        // and a reader must be able to tell them apart in any language.
        assert!(!absent().is_empty());
    }

    #[test]
    fn a_whole_flow_says_how_many_rows_it_carried() {
        let rows = vec![sample_row("alpha", 1), sample_row("beta", 2)];
        let text = stream_through(&mut Text::default(), &rows);
        let last = text.lines().next_back().expect("a last line");
        assert_eq!(last, "(end_of_stream: 2 rows)");
        assert!(!text.contains('\r'));
    }

    #[test]
    fn a_payload_with_no_rows_is_written_one_field_per_line() {
        let envelope = Envelope::new("meta version", json!({"version": "0.1.0", "tls": false}));
        let mut out = Vec::new();
        Text::default()
            .write_envelope(&mut out, &envelope)
            .expect("writes");
        let text = String::from_utf8(out).expect("utf8");
        assert!(text.contains("version  0.1.0"), "{text}");
        assert!(text.contains("tls      false"), "{text}");
    }
}