Created
April 3, 2017 14:49
Custom Text based Diesel type for an enum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] | |
#[serde(rename_all="snake_case")] | |
pub enum State { | |
Pending, | |
Sending, | |
Sent, | |
Failed, | |
} | |
impl fmt::Display for State { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "{}", match *self { | |
State::Pending => "pending", | |
State::Sending => "sending", | |
State::Sent => "sent", | |
State::Failed => "failed", | |
}) | |
} | |
} | |
impl FromSqlRow<Text, Pg> for State { | |
fn build_from_row<R: Row<Pg>>(row: &mut R) -> Result<Self, Box<Error+Send+Sync>> { | |
match String::build_from_row(row)?.as_ref() { | |
"pending" => Ok(State::Pending), | |
"sending" => Ok(State::Sending), | |
"sent" => Ok(State::Sent), | |
"failed" => Ok(State::Failed), | |
v => Err(format!("Unknown value {} for State found", v).into()), | |
} | |
} | |
} | |
impl AsExpression<Text> for State { | |
type Expression = AsExprOf<String, Text>; | |
fn as_expression(self) -> Self::Expression { | |
<String as AsExpression<Text>>::as_expression(self.to_string()) | |
} | |
} | |
impl<'a> AsExpression<Text> for &'a State { | |
type Expression = AsExprOf<String, Text>; | |
fn as_expression(self) -> Self::Expression { | |
<String as AsExpression<Text>>::as_expression(self.to_string()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment