backbone-core 3.0.2

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
549
550
551
552
553
554
555
556
557
//! Repository Traits - Contracts for Entity Persistence
//!
//! These traits define the contracts that entities and repositories must implement
//! to work with the generic repository implementations.

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{de::DeserializeOwned, Serialize};
use std::collections::HashMap;
use std::fmt::Debug;

// ============================================================
// Error Types
// ============================================================

/// Repository error types
#[derive(Debug, thiserror::Error)]
pub enum RepositoryError {
    #[error("Entity not found")]
    NotFound,

    #[error("Entity already exists: {0}")]
    AlreadyExists(String),

    #[error("Validation error: {0}")]
    ValidationError(String),

    #[error("Database error: {0}")]
    DatabaseError(String),

    #[error("Serialization error: {0}")]
    SerializationError(String),

    #[error("Conflict: {0}")]
    Conflict(String),

    #[error("Internal error: {0}")]
    InternalError(String),
}

impl From<serde_json::Error> for RepositoryError {
    fn from(e: serde_json::Error) -> Self {
        RepositoryError::SerializationError(e.to_string())
    }
}

#[cfg(feature = "postgres")]
impl From<sqlx::Error> for RepositoryError {
    fn from(e: sqlx::Error) -> Self {
        match e {
            sqlx::Error::RowNotFound => RepositoryError::NotFound,
            sqlx::Error::Database(db_err) => {
                let msg = db_err.message().to_string();
                if msg.contains("duplicate key") || msg.contains("unique constraint") {
                    RepositoryError::AlreadyExists(msg)
                } else {
                    RepositoryError::DatabaseError(msg)
                }
            }
            _ => RepositoryError::DatabaseError(e.to_string()),
        }
    }
}

// ============================================================
// Entity Traits
// ============================================================

/// Trait for entities that can be persisted.
///
/// This trait defines the common fields and behavior required by all entities
/// that can be stored and retrieved from a repository.
pub trait PersistentEntity: Clone + Send + Sync + Debug + Serialize + DeserializeOwned + 'static {
    /// Get the entity's unique identifier
    fn entity_id(&self) -> String;

    /// Set the entity's unique identifier
    fn set_entity_id(&mut self, id: String);

    /// Get creation timestamp
    fn created_at(&self) -> Option<DateTime<Utc>>;

    /// Set creation timestamp
    fn set_created_at(&mut self, ts: DateTime<Utc>);

    /// Get last update timestamp
    fn updated_at(&self) -> Option<DateTime<Utc>>;

    /// Set last update timestamp
    fn set_updated_at(&mut self, ts: DateTime<Utc>);

    /// Get soft delete timestamp (None if not deleted)
    fn deleted_at(&self) -> Option<DateTime<Utc>>;

    /// Set soft delete timestamp
    fn set_deleted_at(&mut self, ts: Option<DateTime<Utc>>);

    /// Check if entity is soft-deleted
    fn is_deleted(&self) -> bool {
        self.deleted_at().is_some()
    }

    /// Mark entity as deleted (soft delete)
    fn mark_deleted(&mut self) {
        self.set_deleted_at(Some(Utc::now()));
        self.set_updated_at(Utc::now());
    }

    /// Restore a soft-deleted entity
    fn restore(&mut self) {
        self.set_deleted_at(None);
        self.set_updated_at(Utc::now());
    }

    /// Touch the entity (update timestamp)
    fn touch(&mut self) {
        self.set_updated_at(Utc::now());
    }

    /// Generate a new ID for this entity type
    fn generate_id() -> String {
        uuid::Uuid::new_v4().to_string()
    }

    /// Fields that a generic write (PUT, PATCH and their bulk forms) may not
    /// change, by their serialized name.
    ///
    /// The generic service refuses a write that would give one of these a new
    /// value, and still accepts a write that carries the stored value
    /// unchanged, so a form that sends the whole record keeps working. Code
    /// that owns the field — a verb, a write service — changes it through its
    /// own path. `id` and `metadata` are refused for every entity regardless
    /// of this list. The schema generator fills it from the fields the schema
    /// declares as not freely writable; the default protects nothing more.
    fn write_protected_fields() -> &'static [&'static str] {
        &[]
    }
}

