Skip to content

Instantly share code, notes, and snippets.

@ivanovaleksey
Last active March 19, 2018 11:25
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 ivanovaleksey/bac64f6dded5704771ed937644e8fc4b to your computer and use it in GitHub Desktop.
Save ivanovaleksey/bac64f6dded5704771ed937644e8fc4b to your computer and use it in GitHub Desktop.
Enum with integer in DB
use uuid::Uuid;
use models::{Agent, Room};
use schema::room_agent;
#[derive(Associations, Queryable, Debug)]
#[table_name = "room_agent"]
#[belongs_to(Agent)]
#[belongs_to(Room)]
pub struct RoomAgent {
pub id: Uuid,
pub agent_id: Uuid,
pub room_id: Uuid,
pub state: State,
}
#[derive(Insertable, Debug)]
#[table_name = "room_agent"]
pub struct NewRoomAgent {
pub agent_id: Uuid,
pub room_id: Uuid,
pub state: State,
}
impl NewRoomAgent {
pub fn new(agent_id: Uuid, room_id: Uuid) -> NewRoomAgent {
NewRoomAgent {
agent_id,
room_id,
state: State::Pending,
}
}
}
#[derive(AsExpression, FromSqlRow, Copy, Clone, Debug)]
#[sql_type = "Int4"]
#[repr(u32)]
pub enum State {
Pending = 0,
Active = 1,
}
use diesel::deserialize::{self, FromSql};
use diesel::pg::Pg;
use diesel::sql_types::{Int4, Integer};
impl FromSql<Integer, Pg> for State {
fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
match <i32 as FromSql<Integer, Pg>>::from_sql(bytes)? {
0 => Ok(State::Pending),
1 => Ok(State::Active),
n => Err(format!("unknown kind: {}", n).into()),
}
}
}
use diesel::serialize::{self, Output, ToSql};
use std::io::Write;
impl ToSql<Integer, Pg> for State {
fn to_sql<W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result {
let x = *self as i32;
ToSql::<Int4, Pg>::to_sql(&x, out)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment