Skip to content

Instantly share code, notes, and snippets.

@singulared
Forked from dbrgn/state.rs
Created May 27, 2019 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save singulared/80e7e4c3fca25ff716de3f7828ea8359 to your computer and use it in GitHub Desktop.
Save singulared/80e7e4c3fca25ff716de3f7828ea8359 to your computer and use it in GitHub Desktop.
Custom Text based Diesel type for an enum
#[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