georm/tests/defaultable_struct.rs
Lucien Cartier-Tilet 32828f9ee5
feat: add defaultable field support with companion struct generation
Introduces support for `#[georm(defaultable)]` attribute on entity
fields. When fields are marked as defaultable, generates companion
`<Entity>Default` structs where defaultable fields become `Option<T>`,
enabling easier entity creation when some fields have database defaults
or are auto-generated.

Key features:
- Generates `<Entity>Default` structs with optional defaultable fields
- Implements `Defaultable<Id, Entity>` trait with async `create` method
- Validates that `Option<T>` fields cannot be marked as defaultable
- Preserves field visibility in generated companion structs
- Only generates companion struct when defaultable fields are present
2025-06-04 23:59:39 +02:00

62 lines
1.8 KiB
Rust

use georm::Georm;
// Test struct with defaultable fields using existing table structure
#[derive(Georm)]
#[georm(table = "authors")]
struct TestAuthor {
#[georm(id, defaultable)]
pub id: i32,
pub name: String,
pub biography_id: Option<i32>, // Don't mark Option fields as defaultable
}
// Test struct with only ID defaultable
#[derive(Georm)]
#[georm(table = "authors")]
struct MinimalDefaultable {
#[georm(id, defaultable)]
pub id: i32,
pub name: String,
pub biography_id: Option<i32>,
}
#[test]
fn defaultable_struct_should_exist() {
// This test will compile only if TestAuthorDefault struct exists
let _author_default = TestAuthorDefault {
id: Some(1), // Should be Option<i32> since ID is defaultable
name: "Test Author".to_string(), // Should remain String
biography_id: None, // Should remain Option<i32>
};
}
#[test]
fn minimal_defaultable_struct_should_exist() {
// MinimalDefaultableDefault should exist because ID is marked as defaultable
let _minimal_default = MinimalDefaultableDefault {
id: None, // Should be Option<i32>
name: "testuser".to_string(), // Should remain String
biography_id: None, // Should remain Option<i32>
};
}
#[test]
fn defaultable_fields_can_be_none() {
let _author_default = TestAuthorDefault {
id: None, // Can be None since it's defaultable (auto-generated)
name: "Test Author".to_string(),
biography_id: None, // Can remain None
};
}
#[test]
fn field_visibility_is_preserved() {
let _author_default = TestAuthorDefault {
id: Some(1), // pub
name: "Test".to_string(), // pub
biography_id: Some(1), // pub, Option<i32>
};
// This test ensures field visibility is preserved in generated struct
}