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.

3 comments:

  1. If there is anyone who is not able to understand why some type of technical issues are coming up in Hotmail, then bank on 0800-029-4639. In the market there is no one who can actually transfer good quality of work then don’t panic and refer the experts. Other sources or professionals belonging to other sources do not have the expert knowledge like Hotmail Professionals do possess. Over the years countless times measures are being undertaken for precision being maintained and this is what is raising the bar of efficiency provided by experts of Hotmail.
    Hotmail Help Number UK

    ReplyDelete
  2. The craze that Ferrari has among youngsters is unimaginable. If you want to make a statement among your friends with amazing Ferrari, then get in touch with VIP car rentals. At VIP car rentals we provide Ferrari car rental Dubai. Do not worry about the price because all our products are provided at a cheap price.

    ReplyDelete