rustrust-dieselrust-diesel-mysql

Rust how to implement diesel::Insertable<table>


I'm trying to implement the trait diesel::Insertable<table in Rust.

In mail.rs

    diesel::insert_into(mailing_list).values(
         email // This is a String
        ).execute(connection);

This is because the following code results in this error:

error[E0277]: the trait bound `std::string::String: diesel::Insertable<table>` is not satisfied
   --> src/mail.rs:18:10
    |
17  |     diesel::insert_into(mailing_list).values(
    |                                       ------ required by a bound introduced by this call
18  |          email
    |          ^^^^^ the trait `diesel::Insertable<table>` is not implemented for `std::string::String`

Looking a bit more at the documentation from Diesel, I believe that I should make myself a struct that derives Insertable

In models.rs

 #[derive(Insertable)]
 pub struct NewSubscriber {
     pub email: String
}

But then I get

but im getting this error
error[E0433]: failed to resolve: use of undeclared crate or module `new_subscribers`
  --> src/models.rs:13:12
   |
13 | pub struct NewSubscriber {
   |            ^^^^^^^^^^^^^ use of undeclared crate or module `new_subscribers`

I'm so confused why the compiler says it can't find a crate or module with a struct that I'm trying to define.


Solution

  • From the documentation on the Insertable derive macro:

    To implement Insertable this derive needs to know the corresponding table type. By default it uses the snake_case type name with an added s from the current scope. It is possible to change this default by using #[diesel(table_name = something)].

    So you need to define a "new_subscribers" table using table!. If you've already done so make sure you import it into scope, or if you already have a table and its in scope but with a different name, add the above attribute.

    Judging by your insert statement, it looks like the table you're inserting into is mailing_list so use the last option:

    #[derive(Insertable)]
    #[diesel(table_name = mailing_list)]
    pub struct NewSubscriber {
        pub email: String
    }