/// Trait for entities that support partial updates via field map
pub trait PartialUpdatable: PersistentEntity {
    /// Apply partial updates from a field map
    fn apply_partial_update(&mut self, fields: &HashMap<String, serde_json::Value>) -> Result<(), RepositoryError>;
}

/// Trait for entities with version/optimistic locking
pub trait Versioned {
    fn version(&self) -> u64;
    fn set_version(&mut self, version: u64);
    fn increment_version(&mut self) {
        self.set_version(self.version() + 1);
    }
}

// ============================================================
// Repository Traits
// ============================================================

/// Core CRUD repository trait
///
/// This trait defines the basic CRUD operations that all repositories must implement.
/// It's designed to work with the `CrudService` trait from the HTTP layer.
#[async_trait]
pub trait CrudRepository<E>: Send + Sync
where
    E: PersistentEntity,
{
    /// Create a new entity
    async fn create(&self, entity: E) -> Result<E, RepositoryError>;

    /// Find entity by ID (excluding soft-deleted)
    async fn find_by_id(&self, id: &str) -> Result<Option<E>, RepositoryError>;

    /// Find entity by ID (including soft-deleted, for trash operations)
    async fn find_by_id_including_deleted(&self, id: &str) -> Result<Option<E>, RepositoryError>;

    /// Update an existing entity
    async fn update(&self, entity: E) -> Result<E, RepositoryError>;

    /// Soft delete an entity
    async fn soft_delete(&self, id: &str) -> Result<bool, RepositoryError>;

    /// Restore a soft-deleted entity
    async fn restore(&self, id: &str) -> Result<Option<E>, RepositoryError>;

    /// Permanently delete an entity
    async fn hard_delete(&self, id: &str) -> Result<bool, RepositoryError>;

    /// List entities with pagination (excluding soft-deleted)
    async fn list(&self, page: u32, limit: u32) -> Result<(Vec<E>, u64), RepositoryError>;

    /// List soft-deleted entities with pagination
    async fn list_deleted(&self, page: u32, limit: u32) -> Result<(Vec<E>, u64), RepositoryError>;

    /// Count all entities (excluding soft-deleted)
    async fn count(&self) -> Result<u64, RepositoryError>;

    /// Count soft-deleted entities
    async fn count_deleted(&self) -> Result<u64, RepositoryError>;

    /// Bulk create entities
    async fn bulk_create(&self, entities: Vec<E>) -> Result<Vec<E>, RepositoryError>;

    /// Permanently delete all soft-deleted entities
    async fn empty_trash(&self) -> Result<u64, RepositoryError>;

    /// List entities with pagination and filters (excluding soft-deleted)
    ///
    /// Default implementation ignores filters and delegates to `list()`.
    /// Override in repository implementations that support filter pushdown.
    async fn list_filtered(
        &self,
        page: u32,
        limit: u32,
        filters: HashMap<String, String>,
    ) -> Result<(Vec<E>, u64), RepositoryError> {
        let _ = filters; // ignored by default
        self.list(page, limit).await
    }

    /// `list_filtered`, carrying the pagination info (cursor positions
    /// included) so the HTTP layer can surface keyset paging. Default: the
    /// tuple form with the cursor fields absent; the generated Postgres
    /// repositories override this with the real keyset walk.
    async fn list_filtered_with_info(
        &self,
        page: u32,
        limit: u32,
        filters: HashMap<String, String>,
    ) -> Result<(Vec<E>, backbone_orm::repository::PaginationInfo), RepositoryError> {
        let (rows, total) = self.list_filtered(page, limit, filters).await?;
        Ok((
            rows,
            backbone_orm::repository::PaginationInfo::new(page, limit, total),
        ))
    }

    /// Group and reduce entities under the same filters as `list_filtered`.
    ///
    /// There is deliberately no useful default. A repository that cannot group
    /// must SAY so: an honest error tells the caller its chart is unavailable,
    /// whereas a default returning zeros would render an empty chart that looks
    /// like a real answer about a real, empty table. The Postgres-backed
    /// generated repositories override this via `impl_crud_repository!`.
    /// The schema-qualified table this repository reads, when it knows it.
    ///
    /// The Postgres-backed generated repositories override this; anything that
    /// cannot name a table returns `None` and simply has no history.
    fn table_name(&self) -> Option<&str> {
        None
    }

    async fn aggregate_filtered(
        &self,
        spec: &backbone_orm::repository::AggregateSpec,
        filters: HashMap<String, String>,
    ) -> Result<backbone_orm::repository::AggregateResult, RepositoryError> {
        let _ = (spec, filters);
        Err(RepositoryError::DatabaseError(
            "aggregate is not supported by this repository".to_string(),
        ))
    }

    /// Hydrate `?include=` relations: fetch rows from `table` by id list, as JSON
    /// (raw `row_to_json`). `table` comes from `EntityRepoMeta::relations()`
    /// (generator-emitted), never client input. Default: no expansion. The
    /// Postgres-backed generated repos override this via `impl_crud_repository!`.
    async fn fetch_related_json(
        &self,
        _table: &str,
        _ids: &[String],
    ) -> Vec<serde_json::Value> {
        Vec::new()
    }

    /// Check if an entity exists by ID
    async fn exists(&self, id: &str) -> Result<bool, RepositoryError> {
        Ok(self.find_by_id(id).await?.is_some())
    }

    // ── Atomic batch operations ───────────────────────────────────────────────
    //
    // The default implementations loop over the single-row methods and are NOT
    // transactional — they exist so non-Postgres implementors (mocks, custom
    // adapters) keep compiling. The macro-generated repositories override these
    // (via `impl_crud_repository!`) with truly atomic, single-transaction
    // versions backed by `GenericCrudRepository`.

    /// Soft-delete many entities by id. Returns the number affected.
    async fn bulk_soft_delete(&self, ids: &[String]) -> Result<u64, RepositoryError> {
        let mut n = 0;
        for id in ids {
            if self.soft_delete(id).await? {
                n += 1;
            }
        }
        Ok(n)
    }

    /// Restore many soft-deleted entities by id. Returns the restored entities.
    async fn bulk_restore(&self, ids: &[String]) -> Result<Vec<E>, RepositoryError> {
        let mut out = Vec::with_capacity(ids.len());
        for id in ids {
            if let Some(e) = self.restore(id).await? {
                out.push(e);
            }
        }
        Ok(out)
    }

    /// Permanently delete many entities by id. Returns the number affected.
    async fn bulk_hard_delete(&self, ids: &[String]) -> Result<u64, RepositoryError> {
        let mut n = 0;
        for id in ids {
            if self.hard_delete(id).await? {
                n += 1;
            }
        }
        Ok(n)
    }

    /// Restore every soft-deleted entity. Returns the restored entities.
    async fn restore_all(&self) -> Result<Vec<E>, RepositoryError> {
        let mut restored = Vec::new();
        // Restoring removes rows from the deleted set, so page 1 always returns
        // the next batch of still-deleted rows until none remain.
        loop {
            let (batch, _) = self.list_deleted(1, 500).await?;
            if batch.is_empty() {
                break;
            }
            for entity in &batch {
                if let Some(e) = self.restore(&entity.entity_id()).await? {
                    restored.push(e);
                }
            }
        }
        Ok(restored)
    }

    /// Update many entities atomically. Returns the updated entities.
    async fn bulk_update(&self, entities: Vec<E>) -> Result<Vec<E>, RepositoryError> {
        let mut out = Vec::with_capacity(entities.len());
        for entity in entities {
            out.push(self.update(entity).await?);
        }
        Ok(out)
    }
}

