elif-orm 0.7.1

Production-ready ORM with migrations, database services, connection pooling, and query builder
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
//! Relationship Registry - Runtime metadata storage and access system

use dashmap::DashMap;
use std::collections::HashMap;
use std::sync::Arc;

use super::metadata::{RelationshipMetadata, RelationshipType};
use crate::error::{ModelError, ModelResult};

/// Thread-safe relationship registry for storing and accessing metadata at runtime
#[derive(Debug, Clone)]
pub struct RelationshipRegistry {
    /// Map of model name -> relationship name -> metadata
    relationships: Arc<DashMap<String, HashMap<String, RelationshipMetadata>>>,

    /// Reverse lookup: foreign key table -> local table -> relationship metadata
    foreign_key_index: Arc<DashMap<String, HashMap<String, Vec<RelationshipMetadata>>>>,

    /// Index of polymorphic relationships by morph name
    polymorphic_index: Arc<DashMap<String, Vec<RelationshipMetadata>>>,

    /// Eager loading relationships index
    eager_index: Arc<DashMap<String, Vec<String>>>,
}

impl Default for RelationshipRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl RelationshipRegistry {
    /// Create a new empty relationship registry
    pub fn new() -> Self {
        Self {
            relationships: Arc::new(DashMap::new()),
            foreign_key_index: Arc::new(DashMap::new()),
            polymorphic_index: Arc::new(DashMap::new()),
            eager_index: Arc::new(DashMap::new()),
        }
    }

    /// Register a relationship for a model
    pub fn register(
        &self,
        model_name: &str,
        relationship_name: &str,
        metadata: RelationshipMetadata,
    ) -> ModelResult<()> {
        // Validate metadata before registration
        metadata.validate()?;

        // Insert into main registry
        let mut model_relationships = self
            .relationships
            .entry(model_name.to_string())
            .or_default();

        model_relationships.insert(relationship_name.to_string(), metadata.clone());

        // Update foreign key index for reverse lookups
        self.update_foreign_key_index(&metadata);

        // Update polymorphic index if applicable
        if metadata.relationship_type.is_polymorphic() {
            if let Some(ref poly_config) = metadata.polymorphic_config {
                let mut poly_relationships = self
                    .polymorphic_index
                    .entry(poly_config.name.clone())
                    .or_default();
                poly_relationships.push(metadata.clone());
            }
        }

        // Update eager loading index
        if metadata.eager_load {
            let mut eager_relationships =
                self.eager_index.entry(model_name.to_string()).or_default();
            eager_relationships.push(relationship_name.to_string());
        }

        Ok(())
    }

    /// Get relationship metadata by model and relationship name
    pub fn get(&self, model_name: &str, relationship_name: &str) -> Option<RelationshipMetadata> {
        self.relationships
            .get(model_name)?
            .get(relationship_name)
            .cloned()
    }

    /// Get all relationships for a model
    pub fn get_all_for_model(
        &self,
        model_name: &str,
    ) -> Option<HashMap<String, RelationshipMetadata>> {
        self.relationships
            .get(model_name)
            .map(|entry| entry.clone())
    }

    /// Check if a relationship exists
    pub fn has_relationship(&self, model_name: &str, relationship_name: &str) -> bool {
        self.relationships
            .get(model_name)
            .map(|relationships| relationships.contains_key(relationship_name))
            .unwrap_or(false)
    }

    /// Get all relationship names for a model
    pub fn get_relationship_names(&self, model_name: &str) -> Vec<String> {
        self.relationships
            .get(model_name)
            .map(|relationships| relationships.keys().cloned().collect())
            .unwrap_or_default()
    }

    /// Get eager loading relationships for a model
    pub fn get_eager_relationships(&self, model_name: &str) -> Vec<String> {
        self.eager_index
            .get(model_name)
            .map(|relationships| relationships.clone())
            .unwrap_or_default()
    }

