audb-codegen 0.1.11

Code generation for AuDB compile-time database applications
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
//! Relationship detection utilities
//!
//! This module provides utilities for detecting relationships between schemas,
//! including foreign key detection and primary key identification.
//!
//! ## Foreign Key Detection
//!
//! Foreign keys are detected by the naming pattern: `{entity}_id: EntityId`
//!
//! Examples:
//! - `author_id: EntityId` → FK to `Author` schema
//! - `parent_id: EntityId` → FK to `Parent` schema
//! - `user_id: EntityId` → FK to `User` schema
//!
//! ## Primary Key Detection
//!
//! Primary keys are identified as:
//! 1. First EntityId field named "id" (preferred)
//! 2. First EntityId field with any name (fallback)
//!
//! ## Examples
//!
//! ```
//! use audb::schema::{Schema, Field, Type, SchemaFormat};
//! use audb_codegen::relationships::{detect_foreign_keys, find_primary_key};
//!
//! let mut schema = Schema::new("Post".to_string(), SchemaFormat::Native);
//! schema.add_field(Field::new("id".to_string(), Type::EntityId));
//! schema.add_field(Field::new("author_id".to_string(), Type::EntityId));
//!
//! // Find primary key
//! let pk = find_primary_key(&schema).unwrap();
//! assert_eq!(pk.name, "id");
//!
//! // Detect foreign keys
//! let fks = detect_foreign_keys(&schema);
//! assert_eq!(fks.len(), 1);
//! assert_eq!(fks[0].field_name, "author_id");
//! assert_eq!(fks[0].target_schema, "Author");
//! ```

use audb::schema::{Field, Schema, Type};

/// Information about a foreign key relationship
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ForeignKeyInfo {
    /// The field name containing the foreign key (e.g., "author_id")
    pub field_name: String,

    /// The target schema name (e.g., "Author")
    pub target_schema: String,

    /// Whether the foreign key field is nullable
    pub nullable: bool,
}

impl ForeignKeyInfo {
    /// Create a new foreign key info
    pub fn new(field_name: String, target_schema: String, nullable: bool) -> Self {
        Self {
            field_name,
            target_schema,
            nullable,
        }
    }

    /// Get the method name for accessing this relationship
    ///
    /// # Examples
    ///
    /// ```
    /// # use audb_codegen::relationships::ForeignKeyInfo;
    /// let fk = ForeignKeyInfo::new("author_id".to_string(), "Author".to_string(), false);
    /// assert_eq!(fk.method_name(), "author");
    ///
    /// let fk2 = ForeignKeyInfo::new("parent_category_id".to_string(), "Category".to_string(), true);
    /// assert_eq!(fk2.method_name(), "parent_category");
    /// ```
    pub fn method_name(&self) -> String {
        // Remove "_id" suffix from field name
        if self.field_name.ends_with("_id") {
            self.field_name[..self.field_name.len() - 3].to_string()
        } else {
            self.field_name.clone()
        }
    }
}

/// Detect foreign key relationships in a schema
///
/// This function identifies fields that represent foreign keys based on naming patterns.
/// A field is considered a foreign key if:
/// 1. It has type `EntityId`
/// 2. Its name ends with "_id"
/// 3. Its name is not just "id" (that's the primary key)
///
/// # Examples
///
/// ```
/// # use audb::schema::{Schema, Field, Type, SchemaFormat};
/// # use audb_codegen::relationships::detect_foreign_keys;
/// let mut post = Schema::new("Post".to_string(), SchemaFormat::Native);
/// post.add_field(Field::new("id".to_string(), Type::EntityId));
/// post.add_field(Field::new("author_id".to_string(), Type::EntityId));
///
/// let mut category_field = Field::new("category_id".to_string(), Type::EntityId);
/// category_field.nullable = true;
/// post.add_field(category_field);
///
/// let fks = detect_foreign_keys(&post);
/// assert_eq!(fks.len(), 2);
/// assert_eq!(fks[0].field_name, "author_id");
/// assert_eq!(fks[0].target_schema, "Author");
/// assert!(!fks[0].nullable);
///
/// assert_eq!(fks[1].field_name, "category_id");
/// assert_eq!(fks[1].target_schema, "Category");
/// assert!(fks[1].nullable);
/// ```
pub fn detect_foreign_keys(schema: &Schema) -> Vec<ForeignKeyInfo> {
    let mut foreign_keys = Vec::new();

    for field in &schema.fields {
        // Must be EntityId type
        if !matches!(field.field_type, Type::EntityId) {
            continue;
        }

        // Must end with "_id"
        if !field.name.ends_with("_id") {
            continue;
        }

        // Must not be just "id" (that's the primary key)
        if field.name == "id" {
            continue;
        }

        // Extract entity name from field name
        // e.g., "author_id" → "author"
        let entity_name = &field.name[..field.name.len() - 3];

        // Convert to PascalCase for schema name
        // e.g., "author" → "Author", "parent_category" → "ParentCategory"
        let target_schema = to_pascal_case(entity_name);

        foreign_keys.push(ForeignKeyInfo::new(
            field.name.clone(),
            target_schema,
            field.nullable,
        ));
    }

    foreign_keys
}

