backbone-core 3.0.0

Backbone Framework Core - Foundation for generic CRUD system
Documentation
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! PostgreSQL Repository Implementation
//!
//! Generic PostgreSQL-backed repository for production use.
//!
//! # Usage
//!
//! 1. Implement `PostgresEntity` for your entity (includes bind methods)
//! 2. Derive `FromRow` for automatic row mapping
//! 3. Create a repository instance with your entity type
//!
//! ```ignore
//! use backbone_core::persistence::{PostgresRepository, PostgresEntity, PersistentEntity};
//! use sqlx::FromRow;
//!
//! #[derive(Clone, Debug, Serialize, Deserialize, FromRow)]
//! struct User {
//!     id: String,
//!     name: String,
//!     email: String,
//!     created_at: Option<DateTime<Utc>>,
//!     updated_at: Option<DateTime<Utc>>,
//!     deleted_at: Option<DateTime<Utc>>,
//! }
//!
//! impl PersistentEntity for User { /* ... */ }
//!
//! impl PostgresEntity for User {
//!     fn table_name() -> &'static str { "users" }
//!     fn select_columns() -> &'static [&'static str] {
//!         &["id", "name", "email", "created_at", "updated_at", "deleted_at"]
//!     }
//!     fn insert_columns() -> &'static [&'static str] {
//!         &["id", "name", "email", "created_at", "updated_at"]
//!     }
//!     fn bind_for_insert<'q>(entity: &Self, query: Query<'q, ...>) -> Query<'q, ...> {
//!         query.bind(&entity.id).bind(&entity.name).bind(&entity.email)
//!             .bind(entity.created_at).bind(entity.updated_at)
//!     }
//! }
//!
//! let pool = PgPool::connect("...").await?;
//! let repo = PostgresRepository::<User>::new(pool);
//! ```

use async_trait::async_trait;
use sqlx::postgres::PgRow;
use sqlx::PgPool;
use std::collections::HashMap;
use std::marker::PhantomData;

use super::traits::{CrudRepository, PostgresEntity, RepositoryError, SearchableRepository};

/// Generic PostgreSQL repository
///
/// Provides PostgreSQL-backed persistence for any entity implementing
/// `PostgresEntity` (which includes `FromRow` + `PersistentEntity`).
pub struct PostgresRepository<E>
where
    E: PostgresEntity,
{
    pool: PgPool,
    _phantom: PhantomData<E>,
}

impl<E> PostgresRepository<E>
where
    E: PostgresEntity,
{
    /// Create a new repository with the given connection pool
    pub fn new(pool: PgPool) -> Self {
        Self {
            pool,
            _phantom: PhantomData,
        }
    }

    /// Get a reference to the connection pool
    pub fn pool(&self) -> &PgPool {
        &self.pool
    }

    /// Execute a raw query and return entities
    pub async fn query_as(&self, sql: &str) -> Result<Vec<E>, RepositoryError> {
        let rows = sqlx::query(sql).fetch_all(&self.pool).await?;
        rows.iter()
            .map(|row| E::from_row(row).map_err(|e| RepositoryError::DatabaseError(e.to_string())))
            .collect()
    }
}

impl<E> Clone for PostgresRepository<E>
where
    E: PostgresEntity,
{
    fn clone(&self) -> Self {
        Self {
            pool: self.pool.clone(),
            _phantom: PhantomData,
        }
    }
}