    /// Find relationships that reference a specific foreign table
    pub fn find_by_foreign_table(&self, foreign_table: &str) -> Vec<RelationshipMetadata> {
        let mut results = Vec::new();

        for entry in self.relationships.iter() {
            for metadata in entry.value().values() {
                if metadata.foreign_key.table == foreign_table
                    || metadata.related_table == foreign_table
                {
                    results.push(metadata.clone());
                }
            }
        }

        results
    }

    /// Find inverse relationships for a given relationship
    pub fn find_inverse_relationships(
        &self,
        model_name: &str,
        relationship_name: &str,
    ) -> Vec<(String, String, RelationshipMetadata)> {
        let Some(metadata) = self.get(model_name, relationship_name) else {
            return Vec::new();
        };

        let mut inverses = Vec::new();

        // Look for relationships in the related model that point back to this model
        if let Some(related_relationships) = self.get_all_for_model(&metadata.related_model) {
            for (rel_name, rel_metadata) in related_relationships {
                if self.is_inverse_relationship(&metadata, &rel_metadata) {
                    inverses.push((metadata.related_model.clone(), rel_name, rel_metadata));
                }
            }
        }

        inverses
    }

    /// Get polymorphic relationships by morph name
    pub fn get_polymorphic_relationships(&self, morph_name: &str) -> Vec<RelationshipMetadata> {
        self.polymorphic_index
            .get(morph_name)
            .map(|relationships| relationships.clone())
            .unwrap_or_default()
    }

    /// Get statistics about the registry
    pub fn stats(&self) -> RegistryStats {
        let total_models = self.relationships.len();
        let total_relationships: usize = self
            .relationships
            .iter()
            .map(|entry| entry.value().len())
            .sum();

        let eager_relationships: usize = self
            .eager_index
            .iter()
            .map(|entry| entry.value().len())
            .sum();

        let polymorphic_relationships: usize = self
            .polymorphic_index
            .iter()
            .map(|entry| entry.value().len())
            .sum();

        let relationship_type_counts = self.count_relationship_types();

        RegistryStats {
            total_models,
            total_relationships,
            eager_relationships,
            polymorphic_relationships,
            relationship_type_counts,
        }
    }

    /// Clear all registered relationships
    pub fn clear(&self) {
        self.relationships.clear();
        self.foreign_key_index.clear();
        self.polymorphic_index.clear();
        self.eager_index.clear();
    }

    /// Validate all registered relationships
    pub fn validate_all(&self) -> ModelResult<()> {
        for model_entry in self.relationships.iter() {
            for (relationship_name, metadata) in model_entry.value() {
                metadata.validate().map_err(|e| {
                    ModelError::Configuration(format!(
                        "Validation failed for relationship '{}' in model '{}': {}",
                        relationship_name,
                        model_entry.key(),
                        e
                    ))
                })?;
            }
        }
        Ok(())
    }

    /// Update the foreign key index for efficient reverse lookups
    fn update_foreign_key_index(&self, metadata: &RelationshipMetadata) {
        let foreign_table = &metadata.foreign_key.table;
        let local_table = &metadata.related_table;

        let mut foreign_key_relationships = self
            .foreign_key_index
            .entry(foreign_table.clone())
            .or_default();

        let relationships = foreign_key_relationships
            .entry(local_table.clone())
            .or_default();

        relationships.push(metadata.clone());
    }

    /// Check if two relationships are inverses of each other
    fn is_inverse_relationship(
        &self,
        rel1: &RelationshipMetadata,
        rel2: &RelationshipMetadata,
    ) -> bool {
        // Basic inverse detection - can be enhanced
        match (rel1.relationship_type, rel2.relationship_type) {
            (RelationshipType::HasOne, RelationshipType::BelongsTo)
            | (RelationshipType::BelongsTo, RelationshipType::HasOne)
            | (RelationshipType::HasMany, RelationshipType::BelongsTo)
            | (RelationshipType::BelongsTo, RelationshipType::HasMany) => {
                // Check if foreign keys match appropriately
                rel1.foreign_key.primary_column() == rel2.foreign_key.primary_column()
            }
            (RelationshipType::ManyToMany, RelationshipType::ManyToMany) => {
                // For many-to-many, check if they use the same pivot table
                match (&rel1.pivot_config, &rel2.pivot_config) {
                    (Some(pivot1), Some(pivot2)) => pivot1.table == pivot2.table,
                    _ => false,
                }
            }
            _ => false,
        }
    }