/// Find the primary key field in a schema
///
/// This function identifies the primary key field using the following strategy:
/// 1. First `EntityId` field named "id" (preferred)
/// 2. First `EntityId` field with any name (fallback)
/// 3. None if no `EntityId` field exists
///
/// # Examples
///
/// ```
/// # use audb::schema::{Schema, Field, Type, SchemaFormat};
/// # use audb_codegen::relationships::find_primary_key;
/// // Schema with "id" field
/// let mut user = Schema::new("User".to_string(), SchemaFormat::Native);
/// user.add_field(Field::new("id".to_string(), Type::EntityId));
/// user.add_field(Field::new("name".to_string(), Type::String));
///
/// let pk = find_primary_key(&user).unwrap();
/// assert_eq!(pk.name, "id");
///
/// // Schema with alternate PK name
/// let mut entity = Schema::new("Entity".to_string(), SchemaFormat::Native);
/// entity.add_field(Field::new("entity_id".to_string(), Type::EntityId));
///
/// let pk2 = find_primary_key(&entity).unwrap();
/// assert_eq!(pk2.name, "entity_id");
///
/// // Schema without EntityId
/// let mut simple = Schema::new("Simple".to_string(), SchemaFormat::Native);
/// simple.add_field(Field::new("value".to_string(), Type::String));
///
/// assert!(find_primary_key(&simple).is_none());
/// ```
pub fn find_primary_key(schema: &Schema) -> Option<&Field> {
    // Strategy 1: Look for field named "id" with EntityId type
    if let Some(field) = schema
        .fields
        .iter()
        .find(|f| f.name == "id" && matches!(f.field_type, Type::EntityId))
    {
        return Some(field);
    }

    // Strategy 2: First EntityId field (any name)
    schema
        .fields
        .iter()
        .find(|f| matches!(f.field_type, Type::EntityId))
}

