104 lines
2.7 KiB
Rust
104 lines
2.7 KiB
Rust
use chrono::NaiveDate;
|
|
use diesel::{insert_into, prelude::*, Insertable, PgConnection, Queryable};
|
|
use rb::errors::{RbError, RbOption, RbResult};
|
|
use serde::{Deserialize, Serialize};
|
|
use uuid::Uuid;
|
|
|
|
use crate::schema::{versions, versions::dsl::*};
|
|
|
|
/// A version inside the database.
|
|
#[derive(Queryable, Serialize)]
|
|
pub struct Version
|
|
{
|
|
pub id: Uuid,
|
|
pub post_id: Uuid,
|
|
pub title: Option<String>,
|
|
pub publish_date: Option<NaiveDate>,
|
|
pub content: String,
|
|
pub is_draft: bool,
|
|
}
|
|
|
|
#[derive(Deserialize, Insertable)]
|
|
#[table_name = "versions"]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct NewVersion
|
|
{
|
|
pub post_id: Uuid,
|
|
pub title: Option<String>,
|
|
pub publish_date: Option<NaiveDate>,
|
|
pub content: Option<String>,
|
|
pub is_draft: Option<bool>,
|
|
}
|
|
|
|
#[derive(Deserialize, AsChangeset)]
|
|
#[table_name = "versions"]
|
|
pub struct PatchVersion
|
|
{
|
|
pub id: Uuid,
|
|
pub post_id: Option<Uuid>,
|
|
pub title: Option<String>,
|
|
pub publish_date: Option<NaiveDate>,
|
|
pub content: Option<String>,
|
|
pub is_draft: Option<bool>,
|
|
}
|
|
|
|
pub fn get(conn: &PgConnection, offset_: u32, limit_: u32) -> RbResult<Vec<Version>>
|
|
{
|
|
Ok(versions
|
|
.offset(offset_.into())
|
|
.limit(std::cmp::min(limit_, super::MAX_VERSIONS).into())
|
|
.load(conn)
|
|
.map_err(|_| RbError::DbError("Couldn't query versions."))?)
|
|
}
|
|
|
|
pub fn get_for_post(
|
|
conn: &PgConnection,
|
|
post_id_: &Uuid,
|
|
offset_: u32,
|
|
limit_: u32,
|
|
) -> RbResult<Vec<Version>>
|
|
{
|
|
Ok(versions
|
|
.offset(offset_.into())
|
|
.filter(post_id.eq(post_id_))
|
|
.limit(std::cmp::min(limit_, super::MAX_VERSIONS).into())
|
|
.load(conn)
|
|
.map_err(|_| RbError::DbError("Couldn't query versions."))?)
|
|
}
|
|
|
|
pub fn find(conn: &PgConnection, id_: &Uuid) -> RbOption<Version>
|
|
{
|
|
match versions.find(id_).first(conn) {
|
|
Ok(val) => Ok(Some(val)),
|
|
Err(diesel::NotFound) => Ok(None),
|
|
_ => Err(RbError::DbError("Couldn't find version.")),
|
|
}
|
|
}
|
|
|
|
pub fn create(conn: &PgConnection, new: &NewVersion) -> RbResult<Version>
|
|
{
|
|
Ok(insert_into(versions)
|
|
.values(new)
|
|
.get_result(conn)
|
|
.map_err(|_| RbError::DbError("Couldn't insert version."))?)
|
|
|
|
// TODO check for conflict?
|
|
}
|
|
|
|
pub fn update(conn: &PgConnection, id_: &Uuid, patch: &PatchVersion) -> RbResult<Version>
|
|
{
|
|
Ok(diesel::update(versions.filter(id.eq(id_)))
|
|
.set(patch)
|
|
.get_result(conn)
|
|
.map_err(|_| RbError::DbError("Couldn't update version."))?)
|
|
}
|
|
|
|
pub fn delete(conn: &PgConnection, id_: &Uuid) -> RbResult<()>
|
|
{
|
|
diesel::delete(versions.filter(id.eq(id_)))
|
|
.execute(conn)
|
|
.map_err(|_| RbError::DbError("Couldn't delete version."))?;
|
|
|
|
Ok(())
|
|
}
|