    /// Count relationships by type
    fn count_relationship_types(&self) -> HashMap<RelationshipType, usize> {
        let mut counts = HashMap::new();

        for model_entry in self.relationships.iter() {
            for metadata in model_entry.value().values() {
                *counts.entry(metadata.relationship_type).or_insert(0) += 1;
            }
        }

        counts
    }
}

/// Statistics about the relationship registry
#[derive(Debug, Clone)]
pub struct RegistryStats {
    pub total_models: usize,
    pub total_relationships: usize,
    pub eager_relationships: usize,
    pub polymorphic_relationships: usize,
    pub relationship_type_counts: HashMap<RelationshipType, usize>,
}

impl RegistryStats {
    /// Get the most common relationship type
    pub fn most_common_relationship_type(&self) -> Option<(RelationshipType, usize)> {
        self.relationship_type_counts
            .iter()
            .max_by_key(|(_, count)| *count)
            .map(|(rel_type, count)| (*rel_type, *count))
    }

    /// Calculate the percentage of eager relationships
    pub fn eager_relationship_percentage(&self) -> f64 {
        if self.total_relationships == 0 {
            0.0
        } else {
            (self.eager_relationships as f64 / self.total_relationships as f64) * 100.0
        }
    }
}

/// Global registry instance for the application
static GLOBAL_REGISTRY: std::sync::OnceLock<RelationshipRegistry> = std::sync::OnceLock::new();

/// Get the global relationship registry
pub fn global_registry() -> &'static RelationshipRegistry {
    GLOBAL_REGISTRY.get_or_init(RelationshipRegistry::new)
}

/// Convenience macro for registering relationships
#[macro_export]
macro_rules! register_relationship {
    ($model:expr, $name:expr, $metadata:expr) => {
        $crate::relationships::registry::global_registry()
            .register($model, $name, $metadata)
            .expect("Failed to register relationship");
    };
}

#[cfg(test)]
mod tests {
    use super::super::metadata::*;
    use super::*;

    fn create_test_metadata(name: &str, rel_type: RelationshipType) -> RelationshipMetadata {
        RelationshipMetadata::new(
            rel_type,
            name.to_string(),
            format!("{}_table", name),
            format!("{}Model", name),
            ForeignKeyConfig::simple(format!("{}_id", name), format!("{}_table", name)),
        )
    }

    #[test]
    fn test_registry_creation() {
        let registry = RelationshipRegistry::new();
        assert_eq!(registry.stats().total_models, 0);
        assert_eq!(registry.stats().total_relationships, 0);
    }

    #[test]
    fn test_relationship_registration() {
        let registry = RelationshipRegistry::new();
        let metadata = create_test_metadata("posts", RelationshipType::HasMany);

        assert!(registry.register("User", "posts", metadata.clone()).is_ok());
        assert!(registry.has_relationship("User", "posts"));
        assert_eq!(registry.get("User", "posts"), Some(metadata));
    }

    #[test]
    fn test_relationship_not_found() {
        let registry = RelationshipRegistry::new();
        assert!(!registry.has_relationship("User", "nonexistent"));
        assert!(registry.get("User", "nonexistent").is_none());
    }

    #[test]
    fn test_eager_relationships() {
        let registry = RelationshipRegistry::new();
        let mut metadata = create_test_metadata("profile", RelationshipType::HasOne);
        metadata.eager_load = true;

        registry.register("User", "profile", metadata).unwrap();

        let eager_relationships = registry.get_eager_relationships("User");
        assert_eq!(eager_relationships, vec!["profile"]);
    }

