mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! One row test, parsed from `key=value`, `key!=value` or `key~substring`.

use super::value::{lookup, lookup_row, scalar_text};
use crate::error::{Failure, Result};
use crate::output::envelope::Row;
use serde_json::Value;

/// One `key=value`, `key!=value` or `key~substring` test.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Filter {
    path: String,
    operator: Operator,
    operand: String,
}

/// How a filter compares.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Operator {
    /// Exact match.
    Equals,
    /// Anything but an exact match.
    Differs,
    /// The operand occurs somewhere in the value.
    Contains,
}

impl Filter {
    /// Parses one filter expression.
    ///
    /// The three forms are `key=value`, `key!=value` and `key~substring`.
    /// `==` is accepted as a synonym of `=`.
    ///
    /// # Errors
    ///
    /// Returns a usage failure when the expression has no recognised operator
    /// or an empty key. A malformed expression is refused rather than silently
    /// matching nothing, so a typo never looks like an empty result.
    pub fn parse(expression: &str) -> Result<Self> {
        const NO_OPERATOR: &str = "filter.no_operator";
        const EMPTY_KEY: &str = "filter.empty_key";

        // `!=` and `~` are tested before `=` so `a!=b` never parses as `a! = b`.
        let (path, operator, operand) = if let Some((left, right)) = expression.split_once("!=") {
            (left, Operator::Differs, right)
        } else if let Some((left, right)) = expression.split_once('~') {
            (left, Operator::Contains, right)
        } else if let Some((left, right)) = expression.split_once("==") {
            (left, Operator::Equals, right)
        } else if let Some((left, right)) = expression.split_once('=') {
            (left, Operator::Equals, right)
        } else {
            return Err(Failure::usage(
                NO_OPERATOR,
                format!("filter `{expression}` has no operator"),
            )
            .with_detail("detail", expression)
            .with_hint("use key=value, key!=value or key~substring"));
        };

        if path.is_empty() {
            return Err(Failure::usage(
                EMPTY_KEY,
                format!("filter `{expression}` has an empty key"),
            )
            .with_detail("detail", expression));
        }

        Ok(Self {
            path: path.to_owned(),
            operator,
            operand: operand.to_owned(),
        })
    }

    /// Whether this element passes the test.
    ///
    /// A missing field never matches, not even under `!=`: absence is not a
    /// value, so it cannot differ from one.
    pub(super) fn accepts(&self, element: &Value) -> bool {
        self.decide(lookup(element, &self.path))
    }

    /// Whether this arriving row passes the test.
    ///
    /// A row in flight is not a document, so it is tested through the same
    /// decision as a gathered one rather than being rebuilt into a document
    /// first: a row must not mean one thing gathered and another in flight.
    pub(super) fn accepts_row(&self, row: &Row) -> bool {
        self.decide(lookup_row(row, &self.path))
    }

    /// The one decision both shapes of the same test share.
    fn decide(&self, found: Option<&Value>) -> bool {
        let Some(found) = found else {
            return false;
        };
        let text = scalar_text(found);
        match self.operator {
            Operator::Equals => text == self.operand,
            Operator::Differs => text != self.operand,
            Operator::Contains => text.contains(&self.operand),
        }
    }
}

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

    #[test]
    fn a_malformed_filter_fails_instead_of_matching_nothing() {
        let failure = Filter::parse("no-operator-here").expect_err("must refuse");
        assert_eq!(failure.category(), crate::error::Category::Usage);
    }

    #[test]
    fn a_missing_field_never_matches_not_even_under_differs() {
        let filter = Filter::parse("absent!=anything").expect("parses");
        assert!(!filter.accepts(&json!({"name": "alpha"})));
    }
}