fv-connect 0.1.0

FusionVault Conduit: read relational, file and REST sources into rows with mandatory access control pushed into the read, write results back with atomic promotion, and drive incremental base-ingest scans, changelogs and label normalisation checked against the published conformance vectors.
Documentation
//! MySQL source reads — same MAC-pushdown pattern as Postgres, via
//! `mysql_async` (pure Rust, no native TLS/openssl for a local plaintext connection).

use fv_mac::{where_sql, Bindings, Taxonomy};
use fv_value::Value;
use mysql_async::prelude::*;
use mysql_async::Value as MyValue;

use crate::{ConnectError, Row};

/// Read `table` from MySQL with the MAC filter pushed into the query (DOMINANCE `col<=n` is valid
/// MySQL as-is; array axes would need MySQL JSON functions — see the Postgres note).
pub async fn read_mysql_with_mac(
    url: &str,
    table: &str,
    taxonomy: &Taxonomy,
    grants: &Bindings,
    label_column: impl Fn(&str) -> String,
    limit: Option<usize>,
) -> Result<Vec<Row>, ConnectError> {
    let pool = mysql_async::Pool::new(url);
    let mut conn = pool
        .get_conn()
        .await
        .map_err(|e| ConnectError(format!("connect: {e}")))?;

    let predicate = where_sql(taxonomy, grants, &label_column);
    // MySQL quotes identifiers with backticks; `table` may be schema-qualified (`db`.`t`).
    let mut sql = format!("SELECT * FROM {} WHERE {predicate}", crate::ident::mysql_ident(table));
    if let Some(n) = limit {
        sql.push_str(&format!(" LIMIT {n}"));
    }

    let rows: Vec<mysql_async::Row> = conn
        .query(sql.clone())
        .await
        .map_err(|e| ConnectError(format!("query `{sql}`: {e}")))?;
    drop(conn);
    let _ = pool.disconnect().await;

    let mut out = Vec::with_capacity(rows.len());
    for r in &rows {
        let cols = r.columns_ref();
        let mut row: Row = Vec::with_capacity(cols.len());
        for (i, col) in cols.iter().enumerate() {
            row.push((col.name_str().to_string(), cell(r.as_ref(i), col.column_type())));
        }
        out.push(row);
    }
    Ok(out)
}

/// True for MySQL numeric column types. IMPORTANT: the text protocol (`query`) returns EVERY value as
/// `Bytes`, so a numeric column would otherwise decode as a string and break `>=`/`<` in the value
/// dialect (a string-vs-number type error). We type-cast bytes by the column's declared type.
fn is_numeric(ct: mysql_async::consts::ColumnType) -> bool {
    use mysql_async::consts::ColumnType::*;
    matches!(
        ct,
        MYSQL_TYPE_TINY
            | MYSQL_TYPE_SHORT
            | MYSQL_TYPE_LONG
            | MYSQL_TYPE_LONGLONG
            | MYSQL_TYPE_INT24
            | MYSQL_TYPE_FLOAT
            | MYSQL_TYPE_DOUBLE
            | MYSQL_TYPE_DECIMAL
            | MYSQL_TYPE_NEWDECIMAL
            | MYSQL_TYPE_YEAR
    )
}

fn cell(v: Option<&MyValue>, ct: mysql_async::consts::ColumnType) -> Value {
    match v {
        None | Some(MyValue::NULL) => Value::Null,
        Some(MyValue::Int(n)) => Value::Num(*n as f64),
        Some(MyValue::UInt(n)) => Value::Num(*n as f64),
        Some(MyValue::Float(f)) => Value::Num(*f as f64),
        Some(MyValue::Double(f)) => Value::Num(*f),
        Some(MyValue::Bytes(b)) => {
            let s = String::from_utf8_lossy(b);
            if is_numeric(ct) {
                s.trim()
                    .parse::<f64>()
                    .map(Value::Num)
                    .unwrap_or_else(|_| Value::Str(s.into_owned()))
            } else {
                Value::Str(s.into_owned())
            }
        }
        // Date / Time → their string form (matches how the reference runner treats them as text)
        Some(other) => Value::Str(other.as_sql(true).to_string().trim_matches('\'').to_string()),
    }
}