/// Convert snake_case or lowercase to PascalCase
///
/// # Examples
///
/// ```
/// # use audb_codegen::relationships::to_pascal_case;
/// assert_eq!(to_pascal_case("author"), "Author");
/// assert_eq!(to_pascal_case("blog_post"), "BlogPost");
/// assert_eq!(to_pascal_case("parent_category"), "ParentCategory");
/// assert_eq!(to_pascal_case("user"), "User");
/// assert_eq!(to_pascal_case(""), "");
/// ```
pub fn to_pascal_case(s: &str) -> String {
    if s.is_empty() {
        return String::new();
    }

    s.split('_')
        .filter(|part| !part.is_empty())
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                Some(first) => first.to_uppercase().chain(chars).collect::<String>(),
                None => String::new(),
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use audb::schema::SchemaFormat;

    #[test]
    fn test_to_pascal_case_simple() {
        assert_eq!(to_pascal_case("author"), "Author");
        assert_eq!(to_pascal_case("user"), "User");
        assert_eq!(to_pascal_case("post"), "Post");
    }

    #[test]
    fn test_to_pascal_case_multiple_words() {
        assert_eq!(to_pascal_case("blog_post"), "BlogPost");
        assert_eq!(to_pascal_case("parent_category"), "ParentCategory");
        assert_eq!(to_pascal_case("user_profile"), "UserProfile");
    }

    #[test]
    fn test_to_pascal_case_edge_cases() {
        assert_eq!(to_pascal_case(""), "");
        assert_eq!(to_pascal_case("a"), "A");
        assert_eq!(to_pascal_case("a_b_c"), "ABC");
    }

    #[test]
    fn test_detect_foreign_keys_none() {
        let mut schema = Schema::new("User".to_string(), SchemaFormat::Native);
        schema.add_field(Field::new("id".to_string(), Type::EntityId));
        schema.add_field(Field::new("name".to_string(), Type::String));

        let fks = detect_foreign_keys(&schema);
        assert_eq!(fks.len(), 0);
    }

    #[test]
    fn test_detect_foreign_keys_single() {
        let mut schema = Schema::new("Post".to_string(), SchemaFormat::Native);
        schema.add_field(Field::new("id".to_string(), Type::EntityId));
        schema.add_field(Field::new("author_id".to_string(), Type::EntityId));
        schema.add_field(Field::new("title".to_string(), Type::String));

        let fks = detect_foreign_keys(&schema);
        assert_eq!(fks.len(), 1);
        assert_eq!(fks[0].field_name, "author_id");
        assert_eq!(fks[0].target_schema, "Author");
        assert!(!fks[0].nullable);
    }

    #[test]
    fn test_detect_foreign_keys_multiple() {
        let mut schema = Schema::new("Comment".to_string(), SchemaFormat::Native);
        schema.add_field(Field::new("id".to_string(), Type::EntityId));
        schema.add_field(Field::new("post_id".to_string(), Type::EntityId));
        schema.add_field(Field::new("author_id".to_string(), Type::EntityId));

        let fks = detect_foreign_keys(&schema);
        assert_eq!(fks.len(), 2);

        assert_eq!(fks[0].field_name, "post_id");
        assert_eq!(fks[0].target_schema, "Post");

        assert_eq!(fks[1].field_name, "author_id");
        assert_eq!(fks[1].target_schema, "Author");
    }

    #[test]
    fn test_detect_foreign_keys_nullable() {
        let mut schema = Schema::new("Post".to_string(), SchemaFormat::Native);
        schema.add_field(Field::new("id".to_string(), Type::EntityId));

        let mut editor_field = Field::new("editor_id".to_string(), Type::EntityId);
        editor_field.nullable = true;
        schema.add_field(editor_field);

        let fks = detect_foreign_keys(&schema);
        assert_eq!(fks.len(), 1);
        assert_eq!(fks[0].field_name, "editor_id");
        assert_eq!(fks[0].target_schema, "Editor");
        assert!(fks[0].nullable);
    }

    #[test]
    fn test_detect_foreign_keys_composite_names() {
        let mut schema = Schema::new("Item".to_string(), SchemaFormat::Native);
        schema.add_field(Field::new("id".to_string(), Type::EntityId));
        schema.add_field(Field::new("parent_category_id".to_string(), Type::EntityId));

        let fks = detect_foreign_keys(&schema);
        assert_eq!(fks.len(), 1);
        assert_eq!(fks[0].field_name, "parent_category_id");
        assert_eq!(fks[0].target_schema, "ParentCategory");
    }

    #[test]
    fn test_detect_foreign_keys_ignores_non_entity_id() {
        let mut schema = Schema::new("Test".to_string(), SchemaFormat::Native);
        schema.add_field(Field::new("id".to_string(), Type::EntityId));
        schema.add_field(Field::new("user_id".to_string(), Type::String)); // Not EntityId
        schema.add_field(Field::new("count_id".to_string(), Type::Integer)); // Not EntityId

        let fks = detect_foreign_keys(&schema);
        assert_eq!(fks.len(), 0);
    }

    #[test]
    fn test_detect_foreign_keys_ignores_id() {
        let mut schema = Schema::new("Test".to_string(), SchemaFormat::Native);
        schema.add_field(Field::new("id".to_string(), Type::EntityId));

        let fks = detect_foreign_keys(&schema);
        assert_eq!(fks.len(), 0); // "id" is not a foreign key
    }

    #[test]
    fn test_find_primary_key_named_id() {
        let mut schema = Schema::new("User".to_string(), SchemaFormat::Native);
        schema.add_field(Field::new("id".to_string(), Type::EntityId));
        schema.add_field(Field::new("name".to_string(), Type::String));

        let pk = find_primary_key(&schema).unwrap();
        assert_eq!(pk.name, "id");
    }

    #[test]
    fn test_find_primary_key_alternate_name() {
        let mut schema = Schema::new("Entity".to_string(), SchemaFormat::Native);
        schema.add_field(Field::new("name".to_string(), Type::String));
        schema.add_field(Field::new("entity_id".to_string(), Type::EntityId));

        let pk = find_primary_key(&schema).unwrap();
        assert_eq!(pk.name, "entity_id");
    }

    #[test]
    fn test_find_primary_key_prefers_id() {
        let mut schema = Schema::new("Test".to_string(), SchemaFormat::Native);
        schema.add_field(Field::new("user_id".to_string(), Type::EntityId));
        schema.add_field(Field::new("id".to_string(), Type::EntityId));

        let pk = find_primary_key(&schema).unwrap();
        assert_eq!(pk.name, "id"); // Prefers "id" over "user_id"
    }

    #[test]
    fn test_find_primary_key_none() {
        let mut schema = Schema::new("Simple".to_string(), SchemaFormat::Native);
        schema.add_field(Field::new("name".to_string(), Type::String));
        schema.add_field(Field::new("value".to_string(), Type::Integer));

        assert!(find_primary_key(&schema).is_none());
    }

    #[test]
    fn test_foreign_key_info_method_name() {
        let fk1 = ForeignKeyInfo::new("author_id".to_string(), "Author".to_string(), false);
        assert_eq!(fk1.method_name(), "author");

        let fk2 = ForeignKeyInfo::new(
            "parent_category_id".to_string(),
            "ParentCategory".to_string(),
            true,
        );
        assert_eq!(fk2.method_name(), "parent_category");

        let fk3 = ForeignKeyInfo::new("user_id".to_string(), "User".to_string(), false);
        assert_eq!(fk3.method_name(), "user");
    }

    #[test]
    fn test_foreign_key_info_creation() {
        let fk = ForeignKeyInfo::new("author_id".to_string(), "Author".to_string(), true);

        assert_eq!(fk.field_name, "author_id");
        assert_eq!(fk.target_schema, "Author");
        assert!(fk.nullable);
    }
}