-1

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

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
Carlos
  • 19
  • 4

1 Answers1

1

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"] }

)

jthulhu
  • 7,223
  • 2
  • 16
  • 33
  • I've added `sqlx-mysql = { version = "0.7.1", features = ["bigdecimal"] }` as suggested, but I still see the same error when running – Carlos Aug 29 '23 at 07:06
  • @Carlos could you edit your question to include the whole `Cargo.toml` content? – jthulhu Aug 29 '23 at 07:22
  • added all the dependencies in the file in the question – Carlos Aug 29 '23 at 08:00
  • @Carlos with the `bigdecimal` feature, the type you get is `BigDecimal`, so you should do `let price: BigDecimal = row.get("price");`. I checked the source code and it should work. – jthulhu Aug 29 '23 at 09:04
  • 1
    It worked after adding bigdecimal to sqlx `sqlx = { version = "0.7", features = [ "runtime-tokio", "mysql", "chrono", "bigdecimal"] }` – Carlos Aug 30 '23 at 00:39