elif_orm/model/extensions.rs
1//! Model Extensions - Additional utility methods for models
2//!
3//! Provides convenience methods for model instances including refresh,
4//! existence checks, save operations, and transaction support.
5
6use sqlx::Pool;
7
8use crate::error::{ModelError, ModelResult};
9use crate::model::core_trait::Model;
10use crate::model::crud_operations::CrudOperations;
11
12// <<<ELIF:BEGIN agent-editable:model_extensions>>>
13/// Extension trait for models with additional utility methods
14#[allow(async_fn_in_trait)]
15pub trait ModelExtensions: Model + CrudOperations {
16 /// Refresh this model instance from the database
17 async fn refresh(&mut self, pool: &Pool<sqlx::Postgres>) -> ModelResult<()>
18 where
19 Self: Sized,
20 {
21 if let Some(pk) = self.primary_key() {
22 if let Some(refreshed) = Self::find(pool, pk).await? {
23 *self = refreshed;
24 Ok(())
25 } else {
26 Err(ModelError::NotFound(Self::table_name().to_string()))
27 }
28 } else {
29 Err(ModelError::MissingPrimaryKey)
30 }
31 }
32
33 /// Check if this model instance exists in the database
34 async fn exists(&self, pool: &Pool<sqlx::Postgres>) -> ModelResult<bool>
35 where
36 Self: Sized,
37 {
38 if let Some(pk) = self.primary_key() {
39 let exists = Self::find(pool, pk).await?.is_some();
40 Ok(exists)
41 } else {
42 Ok(false)
43 }
44 }
45
46 async fn save(&mut self, pool: &Pool<sqlx::Postgres>) -> ModelResult<()>
47 where
48 Self: Sized + Clone,
49 {
50 if self.primary_key().is_some() && self.exists(pool).await? {
51 // Update existing record
52 self.update(pool).await
53 } else {
54 // Create a new record. `create` takes ownership, so we clone.
55 let new_model = Self::create(pool, self.clone()).await?;
56 // Update self with the state from the database, including the new primary key.
57 *self = new_model;
58 Ok(())
59 }
60 }
61
62 /// Create a clone of this model without the primary key (for duplication)
63 fn duplicate(&self) -> Self
64 where
65 Self: Sized + Clone,
66 {
67 let mut cloned = self.clone();
68 cloned.set_primary_key(Self::PrimaryKey::default());
69
70 // Reset timestamps for new record
71 if Self::uses_timestamps() {
72 cloned.set_created_at(chrono::Utc::now());
73 cloned.set_updated_at(chrono::Utc::now());
74 }
75
76 // Reset soft delete status
77 if Self::uses_soft_deletes() {
78 cloned.set_deleted_at(None);
79 }
80
81 cloned
82 }
83
84 // <<<ELIF:BEGIN agent-editable:transaction_methods>>>
85 // Transaction-scoped operations (placeholders for future implementation)
86
87 /// Placeholder for transaction-scoped model operations
88 /// Will be fully implemented when derive macros are available
89 fn supports_transactions() -> bool
90 where
91 Self: Sized,
92 {
93 true // Basic transaction support is available via the transaction module
94 }
95
96 /// Check if this model has been modified since last save/load
97 /// Default implementation always returns true - override for dirty tracking
98 fn is_dirty(&self) -> bool {
99 true
100 }
101
102 /// Mark all fields as clean (not dirty) after save operations
103 /// Default implementation is a no-op - override for dirty tracking
104 fn mark_clean(&mut self) {}
105
106 /// Get list of modified fields since last save/load
107 /// Default implementation returns empty - override for dirty tracking
108 fn dirty_fields(&self) -> Vec<&str> {
109 vec![]
110 }
111 // <<<ELIF:END agent-editable:transaction_methods>>>
112}
113
114// Implement ModelExtensions for all types that implement Model + CrudOperations
115impl<T: Model + CrudOperations> ModelExtensions for T {}
116// <<<ELIF:END agent-editable:model_extensions>>>