articles_rs/databases/
article_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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//! Article repository module for database operations
//! 
//! This module provides the database model and repository implementation for articles.
//! It handles CRUD operations and queries for articles 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 crate::postgres_repository::PostgresRepository;

/// Database model representing an article
///
/// Contains all fields that map to the articles table in the database.
pub struct DbArticle {
    pub id: Option<Uuid>,
    pub title: String,
    pub hero_image: String,
    pub slug: String,
    pub description: String,
    pub author: String,
    pub status: String,
    pub created: DateTime<Utc>,
    pub content: String,
    pub source: String,
    pub published: Option<DateTime<Utc>>,
}


impl DbArticle {
    /// Creates a new `DbArticle` with basic required fields
    ///
    /// # Arguments
    /// * `title` - Article title
    /// * `slug` - URL-friendly slug
    /// * `description` - Brief description
    /// * `author` - Article author
    pub fn new(title: &str, slug: &str, description: &str, author: &str) -> Self {
        let now = Utc::now();
        DbArticle {
            id: None,
            title: title.to_string(),
            hero_image: "".to_string(),
            slug: slug.to_string(),
            description: description.to_string(),
            author: author.to_string(),
            status: "NEW".to_string(),
            created: now,
            content: String::new(),
            source: String::new(),
            published: None,
        }
    }
}

/// Implementation for converting database rows to DbArticle
impl<'r> FromRow<'r, PgRow> for DbArticle {
    fn from_row(row: &'r PgRow) -> Result<Self, sqlx::Error> {
        let row_id = row.try_get("id").ok();
        let hero: String = row.try_get("hero_image").unwrap_or_else(|_| String::new());
        let published = row.try_get::<chrono::NaiveDateTime, _>("published")
            .ok()
            .map(|naive_date| DateTime::<Utc>::from_naive_utc_and_offset(naive_date, Utc));
        Ok(DbArticle {
            id: row_id,
            title: row.try_get("title")?,
            hero_image: hero,
            slug: row.try_get("slug")?,
            description: row.try_get("description")?,
            author: row.try_get("author")?,
            status: row.try_get("status")?,
            created: row
                .try_get::<DateTime<Utc>, _>("created")
                .unwrap_or_else(|_| {
                    // Handle conversion of naive datetime to UTC
                    let naive_date: chrono::NaiveDateTime = row.try_get("created").unwrap();
                    DateTime::<Utc>::from_naive_utc_and_offset(naive_date, Utc)
                }),
            content: row.try_get("content")?,
            source: row.try_get("source").unwrap_or_default(),
            published: published,
        })
    }
}