/// Extended repository with search/filter capabilities
#[async_trait]
pub trait SearchableRepository<E>: CrudRepository<E>
where
    E: PersistentEntity,
{
    /// Search entities with filters
    async fn search(
        &self,
        filters: HashMap<String, String>,
        page: u32,
        limit: u32,
    ) -> Result<(Vec<E>, u64), RepositoryError>;

    /// Find by a specific field value
    async fn find_by_field(&self, field: &str, value: &str) -> Result<Option<E>, RepositoryError>;

    /// Find all by a specific field value
    async fn find_all_by_field(
        &self,
        field: &str,
        value: &str,
        page: u32,
        limit: u32,
    ) -> Result<(Vec<E>, u64), RepositoryError>;
}

// ============================================================
// PostgreSQL-Specific Traits
// ============================================================

#[cfg(feature = "postgres")]
pub use postgres_traits::*;

#[cfg(feature = "postgres")]
mod postgres_traits {
    use super::*;
    use sqlx::postgres::PgRow;
    use sqlx::FromRow;

    /// Trait for mapping entities to/from PostgreSQL rows
    ///
    /// Implement this trait to enable automatic PostgreSQL persistence for your entity.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use backbone_core::persistence::{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 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 update_columns() -> &'static [&'static str] {
    ///         &["name", "email", "updated_at"]
    ///     }
    ///     fn bind_for_insert(entity: &Self, query: Query<'_, ...>) -> Query<'_, ...> {
    ///         query.bind(&entity.id).bind(&entity.name).bind(&entity.email)
    ///             .bind(&entity.created_at).bind(&entity.updated_at)
    ///     }
    /// }
    /// ```
    pub trait PostgresEntity: PersistentEntity + for<'r> FromRow<'r, PgRow> + Unpin {
        /// Table name for this entity
        fn table_name() -> &'static str;

