docbox_database/models/
document_box.rs1use crate::{DbExecutor, DbResult};
2use chrono::{DateTime, Utc};
3use serde::{Deserialize, Serialize};
4use sqlx::{postgres::PgQueryResult, prelude::FromRow};
5use utoipa::ToSchema;
6
7pub type DocumentBoxScopeRaw = String;
8
9#[derive(Debug, Clone, FromRow, Serialize, ToSchema)]
10pub struct DocumentBox {
11 pub scope: DocumentBoxScopeRaw,
13 pub created_at: DateTime<Utc>,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
18pub struct WithScope<T> {
19 #[serde(flatten)]
20 pub data: T,
21 pub scope: DocumentBoxScopeRaw,
22}
23
24impl<T> WithScope<T> {
25 pub fn new(data: T, scope: DocumentBoxScopeRaw) -> WithScope<T> {
26 WithScope { data, scope }
27 }
28}
29
30impl DocumentBox {
31 pub async fn all(db: impl DbExecutor<'_>) -> DbResult<Vec<DocumentBox>> {
33 sqlx::query_as(r#"SELECT * FROM "docbox_boxes""#)
34 .fetch_all(db)
35 .await
36 }
37
38 pub async fn find_by_scope(
40 db: impl DbExecutor<'_>,
41 scope: &DocumentBoxScopeRaw,
42 ) -> DbResult<Option<DocumentBox>> {
43 sqlx::query_as(r#"SELECT * FROM "docbox_boxes" WHERE "scope" = $1"#)
44 .bind(scope)
45 .fetch_optional(db)
46 .await
47 }
48
49 pub async fn create(db: impl DbExecutor<'_>, scope: String) -> DbResult<DocumentBox> {
50 let document_box = DocumentBox {
51 scope,
52 created_at: Utc::now(),
53 };
54
55 sqlx::query(r#"INSERT INTO "docbox_boxes" ("scope", "created_at") VALUES ($1, $2)"#)
56 .bind(document_box.scope.as_str())
57 .bind(document_box.created_at)
58 .execute(db)
59 .await?;
60
61 Ok(document_box)
62 }
63
64 pub async fn delete(&self, db: impl DbExecutor<'_>) -> DbResult<PgQueryResult> {
66 sqlx::query(r#"DELETE FROM "docbox_boxes" WHERE "scope" = $1"#)
67 .bind(&self.scope)
68 .execute(db)
69 .await
70 }
71}