#[async_trait]
impl<E> CrudRepository<E> for PostgresRepository<E>
where
    E: PostgresEntity,
{
    async fn create(&self, mut entity: E) -> Result<E, RepositoryError> {
        // Generate ID if empty
        if entity.entity_id().is_empty() {
            entity.set_entity_id(E::generate_id());
        }

        // Set timestamps
        let now = chrono::Utc::now();
        if entity.created_at().is_none() {
            entity.set_created_at(now);
        }
        entity.set_updated_at(now);

        // Build INSERT query
        let table = E::table_name();
        let columns = E::insert_columns();
        let select_cols = E::select_columns().join(", ");

        let placeholders: Vec<String> = (1..=columns.len()).map(|i| format!("${}", i)).collect();

        let query = format!(
            "INSERT INTO {} ({}) VALUES ({}) RETURNING {}",
            table,
            columns.join(", "),
            placeholders.join(", "),
            select_cols
        );

        let q = sqlx::query(&query);
        let q = E::bind_for_insert(&entity, q);
        let row: PgRow = q.fetch_one(&self.pool).await?;

        E::from_row(&row).map_err(|e| RepositoryError::DatabaseError(e.to_string()))
    }

    async fn find_by_id(&self, id: &str) -> Result<Option<E>, RepositoryError> {
        let query = E::select_by_id_query();
        let row = sqlx::query(&query)
            .bind(id)
            .fetch_optional(&self.pool)
            .await?;

        match row {
            Some(row) => Ok(Some(
                E::from_row(&row).map_err(|e| RepositoryError::DatabaseError(e.to_string()))?,
            )),
            None => Ok(None),
        }
    }

    async fn find_by_id_including_deleted(&self, id: &str) -> Result<Option<E>, RepositoryError> {
        let query = E::select_by_id_including_deleted_query();
        let row = sqlx::query(&query)
            .bind(id)
            .fetch_optional(&self.pool)
            .await?;

        match row {
            Some(row) => Ok(Some(
                E::from_row(&row).map_err(|e| RepositoryError::DatabaseError(e.to_string()))?,
            )),
            None => Ok(None),
        }
    }

    async fn update(&self, mut entity: E) -> Result<E, RepositoryError> {
        entity.set_updated_at(chrono::Utc::now());

        // Build UPDATE query
        let table = E::table_name();
        let id_col = E::id_column();
        let columns = E::update_columns();
        let select_cols = E::select_columns().join(", ");

        // Build SET clause: col1 = $1, col2 = $2, ...
        let set_clause: Vec<String> = columns
            .iter()
            .enumerate()
            .map(|(i, col)| format!("{} = ${}", col, i + 1))
            .collect();

        let id_param = columns.len() + 1;
        let query = format!(
            "UPDATE {} SET {} WHERE {} = ${} RETURNING {}",
            table,
            set_clause.join(", "),
            id_col,
            id_param,
            select_cols
        );

        let q = sqlx::query(&query);
        let q = E::bind_for_update(&entity, q);
        let q = q.bind(entity.entity_id());
        let row: PgRow = q.fetch_one(&self.pool).await?;

        E::from_row(&row).map_err(|e| RepositoryError::DatabaseError(e.to_string()))
    }

    async fn soft_delete(&self, id: &str) -> Result<bool, RepositoryError> {
        let query = E::soft_delete_query();
        let result = sqlx::query(&query).bind(id).execute(&self.pool).await?;
        Ok(result.rows_affected() > 0)
    }

    async fn restore(&self, id: &str) -> Result<Option<E>, RepositoryError> {
        let query = E::restore_query();
        let row = sqlx::query(&query)
            .bind(id)
            .fetch_optional(&self.pool)
            .await?;

        match row {
            Some(row) => Ok(Some(
                E::from_row(&row).map_err(|e| RepositoryError::DatabaseError(e.to_string()))?,
            )),
            None => Ok(None),
        }
    }

    async fn hard_delete(&self, id: &str) -> Result<bool, RepositoryError> {
        let query = E::hard_delete_query();
        let result = sqlx::query(&query).bind(id).execute(&self.pool).await?;
        Ok(result.rows_affected() > 0)
    }

    async fn list(&self, page: u32, limit: u32) -> Result<(Vec<E>, u64), RepositoryError> {
        let offset = (page.saturating_sub(1)) * limit;

        // Get count
        let count_query = E::count_query();
        let count: i64 = sqlx::query_scalar(&count_query)
            .fetch_one(&self.pool)
            .await?;
        let total = count as u64;

        // Get entities
        let list_query = E::list_query();
        let rows = sqlx::query(&list_query)
            .bind(limit as i32)
            .bind(offset as i32)
            .fetch_all(&self.pool)
            .await?;

        let entities: Result<Vec<E>, _> = rows
            .iter()
            .map(|row| E::from_row(row))
            .collect();

        Ok((
            entities.map_err(|e| RepositoryError::DatabaseError(e.to_string()))?,
            total,
        ))
    }

    async fn list_deleted(&self, page: u32, limit: u32) -> Result<(Vec<E>, u64), RepositoryError> {
        let offset = (page.saturating_sub(1)) * limit;

        // Get count
        let count_query = E::count_deleted_query();
        let count: i64 = sqlx::query_scalar(&count_query)
            .fetch_one(&self.pool)
            .await?;
        let total = count as u64;

        // Get entities
        let list_query = E::list_deleted_query();
        let rows = sqlx::query(&list_query)
            .bind(limit as i32)
            .bind(offset as i32)
            .fetch_all(&self.pool)
            .await?;

        let entities: Result<Vec<E>, _> = rows
            .iter()
            .map(|row| E::from_row(row))
            .collect();

        Ok((
            entities.map_err(|e| RepositoryError::DatabaseError(e.to_string()))?,
            total,
        ))
    }

    async fn count(&self) -> Result<u64, RepositoryError> {
        let query = E::count_query();
        let count: i64 = sqlx::query_scalar(&query).fetch_one(&self.pool).await?;
        Ok(count as u64)
    }

    async fn count_deleted(&self) -> Result<u64, RepositoryError> {
        let query = E::count_deleted_query();
        let count: i64 = sqlx::query_scalar(&query).fetch_one(&self.pool).await?;
        Ok(count as u64)
    }

    async fn bulk_create(&self, entities: Vec<E>) -> Result<Vec<E>, RepositoryError> {
        // Use a transaction for bulk operations
        let mut tx = self.pool.begin().await?;
        let mut results = Vec::with_capacity(entities.len());

        for mut entity in entities {
            // Generate ID if empty
            if entity.entity_id().is_empty() {
                entity.set_entity_id(E::generate_id());
            }

            // Set timestamps
            let now = chrono::Utc::now();
            if entity.created_at().is_none() {
                entity.set_created_at(now);
            }
            entity.set_updated_at(now);

            // Build INSERT query
            let table = E::table_name();
            let columns = E::insert_columns();
            let select_cols = E::select_columns().join(", ");

            let placeholders: Vec<String> =
                (1..=columns.len()).map(|i| format!("${}", i)).collect();

            let query = format!(
                "INSERT INTO {} ({}) VALUES ({}) RETURNING {}",
                table,
                columns.join(", "),
                placeholders.join(", "),
                select_cols
            );

            let q = sqlx::query(&query);
            let q = E::bind_for_insert(&entity, q);
            let row: PgRow = q.fetch_one(&mut *tx).await?;
            let created =
                E::from_row(&row).map_err(|e| RepositoryError::DatabaseError(e.to_string()))?;
            results.push(created);
        }

        tx.commit().await?;
        Ok(results)
    }

    async fn empty_trash(&self) -> Result<u64, RepositoryError> {
        let query = E::empty_trash_query();
        let result = sqlx::query(&query).execute(&self.pool).await?;
        Ok(result.rows_affected())
    }
}