        /// Primary key column name (default: "id")
        fn id_column() -> &'static str {
            "id"
        }

        /// Column names for SELECT queries (excluding computed columns)
        fn select_columns() -> &'static [&'static str];

        /// Column names for INSERT (all columns that should be inserted)
        fn insert_columns() -> &'static [&'static str];

        /// Column names for UPDATE (columns that can be updated, excluding id)
        fn update_columns() -> &'static [&'static str] {
            Self::insert_columns()
        }

        /// Bind entity values to a query for INSERT
        ///
        /// The order must match insert_columns()
        fn bind_for_insert<'q>(
            entity: &'q Self,
            query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
        ) -> sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>;

        /// Bind entity values to a query for UPDATE
        ///
        /// The order must match update_columns()
        fn bind_for_update<'q>(
            entity: &'q Self,
            query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
        ) -> sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments> {
            // Default: same as insert (override if different)
            Self::bind_for_insert(entity, query)
        }

        /// Build SELECT by ID query
        fn select_by_id_query() -> String {
            format!(
                "SELECT {} FROM {} WHERE {} = $1 AND deleted_at IS NULL",
                Self::select_columns().join(", "),
                Self::table_name(),
                Self::id_column()
            )
        }

        /// Build SELECT by ID including deleted
        fn select_by_id_including_deleted_query() -> String {
            format!(
                "SELECT {} FROM {} WHERE {} = $1",
                Self::select_columns().join(", "),
                Self::table_name(),
                Self::id_column()
            )
        }

        /// Build paginated list query
        fn list_query() -> String {
            format!(
                "SELECT {} FROM {} WHERE deleted_at IS NULL ORDER BY created_at DESC LIMIT $1 OFFSET $2",
                Self::select_columns().join(", "),
                Self::table_name()
            )
        }

        /// Build count query
        fn count_query() -> String {
            format!(
                "SELECT COUNT(*) FROM {} WHERE deleted_at IS NULL",
                Self::table_name()
            )
        }

        /// Build list deleted (trash) query
        fn list_deleted_query() -> String {
            format!(
                "SELECT {} FROM {} WHERE deleted_at IS NOT NULL ORDER BY deleted_at DESC LIMIT $1 OFFSET $2",
                Self::select_columns().join(", "),
                Self::table_name()
            )
        }

        /// Build count deleted query
        fn count_deleted_query() -> String {
            format!(
                "SELECT COUNT(*) FROM {} WHERE deleted_at IS NOT NULL",
                Self::table_name()
            )
        }

        /// Build soft delete query
        fn soft_delete_query() -> String {
            format!(
                "UPDATE {} SET deleted_at = NOW(), updated_at = NOW() WHERE {} = $1 AND deleted_at IS NULL",
                Self::table_name(),
                Self::id_column()
            )
        }

        /// Build restore query
        fn restore_query() -> String {
            format!(
                "UPDATE {} SET deleted_at = NULL, updated_at = NOW() WHERE {} = $1 AND deleted_at IS NOT NULL RETURNING {}",
                Self::table_name(),
                Self::id_column(),
                Self::select_columns().join(", ")
            )
        }

        /// Build hard delete query
        fn hard_delete_query() -> String {
            format!(
                "DELETE FROM {} WHERE {} = $1",
                Self::table_name(),
                Self::id_column()
            )
        }

        /// Build empty trash query
        fn empty_trash_query() -> String {
            format!(
                "DELETE FROM {} WHERE deleted_at IS NOT NULL",
                Self::table_name()
            )
        }
    }
}