articles_rs/databases/
images_repository.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
//! Image repository module for database operations
//! 
//! This module provides the database model and repository implementation for article images.
//! It handles CRUD operations and queries for images paths stored in a PostgreSQL database.

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use sqlx::{
    postgres::{PgPool, PgRow},
    Error as SqlxError, FromRow, Row,
};
use std::collections::HashMap;
use uuid::Uuid;

use super::postgres_repository::PostgresRepository;

/// Database model representing an article's image
#[derive(Debug)]
pub struct DbArticleImage {
    pub id: Option<Uuid>,
    pub article_id: Uuid,
    pub image_path: String,
    pub visible: bool,
    pub created_at: DateTime<Utc>,
}

/// Implementation for converting database rows to DbArticleImage
impl<'r> FromRow<'r, PgRow> for DbArticleImage {
    fn from_row(row: &'r PgRow) -> Result<Self, SqlxError> {
        let row_id = row.try_get("id").ok();
        Ok(Self {
            id: row_id,
            article_id: row.get("article_id"),
            image_path: row.get("image_path"),
            visible: row.get("visible"),
            created_at: row
                .try_get::<DateTime<Utc>, _>("created_at")
                .unwrap_or_else(|_| {
                    let naive_date: chrono::NaiveDateTime = row.try_get("created_at").unwrap();
                    DateTime::<Utc>::from_naive_utc_and_offset(naive_date, Utc)
                }),
        })
    }
}

/// Repository for handling article image database operations
pub struct ImageRepository {
    pool: PgPool,
}

impl ImageRepository {
    /// Creates a new ImageRepository instance
    ///
    /// # Arguments
    /// * `pool` - PostgreSQL connection pool
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }
}

/// Implementation of PostgresRepository trait for ImageRepository
#[async_trait]
impl PostgresRepository for ImageRepository {
    type Error = SqlxError;
    type Item = DbArticleImage;

    async fn find_by_id(&self, id: Uuid) -> Result<Option<Self::Item>, Self::Error> {
        let row = sqlx::query_as::<_, DbArticleImage>(
            r#"
            SELECT id, article_id, image_path, visible, created_at
            FROM article_images
            WHERE id = $1
            "#,
        )
        .bind(id)
        .fetch_optional(&self.pool)
        .await?;

        Ok(row)
    }

    async fn find_by_name(&self, _name: String) -> Result<Option<Self::Item>, Self::Error> {
        Err(SqlxError::RowNotFound)
    }

    async fn list(
        &self,
        filters: Option<HashMap<String, String>>,
    ) -> Result<Vec<Self::Item>, Self::Error> {
        let mut query = String::from(
            "SELECT id, article_id, image_path, visible, created_at FROM article_images WHERE 1=1",
        );
        let mut params = vec![];
        let mut param_count = 1;

        if let Some(filters) = filters {
            for (key, value) in filters {
                if key == "id" || key == "article_id" {
                    // Cast the parameter to UUID for id fields
                    query.push_str(&format!(" AND {} = ${}::uuid", key, param_count));
                } else {
                    query.push_str(&format!(" AND {} = ${}", key, param_count));
                }
                params.push(value);
                param_count += 1;
            }
        }

        let mut query_builder = sqlx::query(&query);
        for param in params {
            query_builder = query_builder.bind(param);
        }

        let rows = query_builder
            .fetch_all(&self.pool)
            .await?
            .into_iter()
            .map(|row| DbArticleImage::from_row(&row))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(rows)
    }

    async fn create(&self, item: &Self::Item) -> Result<Uuid, Self::Error> {
        let row = sqlx::query_scalar::<_, Uuid>(
            r#"
            INSERT INTO article_images (article_id, image_path, visible)
            VALUES ($1, $2, $3)
            RETURNING id
            "#,
        )
        .bind(item.article_id)
        .bind(&item.image_path)
        .bind(item.visible)
        .fetch_one(&self.pool)
        .await?;

        Ok(row)
    }

    async fn delete(&self, id: Uuid) -> Result<(), Self::Error> {
        let result = sqlx::query(
            r#"
            DELETE FROM article_images
            WHERE id = $1
            "#,
        )
        .bind(id)
        .execute(&self.pool)
        .await?;

        if result.rows_affected() == 0 {
            return Err(SqlxError::RowNotFound);
        }

        Ok(())
    }

    async fn delete_all(
        &self,
        filters: Option<HashMap<String, String>>,
    ) -> Result<(), Self::Error> {
        let items = self.list(filters).await?;
        for item in items {
            if let Some(id) = item.id {
                self.delete(id).await?;
            }
        }
        Ok(())
    }

    async fn update(&self, _item: &Self::Item) -> Result<(), Self::Error> {
        Err(SqlxError::RowNotFound)
    }
}