Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a trait not implemented for an optional field in Diesel struct

I have this struct:

#[table_name = "clients"]
#[derive(Serialize, Deserialize, Queryable, Insertable, Identifiable, Associations)]
pub struct Client {
    pub id: Option<i64>,
    pub name: String,
    pub rank: Option<i64>,
}

and the following implementation:

impl Client {
    pub fn get(name: String, connection: &PgConnection) -> Option<Self> {
        match clients::table
            .filter(clients::name.eq(&name))
            .limit(1)
            .load::<Client>(connection)
        {
            Ok(clients) => Some(clients[0]),
            Err(_) => None,
        }
    }
}

which gives me the following error:

.load::<Client>(connection) {                                                                                   
 ^^^^ the trait `diesel::Queryable<diesel::sql_types::BigInt, _>` is not implemented for `std::option::Option<i64>`
like image 711
Lev Avatar asked Mar 05 '23 05:03

Lev


1 Answers

Your error message says that you cannot query a BigInt (a 64 bits int) into an Option<i64>. That is because you forgot to say that id is nullable in your table declaration. It must look like:

table! {
    clients {
        id -> Nullable<BigInt>,
        name -> Text,
        rank -> Nullable<BigInt>,
    }
}

You can see the implementation of Queryable you are looking for in the documentation.

like image 193
Boiethios Avatar answered Mar 12 '23 15:03

Boiethios