Skip to content

How to use an optional custom type with Insertable? #3835

Answered by weiznich
ISibboI asked this question in Q&A
Discussion options

You must be logged in to vote

The following code works for me:

use diesel::prelude::*;

table! {
    users(name) {
        name -> Text,
        password_hash -> Nullable<Text>,
    }
}

#[derive(Insertable, Clone, Debug)]
#[diesel(table_name = users)]
#[diesel(primary_key(name))]
#[diesel(check_for_backend(diesel::pg::Pg))]
#[diesel(treat_none_as_default_value = false)]
pub struct User {
    #[diesel(serialize_as = String)]
    pub name: UserName,
    #[diesel(serialize_as = Option<String>)]
    pub password_hash: PasswordHash,
}

#[derive(Clone, Debug)]
pub struct UserName(String);

impl From<String> for UserName {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<UserName> for String {
    fn

Replies: 4 comments 3 replies

Comment options

You must be logged in to vote
1 reply
@ISibboI
Comment options

Answer selected by ISibboI
Comment options

You must be logged in to vote
1 reply
@Ten0
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@weiznich
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
5 participants