li7y/src/manage/item.rs

94 lines
2.5 KiB
Rust
Raw Normal View History

2024-06-24 22:46:04 +02:00
// SPDX-FileCopyrightText: 2024 Simon Bruder <simon@sbruder.de>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
2024-07-05 12:38:45 +02:00
use std::collections::HashMap;
2024-06-24 22:46:04 +02:00
use diesel::prelude::*;
use diesel_async::pg::AsyncPgConnection;
use diesel_async::RunQueryDsl;
2024-06-24 22:46:04 +02:00
use uuid::Uuid;
use crate::{models::*, schema};
pub async fn add(
conn: &mut AsyncPgConnection,
new_item: NewItem,
) -> Result<Item, diesel::result::Error> {
2024-06-24 22:46:04 +02:00
diesel::insert_into(schema::items::table)
.values(new_item)
.returning(Item::as_returning())
.get_result(conn)
.await
2024-06-24 22:46:04 +02:00
}
pub async fn get(conn: &mut AsyncPgConnection, id: Uuid) -> Result<Item, diesel::result::Error> {
2024-06-24 22:46:04 +02:00
schema::items::table
.filter(schema::items::id.eq(id))
.select(Item::as_select())
.first(conn)
.await
2024-06-24 22:46:04 +02:00
}
pub async fn get_all(conn: &mut AsyncPgConnection) -> Result<Vec<Item>, diesel::result::Error> {
schema::items::table
.select(Item::as_select())
.load(conn)
.await
2024-06-24 22:46:04 +02:00
}
2024-07-03 18:47:29 +02:00
pub async fn update(
conn: &mut AsyncPgConnection,
2024-07-05 12:38:45 +02:00
id: Uuid,
modified_item: NewItem,
) -> Result<Item, diesel::result::Error> {
2024-07-03 18:47:29 +02:00
diesel::update(schema::items::table.filter(schema::items::id.eq(id)))
.set(modified_item)
.returning(Item::as_returning())
.get_result(conn)
.await
2024-07-03 18:47:29 +02:00
}
2024-07-05 12:38:45 +02:00
pub async fn delete(conn: &mut AsyncPgConnection, id: Uuid) -> Result<(), diesel::result::Error> {
let num_deleted = diesel::delete(schema::items::table.filter(schema::items::id.eq(id)))
.execute(conn)
.await?;
assert_eq!(num_deleted, 1);
Ok(())
}
2024-07-05 12:38:45 +02:00
/// 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<Uuid>,
}
pub async fn get_parents(
conn: &mut AsyncPgConnection,
id: Uuid,
) -> Result<Vec<Uuid>, diesel::result::Error> {
2024-07-05 12:38:45 +02:00
schema::item_tree::table
.filter(schema::item_tree::id.eq(id))
.select(ItemTreeMapping::as_select())
.first(conn)
.await
2024-07-05 12:38:45 +02:00
.map(|itm| itm.parents)
}
pub async fn get_all_parents(
conn: &mut AsyncPgConnection,
2024-07-05 12:38:45 +02:00
) -> Result<HashMap<Uuid, Vec<Uuid>>, diesel::result::Error> {
schema::item_tree::table
.select(ItemTreeMapping::as_select())
.load(conn)
.await
2024-07-05 12:38:45 +02:00
.map(|itms| {
itms.into_iter()
.map(|ItemTreeMapping { id, parents }| (id, parents))
.collect::<HashMap<Uuid, Vec<Uuid>>>()
})
}