/// Repository for handling article database operations
pub struct ArticleRepository {
    /// Database connection pool
    pool: PgPool,
}

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

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

    /// Creates a new article in the database
    ///
    /// # Arguments
    /// * `article` - Article to create
    ///
    /// # Returns
    /// The UUID of the created article
    async fn create(&self, article: &Self::Item) -> Result<Uuid, Self::Error> {
        let row = sqlx::query(
            r#"
                INSERT INTO articles (title, slug, source, description, author, status, created, content, published)
                VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
                RETURNING id
                "#,
        )
        .bind(&article.title)
        .bind(&article.slug)
        .bind(&article.source)
        .bind(&article.description)
        .bind(&article.author)
        .bind(&article.status)
        .bind(article.created)
        .bind(&article.content)
        .fetch_one(&self.pool)
        .await?;

        let id: Uuid = row.try_get("id")?;
        Ok(id)
    }

    /// Updates an existing article in the database
    ///
    /// # Arguments
    /// * `article` - Article with updated fields
    ///
    /// # Returns
    /// Error if article not found
    async fn update(&self, article: &Self::Item) -> Result<(), Self::Error> {
        let affected_rows = sqlx::query(
            r#"
                UPDATE articles
                SET title = $1, slug = $2, author = $3, status = $4, created = $5, content = $6, description = $7, source = $8, published = $9
                WHERE id = $10
                "#,
        )
        .bind(&article.title)
        .bind(&article.slug)
        .bind(&article.author)
        .bind(&article.status)
        .bind(article.created)
        .bind(&article.content)
        .bind(&article.description)
        .bind(&article.source)
        .bind(article.published)
        .bind(article.id)
        .execute(&self.pool)
        .await?
        .rows_affected();

        if affected_rows == 0 {
            return Err(SqlxError::RowNotFound);
        }

        Ok(())
    }

    /// Deletes an article from the database
    ///
    /// # Arguments
    /// * `id` - UUID of article to delete
    ///
    /// # Returns
    /// Error if article not found
    async fn delete(&self, id: Uuid) -> Result<(), Self::Error> {
        let affected_rows = sqlx::query(
            r#"
                DELETE FROM articles
                WHERE id = $1
                "#,
        )
        .bind(id)
        .execute(&self.pool)
        .await?
        .rows_affected();

        if affected_rows == 0 {
            return Err(SqlxError::RowNotFound);
        }

        Ok(())
    }

    /// Deletes all articles matching the provided filters
    /// 
    /// Currently not implemented
    async fn delete_all(
        &self,
        _filters: Option<HashMap<String, String>>,
    ) -> Result<(), Self::Error> {
        tracing::warn!("delete_all not implemented");
        return Err(SqlxError::RowNotFound);
    }

    /// Finds an article by its UUID
    ///
    /// # Arguments
    /// * `id` - UUID to search for
    ///
    /// # Returns
    /// The article if found, None otherwise
    async fn find_by_id(&self, id: Uuid) -> Result<Option<Self::Item>, Self::Error> {
        let row_result = sqlx::query(
            "SELECT articles.id, title, slug, description, author, status, created, content,
            (SELECT image_path FROM article_images WHERE article_images.article_id = articles.id LIMIT 1) as hero_image,
            source,
            published
            FROM articles WHERE articles.id = $1",
        )
        .bind(id)
        .fetch_optional(&self.pool)
        .await?;

        match row_result {
            Some(row) => {
                let article = DbArticle::from_row(&row)?;
                Ok(Some(article))
            }
            None => Ok(None),
        }
    }

    /// Finds an article by its slug
    ///
    /// # Arguments
    /// * `slug` - Slug to search for
    ///
    /// # Returns
    /// The article if found, None otherwise
    async fn find_by_name(&self, slug: String) -> Result<Option<Self::Item>, Self::Error> {
        let sql = "SELECT articles.id, title, slug, description, author, status, created, content,
                            (SELECT image_path FROM article_images WHERE article_images.article_id = articles.id LIMIT 1) as hero_image,
                            source,
                            published
                            FROM articles WHERE articles.slug = $1";
        let row_result = sqlx::query(sql)
            .bind(slug.clone())
            .fetch_optional(&self.pool)
            .await?;

        match row_result {
            Some(row) => {
                let article = DbArticle::from_row(&row)?;
                Ok(Some(article))
            }
            None => Ok(None),
        }
    }

    /// Lists articles with optional filters
    ///
    /// # Arguments
    /// * `filters` - Optional HashMap of column names to values to filter by
    ///
    /// # Returns
    /// Vector of matching articles
    async fn list(
        &self,
        filters: Option<HashMap<String, String>>,
    ) -> Result<Vec<Self::Item>, Self::Error> {
        // Build base query
        let mut query = String::from(
            "SELECT articles.id, title, slug, description, author, status, created, content, source, published,
                                        (SELECT image_path FROM article_images WHERE article_images.article_id = articles.id LIMIT 1) as hero_image
                                        FROM articles",
        );
        let mut params: Vec<String> = Vec::new();
        let mut param_count = 1;

        // Add WHERE clause if filters are provided
        if let Some(filter_map) = filters {
            if !filter_map.is_empty() {
                query.push_str(" WHERE ");
                for (column, value) in filter_map {
                    if param_count > 1 {
                        query.push_str(" AND ");
                    }
                    query.push_str(&format!("{} = ${}", column, param_count));
                    params.push(value);
                    param_count += 1;
                }
            }
        }

        // Add ORDER BY clause
        query.push_str(" ORDER BY created DESC");
        let mut query_builder = sqlx::query(&query);
        
        // Bind parameters, handling UUIDs specially
        for param in params {
            // Try parsing as UUID first, if it fails, bind as a string
            if let Ok(uuid) = sqlx::types::Uuid::parse_str(&param) {
                query_builder = query_builder.bind(uuid);
            } else {
                query_builder = query_builder.bind(param);
            }
        }

        // Execute query and convert results to DbArticles
        let articles = query_builder
            .fetch_all(&self.pool)
            .await?
            .into_iter()
            .map(|row| DbArticle::from_row(&row))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(articles)
    }
}