rustmysql-connector

How to extract NaiveDate and NaiveTime values from mySQL results in Rust?


I'm interating over results from mySQL query to generate an array of JSON objects, but some data types need to be serializable.

I've tried just extract the values explicitly by setting NaiveDate and NaiveTime, but I get this error:

Trait `FromValue` is not implemented for `NaiveDate` [E0277]

this is actually the code:

let results: Vec<Row> = conn.exec(
        &stmt,
        params! {
            "date" => date
        },
    )?;
    let mut events = Vec::new();
    // Convert the result into a String
    for row in results {
        // FIXME: retornar date e time corretamente

        let event = json!({
            "event_id": row.get::<String, _>("event_uuid").unwrap_or_default(),
            "date": row.get::<NaiveDate, _>("date").unwrap_or_default(),
            "time": row.get::<NaiveTime, _>("time").unwrap_or_default(),
        }
        );
        events.push(event)
    }

Solution

  • Assuming these are mysql::Row objects...

    mysql::Row::get requires the type implements mysql::prelude::FromValue to convert from the MySQL value to the type. The mysql crate implements this for many types, but not NativeDate nor NativeTime.

    Fortunately mysql_common does implement FromValue for chrono types. Use mysql_common and turn on chrono support.

    [dependencies.mysql_common]
    features = ["chrono"]