li7y/src/manage/item.rs

99 lines
2.7 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;
use sqlx::{query, query_as, query_scalar, PgPool};
2024-06-24 22:46:04 +02:00
use uuid::Uuid;
use crate::models::{Item, NewItem};
2024-06-24 22:46:04 +02:00
pub async fn add(pool: &PgPool, new_item: NewItem) -> Result<Item, sqlx::Error> {
query_as!(
Item,
"INSERT INTO items (name, parent, class) VALUES ($1, $2, $3) RETURNING *",
new_item.name,
new_item.parent,
new_item.class
)
.fetch_one(pool)
.await
2024-06-24 22:46:04 +02:00
}
pub async fn get(pool: &PgPool, id: Uuid) -> Result<Item, sqlx::Error> {
query_as!(Item, "SELECT * FROM items WHERE id = $1", id)
.fetch_one(pool)
.await
2024-06-24 22:46:04 +02:00
}
pub async fn get_all(pool: &PgPool) -> Result<Vec<Item>, sqlx::Error> {
query_as!(Item, "SELECT * FROM items").fetch_all(pool).await
2024-06-24 22:46:04 +02:00
}
2024-07-03 18:47:29 +02:00
pub async fn get_all_as_map(pool: &PgPool) -> Result<HashMap<Uuid, Item>, sqlx::Error> {
Ok(get_all(pool)
.await?
.into_iter()
.map(|i| (i.id, i))
.collect())
}
pub async fn update(pool: &PgPool, id: Uuid, modified_item: NewItem) -> Result<Item, sqlx::Error> {
query_as!(
Item,
"UPDATE items SET name = $2, parent = $3, class = $4 WHERE id = $1 RETURNING *",
id,
modified_item.name,
modified_item.parent,
modified_item.class
)
.fetch_one(pool)
.await
2024-07-03 18:47:29 +02:00
}
2024-07-05 12:38:45 +02:00
pub async fn delete(pool: &PgPool, id: Uuid) -> Result<(), sqlx::Error> {
let res = query!("DELETE FROM items WHERE id = $1", id)
.execute(pool)
.await?;
assert_eq!(res.rows_affected(), 1);
Ok(())
}
pub async fn get_parents(pool: &PgPool, id: Uuid) -> Result<Vec<Uuid>, sqlx::Error> {
// force nullable is required for all columns in views
query_scalar!(
r#"SELECT unnest(parents) as "parents!" FROM item_tree WHERE id = $1"#,
id
)
.fetch_all(pool)
.await
2024-07-05 12:38:45 +02:00
}
pub async fn get_all_parents(pool: &PgPool) -> Result<HashMap<Uuid, Vec<Uuid>>, sqlx::Error> {
let mut parents = HashMap::new();
for row in query!(r#"SELECT id as "id!", parents as "parents!" FROM item_tree"#)
.fetch_all(pool)
.await?
{
parents.insert(row.id, row.parents);
}
Ok(parents)
2024-07-05 12:38:45 +02:00
}
pub async fn get_parents_details(pool: &PgPool, id: Uuid) -> Result<Vec<Item>, sqlx::Error> {
query_as!(
Item,
"SELECT * FROM items WHERE id = ANY (SELECT unnest(parents) FROM item_tree WHERE id = $1)",
id
)
.fetch_all(pool)
.await
}
2024-07-08 22:45:28 +02:00
pub async fn get_children(pool: &PgPool, id: Uuid) -> Result<Vec<Item>, sqlx::Error> {
query_as!(Item, "SELECT * FROM items WHERE parent = $1", id)
.fetch_all(pool)
2024-07-08 22:45:28 +02:00
.await
}