Skip to content

Instantly share code, notes, and snippets.

@dbrgn
Created April 3, 2017 14:49
Show Gist options
  • Save dbrgn/9e88f54e23b4640bb3641734277a85dd to your computer and use it in GitHub Desktop.
Save dbrgn/9e88f54e23b4640bb3641734277a85dd 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