Skip to content

Instantly share code, notes, and snippets.

@Wassasin
Last active May 1, 2019 15:08
Show Gist options
  • Save Wassasin/cc987c8945ce5f63c9604a1f3cd584c4 to your computer and use it in GitHub Desktop.
Save Wassasin/cc987c8945ce5f63c9604a1f3cd584c4 to your computer and use it in GitHub Desktop.
Real API's code examples
derive_crud!(Message; NewMessage; messages);
fn try_find(
id: Id<$struct_name>,
connection: &PgConnection,
) -> Result<Option<$struct_name>, ::error::Error> {
let result = $schema::table
.filter($schema::id.eq(&id))
.first::<$struct_name>(connection);
match result {
Ok(obj) => Ok(Some(obj)),
Err(diesel::result::Error::NotFound) => Ok(None),
Err(e) => Err(e)
.context(format_err!(
"Was not able to read {}",
stringify!($struct_name)
))
.context(::error::ErrorKind::DatabaseError)
.map_err(|err| err.into()),
}
}
pub trait CRUD: Sized {
type NewEntity;
fn create(obj: &Self::NewEntity, connection: &PgConnection) -> Result<Id<Self>, Error>;
fn create_promote(obj: Self::NewEntity, connection: &PgConnection) -> Result<Self, Error>;
fn try_find(id: Id<Self>, connection: &PgConnection) -> Result<Option<Self>, Error>;
fn find(id: Id<Self>, connection: &PgConnection) -> Result<Self, Error>;
fn read(connection: &PgConnection) -> Result<Vec<Self>, Error>;
fn update(obj: &Self, connection: &PgConnection) -> Result<usize, Error>;
fn delete(id: &Id<Self>, connection: &PgConnection) -> Result<usize, Error>;
}
#[derive(FromSqlRow, AsExpression, PartialEq, Eq)]
#[sql_type = "Integer"]
pub struct Id<T>(i32, PhantomData<T>);
#[derive(Queryable, AsChangeset, Debug, Clone, PartialEq, Serialize, Deserialize, TypeName)]
#[table_name=messages]
pub struct Message {
id: Id<Message>,
timestamp: NaiveDateTime,
tag: String,
blob: JsonValue
}
#[derive(Queryable, Insertable, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[table_name=messages]
pub struct NewMessage {
timestamp: NaiveDateTime,
tag: String,
blob: JsonValue
}
build_model!(Message; NewMessage; "messages" => {
timestamp: NaiveDateTime,
tag: String,
blob: JsonValue
});
table! {
use diesel::sql_types::{Serial, Nullable, Integer, Varchar, Timestamp};
events (id) {
id -> Serial,
source_id -> Nullable<Integer>,
timestamp -> Timestamp,
subject -> Varchar,
origin -> Varchar,
concerns -> Varchar,
summary -> Varchar,
url -> Nullable<Varchar>,
}
}
joinable!(events -> messages (source_id));
table! {
use diesel::sql_types::{Serial, Varchar, Timestamp, Json};
messages (id) {
id -> Serial,
timestamp -> Timestamp,
tag -> Varchar,
blob -> Json,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment