Problem with ToSql implementation for custom enum in Diesel

Good morning,

I'm working on a Rust project using Diesel to interact with a PostgreSQL database, and I'm trying to implement the ToSql interface for a custom UserRole enum that represents different user roles in my application. My goal is to convert these roles to text when inserting into the database.

Here is my current code:

/**
 * UserRole enum
 * enum pour les rôles des utilisateurs
 * trainer: formateur
 * student: étudiant
 * autoriser la conversion de UserRole en Text pour la base de données
 */
impl<DB: diesel::backend::Backend> ToSql<Text, DB> for UserRole {
    fn to_sql<W: std::io::Write>(&self, out: &mut diesel::serialize::Output<W, DB>) -> diesel::serialize::Result {
        match *self {
            UserRole::Trainer => out.write_all(b"trainer".as_ref())?,
            UserRole::Student => out.write_all(b"student".as_ref())?,
        }
        Ok(diesel::serialize::IsNull::No)
    }
}

However, when I compile my code, I receive the following error:

[E0599] no method named `write_all` found for mutable reference `&mut diesel::serialize::Output<'_, '_, W>` in the current scope. 
[Note] method not found in `&mut Output<'_, '_, W>`

It seems that I cannot use write_all on the Output object provided by Diesel. I searched the Diesel documentation but couldn't find any clear examples on how to correctly write data into this Output object for an enum.

Can anyone tell me what I'm doing wrong or suggest a correct way to implement ToSql for my UserRole enum? Any help or pointers to relevant resources would be greatly appreciated.

Thank you in advance for your help.

write_all is a trait method. trait methods can only be used when their trait is in scope.

try adding use std::io::Write; to the top of your source file.

2 Likes

Thank you for posting the code and error with proper quoting, that helps!

However, if you look at the full error you should see something near the bottom mentioning that traits for trait methods must be in scope. And it may mention the specific trait that you need to use to bring it into scope. Please do always post the full error from running cargo build or cargo check in the terminal.

2 Likes

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.