This repository has been archived by the owner. It is now read-only.
Permalink
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
86 lines (73 sloc) 1.84 KB
use serde_derive::{Serialize, Deserialize};
use crate::schema::posts;
use diesel::pg::Pg;
use diesel::deserialize::Queryable;
use diesel::prelude::{Insertable, Expression};
use serde_json;
use diesel::expression::{
AppearsOnTable, AsExpressionList, NonAggregate, SelectableExpression,
};
#[derive(Debug, Serialize, Deserialize)]
pub struct Body {
pub text1: String,
pub text2: String,
}
#[derive(Debug, Identifiable)]
pub struct Post {
pub id: i32,
pub title: String,
pub body: Body,
pub published: bool,
}
#[derive(Insertable)]
#[table_name="posts"]
pub struct NewPost {
pub title: String,
pub body: Body,
}
impl Queryable<posts::SqlType, Pg> for Post {
type Row = (i32, String, serde_json::Value, bool);
fn build(row: Self::Row) -> Self {
let default_body = Body { text1: String::from(""), text2: String::from("") };
let body = match serde_json::from_value(row.2) {
Err(_) => default_body,
Ok(val) => val,
};
Post {
id: row.0,
title: row.1,
body,
published: row.3,
}
}
}
impl Expression for Body {
type SqlType = diesel::sql_types::Jsonb;
}
impl<QS> AppearsOnTable<QS> for Body
where
Body: Expression,
{
}
// use serde_derive::{Serialize, Deserialize};
// use crate::schema::posts;
// use diesel::prelude::{Insertable, Queryable};
// use serde_json;
// #[derive(Debug, Serialize, Deserialize)]
// pub struct Body {
// pub text1: String,
// pub text2: String,
// }
// #[derive(Debug, Identifiable, Queryable)]
// pub struct Post {
// pub id: i32,
// pub title: String,
// pub body: serde_json::Value,
// pub published: bool,
// }
// #[derive(Insertable)]
// #[table_name="posts"]
// pub struct NewPost<'a> {
// pub title: &'a str,
// pub body: serde_json::Value,
// }