Sunday, December 10, 2017

Diesel: How To have struct fields named differently than their columns

Diesel is very good at generating code that reduces the amount of boilerplate you have to write. You can explicitly ask something like
.filter(email.like(""))
and it will know how to filter based on the 'email' column, and how to populate a struct based on this.

For some reason, this falls apart when you're trying to derive the  Insertable trait.

The solution is hidden away in the API documentation, which is currently at this link.

The Solution
So, you just have to set up mappings between your struct fields and your database column in order to insert your struct as a record. Here's an example:

table:
Create Table User(EmailAddress text primary key not null, Name text not null)

struct:

#[derive(Queryable, Insertable)]
#[table_name="User"]
pub struct User {
   
    #[column_name(EmailAddress)]
    pub address: String,

    #[column_name(Name)]
    pub name: String
}

There aren't supposed to be quotes around the column names, as it's using the diesel-generated helper structures. As such, you have to make sure that your schema is imported for this to properly work.