// SPDX-FileCopyrightText: 2024 Simon Bruder // // SPDX-License-Identifier: AGPL-3.0-or-later use std::collections::HashMap; use diesel::pg::PgConnection; use diesel::prelude::*; use uuid::Uuid; use crate::{models::*, schema}; pub fn add(conn: &mut PgConnection, new_item: NewItem) -> Result { diesel::insert_into(schema::items::table) .values(new_item) .returning(Item::as_returning()) .get_result(conn) } pub fn get(conn: &mut PgConnection, id: Uuid) -> Result { schema::items::table .filter(schema::items::id.eq(id)) .select(Item::as_select()) .first(conn) } pub fn get_all(conn: &mut PgConnection) -> Result, diesel::result::Error> { schema::items::table.select(Item::as_select()).load(conn) } pub fn update( conn: &mut PgConnection, id: Uuid, modified_item: NewItem, ) -> Result { diesel::update(schema::items::table.filter(schema::items::id.eq(id))) .set(modified_item) .returning(Item::as_returning()) .get_result(conn) } /// Helper type for querying parents of items #[derive(Debug, Queryable, Selectable)] #[diesel(table_name = schema::item_tree)] #[diesel(check_for_backend(diesel::pg::Pg))] struct ItemTreeMapping { pub id: Uuid, pub parents: Vec, } pub fn get_parents(conn: &mut PgConnection, id: Uuid) -> Result, diesel::result::Error> { schema::item_tree::table .filter(schema::item_tree::id.eq(id)) .select(ItemTreeMapping::as_select()) .first(conn) .map(|itm| itm.parents) } pub fn get_all_parents( conn: &mut PgConnection, ) -> Result>, diesel::result::Error> { schema::item_tree::table .select(ItemTreeMapping::as_select()) .load(conn) .map(|itms| { itms.into_iter() .map(|ItemTreeMapping { id, parents }| (id, parents)) .collect::>>() }) }