How to get db field with enum `std::option::Option` type?

Hi. I'm new in rust and I have a problem in retrieving data from the mysql DB with sqlx. I can get all records of table with this code:

let rows = sqlx::query!("SELECT * FROM api_options")
.fetch_all(&pool).await?; println!("{:?}", rows);

The output of above code is:

[Record { id: 1, key: "pick-up", option: Some("CNG and Gasolin"), year: "2019" }, Record { id: 2, key: "lx_basic", option: Some(""), year: "2018" }, .....]

The problem occurs when I want to get data with query_as! as below:

struct Object {id: i32, key: String, option: String, year: String};
let rows = sqlx::query_as!(Object, "SELECT * FROM api_options")

The problem is option field. Type of option in mysql is longtext. The output of above code is:

mismatched types
expected struct std::string::String, found enum std::option::Option

After getting this error I changed Object struct to this:

pub enum Option{
struct Object {id: i32, key: String, option: Option<String>, year: String};

After running above code I get this error:

error[E0277]: the trait bound main::{{closure}}#0::Option<std::string::String>: sqlx_core::decode::Decode<', sqlx_core::mysql::database::MySql> is not satisfied
the trait sqlx_core::decode::Decode<'
, sqlx_core::mysql::database::MySql> is not implemented for main::{{closure}}#0::Option<std::string::String>

What is the problem?

It looks like you defined your own Option type? Using the built-in one should work as expected.

1 Like

Thanks you for reply. I just remove Option enum and use built-in Option and it works. Actually I didn't know that there is built-in option :slightly_smiling_face:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.