2021-09-15 11:36:40 +02:00
|
|
|
//! Handles all section-related database operations.
|
|
|
|
|
2021-09-13 17:35:06 +02:00
|
|
|
use diesel::{insert_into, prelude::*, Insertable, PgConnection, Queryable};
|
2021-09-13 22:15:38 +02:00
|
|
|
use serde::Deserialize;
|
2021-09-13 17:35:06 +02:00
|
|
|
use uuid::Uuid;
|
|
|
|
|
|
|
|
use crate::{
|
|
|
|
errors::{RbError, RbResult},
|
|
|
|
schema::{sections, sections::dsl::*},
|
|
|
|
};
|
|
|
|
|
2021-09-15 11:36:40 +02:00
|
|
|
/// Represents a section contained in the database.
|
2021-09-13 17:35:06 +02:00
|
|
|
#[derive(Queryable)]
|
|
|
|
pub struct Section
|
|
|
|
{
|
|
|
|
pub id: Uuid,
|
|
|
|
pub title: String,
|
|
|
|
pub description: Option<String>,
|
|
|
|
pub is_default: bool,
|
|
|
|
pub has_titles: bool,
|
|
|
|
}
|
|
|
|
|
2021-09-15 11:36:40 +02:00
|
|
|
/// A new section to be added into the database.
|
2021-09-13 22:15:38 +02:00
|
|
|
#[derive(Deserialize, Insertable)]
|
2021-09-13 17:35:06 +02:00
|
|
|
#[table_name = "sections"]
|
2021-09-13 22:15:38 +02:00
|
|
|
// #[serde(rename_all = "camelCase")]
|
2021-09-13 17:35:06 +02:00
|
|
|
pub struct NewSection
|
|
|
|
{
|
|
|
|
title: String,
|
|
|
|
description: Option<String>,
|
2021-09-13 22:15:38 +02:00
|
|
|
is_default: Option<bool>,
|
|
|
|
has_titles: Option<bool>,
|
2021-09-13 17:35:06 +02:00
|
|
|
}
|
|
|
|
|
2021-09-15 11:36:40 +02:00
|
|
|
/// Returns all sections in the database.
|
|
|
|
///
|
|
|
|
/// # Arguments
|
|
|
|
///
|
|
|
|
/// * `conn` - reference to a database connection
|
2021-09-13 17:35:06 +02:00
|
|
|
pub fn all(conn: &PgConnection) -> RbResult<Vec<Section>>
|
|
|
|
{
|
2021-09-13 22:15:38 +02:00
|
|
|
sections
|
|
|
|
.load::<Section>(conn)
|
|
|
|
.map_err(|_| RbError::DbError("Couldn't get all sections"))
|
2021-09-13 17:35:06 +02:00
|
|
|
}
|
|
|
|
|
2021-09-15 11:36:40 +02:00
|
|
|
/// Inserts a new section into the database.
|
|
|
|
///
|
|
|
|
/// # Arguments
|
|
|
|
///
|
|
|
|
/// * `conn` - reference to a database connection
|
|
|
|
/// * `new_section` - the new section to be added
|
2021-09-13 17:35:06 +02:00
|
|
|
pub fn create(conn: &PgConnection, new_section: &NewSection) -> RbResult<()>
|
|
|
|
{
|
|
|
|
insert_into(sections)
|
|
|
|
.values(new_section)
|
|
|
|
.execute(conn)
|
|
|
|
.map_err(|_| RbError::DbError("Couldn't insert section."))?;
|
|
|
|
|
|
|
|
// TODO check for conflict?
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|