#[async_trait]
impl<E> SearchableRepository<E> for PostgresRepository<E>
where
    E: PostgresEntity,
{
    async fn search(
        &self,
        filters: HashMap<String, String>,
        page: u32,
        limit: u32,
    ) -> Result<(Vec<E>, u64), RepositoryError> {
        let offset = (page.saturating_sub(1)) * limit;
        let table = E::table_name();
        let columns = E::select_columns().join(", ");

        // Build WHERE clause from filters
        let mut conditions = vec!["deleted_at IS NULL".to_string()];
        let mut bind_values: Vec<String> = Vec::new();
        let mut param_idx = 1;

        for (key, value) in &filters {
            // Only allow filtering on known columns to prevent SQL injection
            if E::select_columns().contains(&key.as_str()) {
                conditions.push(format!("{}::text ILIKE ${}", key, param_idx));
                bind_values.push(format!("%{}%", value));
                param_idx += 1;
            }
        }

        let where_clause = conditions.join(" AND ");

        // Count query
        let count_query = format!("SELECT COUNT(*) FROM {} WHERE {}", table, where_clause);

        let mut count_q = sqlx::query_scalar::<_, i64>(&count_query);
        for val in &bind_values {
            count_q = count_q.bind(val.clone());
        }
        let total = count_q.fetch_one(&self.pool).await? as u64;

        // List query
        let list_query = format!(
            "SELECT {} FROM {} WHERE {} ORDER BY created_at DESC LIMIT ${} OFFSET ${}",
            columns,
            table,
            where_clause,
            param_idx,
            param_idx + 1
        );

        let mut list_q = sqlx::query(&list_query);
        for val in &bind_values {
            list_q = list_q.bind(val.clone());
        }
        list_q = list_q.bind(limit as i32).bind(offset as i32);

        let rows = list_q.fetch_all(&self.pool).await?;
        let entities: Result<Vec<E>, _> = rows.iter().map(|row| E::from_row(row)).collect();

        Ok((
            entities.map_err(|e| RepositoryError::DatabaseError(e.to_string()))?,
            total,
        ))
    }

    async fn find_by_field(&self, field: &str, value: &str) -> Result<Option<E>, RepositoryError> {
        // Validate field is a known column
        if !E::select_columns().contains(&field) {
            return Err(RepositoryError::ValidationError(format!(
                "Unknown field: {}",
                field
            )));
        }

        let query = format!(
            "SELECT {} FROM {} WHERE {} = $1 AND deleted_at IS NULL LIMIT 1",
            E::select_columns().join(", "),
            E::table_name(),
            field
        );

        let row = sqlx::query(&query)
            .bind(value)
            .fetch_optional(&self.pool)
            .await?;

        match row {
            Some(row) => Ok(Some(
                E::from_row(&row).map_err(|e| RepositoryError::DatabaseError(e.to_string()))?,
            )),
            None => Ok(None),
        }
    }

    async fn find_all_by_field(
        &self,
        field: &str,
        value: &str,
        page: u32,
        limit: u32,
    ) -> Result<(Vec<E>, u64), RepositoryError> {
        // Validate field is a known column
        if !E::select_columns().contains(&field) {
            return Err(RepositoryError::ValidationError(format!(
                "Unknown field: {}",
                field
            )));
        }

        let offset = (page.saturating_sub(1)) * limit;

        // Count
        let count_query = format!(
            "SELECT COUNT(*) FROM {} WHERE {} = $1 AND deleted_at IS NULL",
            E::table_name(),
            field
        );
        let total: i64 = sqlx::query_scalar(&count_query)
            .bind(value)
            .fetch_one(&self.pool)
            .await?;

        // List
        let list_query = format!(
            "SELECT {} FROM {} WHERE {} = $1 AND deleted_at IS NULL ORDER BY created_at DESC LIMIT $2 OFFSET $3",
            E::select_columns().join(", "),
            E::table_name(),
            field
        );

        let rows = sqlx::query(&list_query)
            .bind(value)
            .bind(limit as i32)
            .bind(offset as i32)
            .fetch_all(&self.pool)
            .await?;

        let entities: Result<Vec<E>, _> = rows.iter().map(|row| E::from_row(row)).collect();

        Ok((
            entities.map_err(|e| RepositoryError::DatabaseError(e.to_string()))?,
            total as u64,
        ))
    }
}

// ============================================================
// Helper: Repository Builder
// ============================================================

/// Builder for creating repositories with custom configuration
pub struct PostgresRepositoryBuilder<E>
where
    E: PostgresEntity,
{
    pool: Option<PgPool>,
    _phantom: PhantomData<E>,
}

impl<E> PostgresRepositoryBuilder<E>
where
    E: PostgresEntity,
{
    pub fn new() -> Self {
        Self {
            pool: None,
            _phantom: PhantomData,
        }
    }

    pub fn with_pool(mut self, pool: PgPool) -> Self {
        self.pool = Some(pool);
        self
    }

    pub fn build(self) -> Result<PostgresRepository<E>, RepositoryError> {
        let pool = self.pool.ok_or_else(|| {
            RepositoryError::InternalError("Database pool not configured".to_string())
        })?;

        Ok(PostgresRepository::new(pool))
    }
}

impl<E> Default for PostgresRepositoryBuilder<E>
where
    E: PostgresEntity,
{
    fn default() -> Self {
        Self::new()
    }
}