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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Trait for type-safe field selectors
///
/// This trait is automatically implemented for field selector structs generated
/// by the `#[model(...)]` macro (e.g., `UserFields`).
pub trait FieldSelector: Clone {
/// Set table alias for all fields
///
/// This is used for self-joins where the same table appears multiple times
/// with different aliases.
fn with_alias(self, alias: &str) -> Self;
}
/// Core trait for database models
/// Uses composition instead of inheritance - models can implement multiple traits
///
/// # Breaking Change (Phase 4)
///
/// A new associated type `Fields` has been added. It provides a type-safe field selector.
/// When using the `#[model(...)]` macro, this implementation is automatically generated.
pub trait Model: Serialize + for<'de> Deserialize<'de> + Send + Sync + Clone {
/// The primary key type
type PrimaryKey: Send + Sync + Clone + std::fmt::Display;
/// Type-safe field selector
///
/// This type is automatically generated by the `#[model(...)]` macro as `{Model}Fields`.
/// It provides compile-time type safety for field references in queries.
type Fields: FieldSelector;
/// Get the table name
fn table_name() -> &'static str;
/// Create a new field selector instance
///
/// This method is automatically implemented by the `#[model(...)]` macro.
/// It returns a new instance of the type-safe field selector.
fn new_fields() -> Self::Fields;
/// Get the app label for this model
///
/// This is used by the migration system to organize models by application.
/// Defaults to "default" if not specified.
fn app_label() -> &'static str {
"default"
}
/// Get the primary key field name
fn primary_key_field() -> &'static str {
"id"
}
/// Get the primary key value
///
/// Returns an owned copy of the primary key. For composite primary keys,
/// this constructs a new PK value from the component fields.
fn primary_key(&self) -> Option<Self::PrimaryKey>;
/// Set the primary key value
fn set_primary_key(&mut self, value: Self::PrimaryKey);
/// Get composite primary key definition if this model uses composite PK
///
/// Returns None for single primary key models, Some(CompositePrimaryKey) for composite PK models.
fn composite_primary_key() -> Option<super::composite_pk::CompositePrimaryKey> {
None
}
/// Get composite primary key values for this instance
///
/// Only meaningful for models with composite primary keys.
/// Returns empty HashMap for single primary key models.
fn get_composite_pk_values(&self) -> HashMap<String, super::composite_pk::PkValue> {
HashMap::new()
}
/// Get field metadata for inspection
///
/// This method should be implemented to provide introspection capabilities.
/// By default, returns an empty vector. Override this in derive macros or
/// manual implementations to provide actual field metadata.
///
/// # Examples
///
/// ```ignore
/// use reinhardt_db::orm::Model;
///
/// struct User {
/// id: i32,
/// name: String,
/// }
///
/// impl Model for User {
/// // ... other required methods ...
///
/// fn field_metadata() -> Vec<super::inspection::FieldInfo> {
/// vec![
/// // Field metadata would be generated here
/// ]
/// }
/// }
/// ```
fn field_metadata() -> Vec<super::inspection::FieldInfo> {
Vec::new()
}
/// Get relationship metadata for inspection
///
/// This method should be implemented to provide relationship introspection.
/// By default, returns an empty vector. Override this in derive macros or
/// manual implementations to provide actual relationship metadata.
fn relationship_metadata() -> Vec<super::inspection::RelationInfo> {
Vec::new()
}
/// Get index metadata for inspection
///
/// This method should be implemented to provide index introspection.
/// By default, returns an empty vector. Override this in derive macros or
/// manual implementations to provide actual index metadata.
fn index_metadata() -> Vec<super::inspection::IndexInfo> {
Vec::new()
}
/// Get constraint metadata for inspection
///
/// This method should be implemented to provide constraint introspection.
/// By default, returns an empty vector. Override this in derive macros or
/// manual implementations to provide actual constraint metadata.
fn constraint_metadata() -> Vec<super::inspection::ConstraintInfo> {
Vec::new()
}
/// Django-style objects manager accessor
///
/// Returns a new Manager instance for this model type.
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_db::orm::Model;
/// use serde::{Serialize, Deserialize};
/// # #[derive(Debug, Clone, Serialize, Deserialize)]
/// # struct MyModel { id: Option<i64> }
/// # #[derive(Clone)]
/// # struct MyModelFields;
/// # impl reinhardt_db::orm::model::FieldSelector for MyModelFields {
/// # fn with_alias(self, _alias: &str) -> Self { self }
/// # }
/// # impl Model for MyModel {
/// # type PrimaryKey = i64;
/// # type Fields = MyModelFields;
/// # fn app_label() -> &'static str { "app" }
/// # fn table_name() -> &'static str { "table" }
/// # fn new_fields() -> Self::Fields { MyModelFields }
/// # fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id.clone() }
/// # fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
/// # fn primary_key_field() -> &'static str { "id" }
/// # }
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let manager = MyModel::objects();
/// let all_records = manager.all().all().await?;
/// # Ok(())
/// # }
/// ```
fn objects() -> super::Manager<Self>
where
Self: Sized,
{
super::Manager::new()
}
/// Save the model instance to the database with event dispatching
///
/// If the primary key is None, performs an INSERT and dispatches before_insert/after_insert events.
/// If the primary key is Some, performs an UPDATE and dispatches before_update/after_update events.
///
/// Event listeners can veto the operation by returning `EventResult::Veto`.
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_db::orm::Model;
/// use serde::{Serialize, Deserialize};
/// # #[derive(Debug, Clone, Serialize, Deserialize)]
/// # struct User { id: Option<i64>, name: String }
/// # #[derive(Clone)]
/// # struct UserFields;
/// # impl reinhardt_db::orm::model::FieldSelector for UserFields {
/// # fn with_alias(self, _alias: &str) -> Self { self }
/// # }
/// # impl Model for User {
/// # type PrimaryKey = i64;
/// # type Fields = UserFields;
/// # fn app_label() -> &'static str { "app" }
/// # fn table_name() -> &'static str { "users" }
/// # fn new_fields() -> Self::Fields { UserFields }
/// # fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id.clone() }
/// # fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
/// # fn primary_key_field() -> &'static str { "id" }
/// # }
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut user = User { id: None, name: "John".to_string() };
///
/// // INSERT - triggers before_insert/after_insert events
/// user.save().await?;
///
/// // UPDATE - triggers before_update/after_update events
/// user.name = "Jane".to_string();
/// user.save().await?;
/// # Ok(())
/// # }
/// ```
fn save(
&mut self,
) -> impl std::future::Future<Output = reinhardt_core::exception::Result<()>> + Send
where
Self: Sized,
{
async move {
use super::events::{EventResult, get_active_registry};
use super::manager::get_connection;
let registry = get_active_registry();
let conn = get_connection().await?;
let manager = super::Manager::<Self>::new();
let json = serde_json::to_value(&*self)
.map_err(|e| reinhardt_core::exception::Error::Database(e.to_string()))?;
if self.primary_key().is_none() {
// INSERT: new record
let instance_id = format!("{}-new-{}", Self::table_name(), uuid::Uuid::now_v7());
// Dispatch before_insert event if registry is active
if let Some(ref reg) = registry {
let result = reg
.dispatch_before_insert(Self::table_name(), &instance_id, &json)
.await;
if result == EventResult::Veto {
return Err(reinhardt_core::exception::Error::Database(
"Insert operation vetoed by event listener".to_string(),
));
}
}
// Perform the INSERT
let created = manager.create_with_conn(&conn, self).await?;
*self = created;
// Dispatch after_insert event if registry is active
if let Some(ref reg) = registry {
let final_id = format!(
"{}-{}",
Self::table_name(),
self.primary_key()
.map(|pk| pk.to_string())
.unwrap_or_default()
);
reg.dispatch_after_insert(Self::table_name(), &final_id)
.await;
}
} else {
// UPDATE: existing record
let instance_id = format!(
"{}-{}",
Self::table_name(),
self.primary_key()
.map(|pk| pk.to_string())
.unwrap_or_default()
);
// Dispatch before_update event if registry is active
if let Some(ref reg) = registry {
let result = reg
.dispatch_before_update(Self::table_name(), &instance_id, &json)
.await;
if result == EventResult::Veto {
return Err(reinhardt_core::exception::Error::Database(
"Update operation vetoed by event listener".to_string(),
));
}
}
// Perform the UPDATE
let updated = manager.update_with_conn(&conn, self).await?;
*self = updated;
// Dispatch after_update event if registry is active
if let Some(ref reg) = registry {
reg.dispatch_after_update(Self::table_name(), &instance_id)
.await;
}
}
Ok(())
}
}
/// Delete the model instance from the database with event dispatching
///
/// Dispatches before_delete/after_delete events. Event listeners can veto
/// the operation by returning `EventResult::Veto`.
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_db::orm::Model;
/// use serde::{Serialize, Deserialize};
/// # #[derive(Debug, Clone, Serialize, Deserialize)]
/// # struct User { id: Option<i64>, name: String }
/// # #[derive(Clone)]
/// # struct UserFields;
/// # impl reinhardt_db::orm::model::FieldSelector for UserFields {
/// # fn with_alias(self, _alias: &str) -> Self { self }
/// # }
/// # impl Model for User {
/// # type PrimaryKey = i64;
/// # type Fields = UserFields;
/// # fn app_label() -> &'static str { "app" }
/// # fn table_name() -> &'static str { "users" }
/// # fn new_fields() -> Self::Fields { UserFields }
/// # fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id.clone() }
/// # fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
/// # fn primary_key_field() -> &'static str { "id" }
/// # }
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut user = User { id: Some(1), name: "John".to_string() };
///
/// // Triggers before_delete/after_delete events
/// user.delete().await?;
/// # Ok(())
/// # }
/// ```
fn delete(
&self,
) -> impl std::future::Future<Output = reinhardt_core::exception::Result<()>> + Send
where
Self: Sized,
{
async move {
use super::events::{EventResult, get_active_registry};
use super::manager::get_connection;
let pk = self.primary_key().ok_or_else(|| {
reinhardt_core::exception::Error::Database(
"Cannot delete model without primary key".to_string(),
)
})?;
let conn = get_connection().await?;
let manager = super::Manager::<Self>::new();
let instance_id = format!("{}-{}", Self::table_name(), pk);
// Dispatch before_delete event if registry is available
if let Some(registry) = get_active_registry() {
let result = registry
.dispatch_before_delete(Self::table_name(), &instance_id)
.await;
if result == EventResult::Veto {
return Err(reinhardt_core::exception::Error::Database(
"Delete operation vetoed by event listener".to_string(),
));
}
}
// Perform the DELETE
manager.delete_with_conn(&conn, pk.clone()).await?;
// Dispatch after_delete event if registry is available
if let Some(registry) = get_active_registry() {
registry
.dispatch_after_delete(Self::table_name(), &instance_id)
.await;
}
Ok(())
}
}
}
/// Trait for models with timestamps - compose this with Model
/// This follows Rust's composition pattern rather than Django's inheritance
pub trait Timestamped {
/// Returns the creation timestamp.
fn created_at(&self) -> chrono::DateTime<chrono::Utc>;
/// Returns the last update timestamp.
fn updated_at(&self) -> chrono::DateTime<chrono::Utc>;
/// Sets the last update timestamp.
fn set_updated_at(&mut self, time: chrono::DateTime<chrono::Utc>);
}
/// Trait for soft-deletable models
/// Another composition trait instead of inheritance
pub trait SoftDeletable {
/// Returns the deletion timestamp, or `None` if not deleted.
fn deleted_at(&self) -> Option<chrono::DateTime<chrono::Utc>>;
/// Sets the deletion timestamp, or `None` to restore.
fn set_deleted_at(&mut self, time: Option<chrono::DateTime<chrono::Utc>>);
/// Returns whether the model has been soft-deleted.
fn is_deleted(&self) -> bool {
self.deleted_at().is_some()
}
}
/// Common timestamp fields that can be composed into structs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Timestamps {
/// The created at.
pub created_at: chrono::DateTime<chrono::Utc>,
/// The updated at.
pub updated_at: chrono::DateTime<chrono::Utc>,
}
impl Timestamps {
/// Creates a new Timestamps instance with current time
///
/// # Examples
///
/// ```
/// use reinhardt_db::orm::model::Timestamps;
///
/// let timestamps = Timestamps::now();
/// assert!(timestamps.created_at <= chrono::Utc::now());
/// assert!(timestamps.updated_at <= chrono::Utc::now());
/// ```
pub fn now() -> Self {
let now = chrono::Utc::now();
Self {
created_at: now,
updated_at: now,
}
}
/// Updates the updated_at timestamp to current time
///
/// # Examples
///
/// ```
/// use reinhardt_db::orm::model::Timestamps;
/// use chrono::Utc;
///
/// let mut timestamps = Timestamps::now();
/// let old_updated = timestamps.updated_at;
///
/// // Wait a small amount to ensure time difference
/// std::thread::sleep(std::time::Duration::from_millis(1));
/// timestamps.touch();
///
/// assert!(timestamps.updated_at > old_updated);
/// ```
pub fn touch(&mut self) {
self.updated_at = chrono::Utc::now();
}
}
/// Soft delete field that can be composed into structs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SoftDelete {
/// The deleted at.
pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,
}
impl SoftDelete {
/// Creates a new SoftDelete instance with no deletion timestamp
///
/// # Examples
///
/// ```
/// use reinhardt_db::orm::model::SoftDelete;
///
/// let soft_delete = SoftDelete::new();
/// assert!(soft_delete.deleted_at.is_none());
/// ```
pub fn new() -> Self {
Self { deleted_at: None }
}
/// Marks the record as deleted by setting the deletion timestamp
///
/// # Examples
///
/// ```
/// use reinhardt_db::orm::model::SoftDelete;
///
/// let mut soft_delete = SoftDelete::new();
/// assert!(!soft_delete.is_deleted());
///
/// soft_delete.delete();
/// assert!(soft_delete.is_deleted());
/// assert!(soft_delete.deleted_at.is_some());
/// ```
pub fn delete(&mut self) {
self.deleted_at = Some(chrono::Utc::now());
}
/// Restores a soft-deleted record by clearing the deletion timestamp
///
/// # Examples
///
/// ```
/// use reinhardt_db::orm::model::SoftDelete;
///
/// let mut soft_delete = SoftDelete::new();
/// soft_delete.delete();
/// assert!(soft_delete.is_deleted());
///
/// soft_delete.restore();
/// assert!(!soft_delete.is_deleted());
/// assert!(soft_delete.deleted_at.is_none());
/// ```
pub fn restore(&mut self) {
self.deleted_at = None;
}
/// Check if the record is soft-deleted
pub fn is_deleted(&self) -> bool {
self.deleted_at.is_some()
}
}
impl Default for SoftDelete {
fn default() -> Self {
Self::new()
}
}