Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created January 28, 2020 20:37
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 rust-play/7fa89c49724e36465ec9017de8bddce5 to your computer and use it in GitHub Desktop.
Save rust-play/7fa89c49724e36465ec9017de8bddce5 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::io::Write;
use diesel::backend::Backend;
use diesel::deserialize::FromSql;
use diesel::expression::helper_types::AsExprOf;
use diesel::expression::AsExpression;
use diesel::serialize::{Output, ToSql};
use diesel::sql_types::SmallInt;
use diesel::{deserialize, serialize};
use crate::schema::show;
pub type ShowId = i64;
#[repr(i16)]
#[derive(Clone, Copy, Debug, Deserialize, FromSqlRow, PartialEq, Serialize)]
pub enum PublicationStatus {
Ongoing,
Completed,
Cancelled,
Hiatus,
}
impl AsExpression<SmallInt> for PublicationStatus {
type Expression = AsExprOf<i16, SmallInt>;
fn as_expression(self) -> Self::Expression {
<i16 as AsExpression<SmallInt>>::as_expression(self as i16)
}
}
impl<DB> FromSql<SmallInt, DB> for PublicationStatus
where
DB: Backend,
i16: FromSql<SmallInt, DB>,
{
fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
match i16::from_sql(bytes)? {
0 => Ok(PublicationStatus::Ongoing),
1 => Ok(PublicationStatus::Completed),
2 => Ok(PublicationStatus::Cancelled),
3 => Ok(PublicationStatus::Hiatus),
x => Err(format!("Unrecognized variant {}", x).into()),
}
}
}
impl<DB> ToSql<SmallInt, DB> for PublicationStatus
where
DB: Backend,
i16: ToSql<SmallInt, DB>,
{
fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
(*self as i16).to_sql(out)
}
}
#[derive(Identifiable, Insertable, Queryable, Serialize, Deserialize)]
#[table_name = "shows"]
pub struct Show {
pub id: ShowId,
pub author: String,
pub description: String,
pub favorite: bool,
pub source: String,
pub status: PublicationStatus,
pub title: String,
pub url: String,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment