rusttypesrust-sqlx

What data type to use in Rust to match Decimal in MySQL


In MySQL, I have a table My_Table with a column price decimal(20,10)

Using sqlx, I want to query and extract the value from MySQL into my function.

Below are the relevant code

    let query = format!("select price from My_Table");
    let query_result = sqlx::query(&query)
        .fetch_all(&pool)
        .await
        .expect("Failed to execute query");

    for row in query_result {
        let price: Decimal = row.get("price");
    }


This is what I have in Cargo.toml

[dependencies]
sqlx = { version = "0.7", features = [ "runtime-tokio", "mysql", "chrono"] }
sqlx-core = "0.7.0"

sqlx-mysql = { version = "0.7.1", features = ["bigdecimal"] }

mysql = "24.0.0"

tokio = { version = "1.32.0", features = ["full"] }

chrono = { version = "0.4.10", features = ["serde"] }

bigdecimal = { version = "0.4.1", features = ["serde"] }

decimal = { version = "2.1.0", features = ["serde"] }

rust_decimal= "1.31.0" 

futures-util = "0.3.1"

I am getting this error

let price: Decimal = row.get("price");
   |                     ^^^ the trait `sqlx::Decode<'_, MySql>` is not implemented for `Decimal`

I've tried use bigdecimal::BigDecimal;, use rust_decimal::Decimal; as suggested here and others, none of them works.

I am able to query for columns with data types: varchar, datetime, int etc... It is only Decimal that is giving me headaches


Solution

  • If you want to use bigdecimal (respectively, rust_decimal) with sqlx_mysql, you need to enable the feature flag bigdecimal (resp. decimal) of sqlx_mysql.

    To do so, you need to change your Cargo.toml as follows. Assuming your entry for sqlx_mysql looks like

    sqlx-mysql = "x.y.z"
    

    you need to turn it into

    sqlx-mysql = { version = "x.y.z", features = ["bigdecimal"] }
    

    (or, respectively:

    sqlx-mysql = { version = "x.y.z", features = ["decimal"] }
    

    )