    #[test]
    fn test_polymorphic_relationships() {
        let registry = RelationshipRegistry::new();
        let mut metadata = create_test_metadata("comments", RelationshipType::MorphMany);
        metadata.polymorphic_config = Some(PolymorphicConfig::new(
            "commentable".to_string(),
            "commentable_type".to_string(),
            "commentable_id".to_string(),
        ));

        registry.register("Post", "comments", metadata).unwrap();

        let poly_relationships = registry.get_polymorphic_relationships("commentable");
        assert_eq!(poly_relationships.len(), 1);
    }

    #[test]
    fn test_find_by_foreign_table() {
        let registry = RelationshipRegistry::new();
        let metadata = create_test_metadata("user", RelationshipType::BelongsTo);

        registry.register("Post", "user", metadata).unwrap();

        let found = registry.find_by_foreign_table("user_table");
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "user");
    }

    #[test]
    fn test_registry_stats() {
        let registry = RelationshipRegistry::new();

        let posts_metadata = create_test_metadata("posts", RelationshipType::HasMany);
        let profile_metadata = create_test_metadata("profile", RelationshipType::HasOne);
        let mut eager_metadata = create_test_metadata("comments", RelationshipType::HasMany);
        eager_metadata.eager_load = true;

        registry.register("User", "posts", posts_metadata).unwrap();
        registry
            .register("User", "profile", profile_metadata)
            .unwrap();
        registry
            .register("User", "comments", eager_metadata)
            .unwrap();

        let stats = registry.stats();
        assert_eq!(stats.total_models, 1);
        assert_eq!(stats.total_relationships, 3);
        assert_eq!(stats.eager_relationships, 1);

        let most_common = stats.most_common_relationship_type();
        assert_eq!(most_common, Some((RelationshipType::HasMany, 2)));

        assert!(stats.eager_relationship_percentage() > 30.0);
    }

    #[test]
    fn test_all_relationships_for_model() {
        let registry = RelationshipRegistry::new();

        let posts_metadata = create_test_metadata("posts", RelationshipType::HasMany);
        let profile_metadata = create_test_metadata("profile", RelationshipType::HasOne);

        registry.register("User", "posts", posts_metadata).unwrap();
        registry
            .register("User", "profile", profile_metadata)
            .unwrap();

        let all_relationships = registry.get_all_for_model("User").unwrap();
        assert_eq!(all_relationships.len(), 2);
        assert!(all_relationships.contains_key("posts"));
        assert!(all_relationships.contains_key("profile"));
    }

    #[test]
    fn test_relationship_names() {
        let registry = RelationshipRegistry::new();

        let posts_metadata = create_test_metadata("posts", RelationshipType::HasMany);
        let profile_metadata = create_test_metadata("profile", RelationshipType::HasOne);

        registry.register("User", "posts", posts_metadata).unwrap();
        registry
            .register("User", "profile", profile_metadata)
            .unwrap();

        let mut names = registry.get_relationship_names("User");
        names.sort();
        assert_eq!(names, vec!["posts", "profile"]);
    }

    #[test]
    fn test_registry_validation() {
        let registry = RelationshipRegistry::new();

        // Valid relationship
        let valid_metadata = create_test_metadata("posts", RelationshipType::HasMany);
        registry.register("User", "posts", valid_metadata).unwrap();

        assert!(registry.validate_all().is_ok());
    }

    #[test]
    fn test_registry_clear() {
        let registry = RelationshipRegistry::new();
        let metadata = create_test_metadata("posts", RelationshipType::HasMany);

        registry.register("User", "posts", metadata).unwrap();
        assert_eq!(registry.stats().total_relationships, 1);

        registry.clear();
        assert_eq!(registry.stats().total_relationships, 0);
        assert!(!registry.has_relationship("User", "posts"));
    }
}