this-rs 0.0.9

Framework for building complex multi-entity REST and GraphQL APIs with many relationships
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
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
//! Macros for reducing boilerplate when defining entities
//!
//! These macros generate the repetitive trait implementations needed
//! for each entity type following the Entity/Data/Link architecture.

/// Helper macro to enable multi-tenancy for an entity
///
/// This macro adds an override for the `Entity::tenant_id()` method
/// to return the actual tenant_id field value.
///
/// # Example
/// ```rust,ignore
/// impl_data_entity!(User, "user", ["name"], {
///     tenant_id: Uuid,
///     email: String,
/// });
///
/// // Enable multi-tenancy
/// impl_entity_multi_tenant!(User);
/// ```
#[macro_export]
macro_rules! impl_entity_multi_tenant {
    ($type:ident) => {
        // Cannot override trait methods in separate impl blocks in stable Rust
        // This is a marker for documentation purposes
        // Users should manually implement tenant_id access via a helper method
        impl $type {
            /// Get the tenant ID for multi-tenant isolation
            #[allow(dead_code)]
            pub fn get_tenant_id(&self) -> ::uuid::Uuid {
                self.tenant_id
            }
        }
    };
}

/// Macro to inject Entity base fields into a struct
///
/// Injects: id, entity_type, created_at, updated_at, deleted_at, status
#[macro_export]
macro_rules! entity_fields {
    () => {
        /// Unique identifier for this entity
        pub id: ::uuid::Uuid,

        /// Type of the entity (e.g., "user", "product")
        #[serde(rename = "type")]
        pub entity_type: String,

        /// When this entity was created
        pub created_at: ::chrono::DateTime<::chrono::Utc>,

        /// When this entity was last updated
        pub updated_at: ::chrono::DateTime<::chrono::Utc>,

        /// When this entity was soft-deleted (if applicable)
        pub deleted_at: Option<::chrono::DateTime<::chrono::Utc>>,

        /// Current status of the entity
        pub status: String,
    };
}

/// Macro to inject Data fields into a struct (Entity fields + name)
#[macro_export]
macro_rules! data_fields {
    () => {
        /// Unique identifier for this entity
        pub id: ::uuid::Uuid,

        /// Type of the entity (e.g., "user", "product")
        #[serde(rename = "type")]
        pub entity_type: String,

        /// When this entity was created
        pub created_at: ::chrono::DateTime<::chrono::Utc>,

        /// When this entity was last updated
        pub updated_at: ::chrono::DateTime<::chrono::Utc>,

        /// When this entity was soft-deleted (if applicable)
        pub deleted_at: Option<::chrono::DateTime<::chrono::Utc>>,

        /// Current status of the entity
        pub status: String,

        /// Name of this data entity
        pub name: String,
    };
}

/// Macro to inject Link fields into a struct (Entity fields + source_id + target_id + link_type)
#[macro_export]
macro_rules! link_fields {
    () => {
        /// Unique identifier for this entity
        pub id: ::uuid::Uuid,

        /// Type of the entity (e.g., "user", "product")
        #[serde(rename = "type")]
        pub entity_type: String,

        /// When this entity was created
        pub created_at: ::chrono::DateTime<::chrono::Utc>,

        /// When this entity was last updated
        pub updated_at: ::chrono::DateTime<::chrono::Utc>,

        /// When this entity was soft-deleted (if applicable)
        pub deleted_at: Option<::chrono::DateTime<::chrono::Utc>>,

        /// Current status of the entity
        pub status: String,

        /// Type of relationship
        pub link_type: String,

        /// ID of the source entity
        pub source_id: ::uuid::Uuid,

        /// ID of the target entity
        pub target_id: ::uuid::Uuid,
    };
}

/// Complete macro to create a Data entity with automatic trait implementations
///
/// # Example
///
/// ```rust,ignore
/// use this::prelude::*;
///
/// impl_data_entity!(
///     User,
///     "user",
///     ["name", "email"],
///     {
///         email: String,
///         password_hash: String,
///         roles: Vec<String>,
///     }
/// );
///
/// // Usage
/// let user = User::new(
///     "John Doe".to_string(),
///     "active".to_string(),
///     "john@example.com".to_string(),
///     "$argon2$...".to_string(),
///     vec!["admin".to_string()],
/// );
/// ```
#[macro_export]
macro_rules! impl_data_entity {
    (
        $type:ident,
        $type_name:expr,
        [ $( $indexed_field:expr ),* $(,)? ],
        {
            $( $specific_field:ident : $specific_type:ty ),* $(,)?
        }
    ) => {
        #[derive(Debug, Clone, ::serde::Serialize, ::serde::Deserialize)]
        pub struct $type {
            /// Unique identifier for this entity
            pub id: ::uuid::Uuid,

            /// Type of the entity
            #[serde(rename = "type")]
            pub entity_type: String,

            /// When this entity was created
            pub created_at: ::chrono::DateTime<::chrono::Utc>,

            /// When this entity was last updated
            pub updated_at: ::chrono::DateTime<::chrono::Utc>,

            /// When this entity was soft-deleted (if applicable)
            pub deleted_at: Option<::chrono::DateTime<::chrono::Utc>>,

            /// Current status of the entity
            pub status: String,

            /// Name of this data entity
            pub name: String,
            $( pub $specific_field : $specific_type ),*
        }

        // Implement Entity trait
        impl $crate::core::entity::Entity for $type {
            type Service = ();

            fn resource_name() -> &'static str {
                use std::sync::OnceLock;
                static PLURAL: OnceLock<&'static str> = OnceLock::new();
                PLURAL.get_or_init(|| {
                    Box::leak(
                        $crate::core::pluralize::Pluralizer::pluralize($type_name)
                            .into_boxed_str()
                    )
                })
            }

            fn resource_name_singular() -> &'static str {
                $type_name
            }

            fn service_from_host(
                _host: &::std::sync::Arc<dyn ::std::any::Any + Send + Sync>
            ) -> ::anyhow::Result<::std::sync::Arc<Self::Service>> {
                unimplemented!("service_from_host must be implemented by user")
            }

            fn id(&self) -> ::uuid::Uuid {
                self.id
            }

            fn entity_type(&self) -> &str {
                &self.entity_type
            }

            fn created_at(&self) -> ::chrono::DateTime<::chrono::Utc> {
                self.created_at
            }

            fn updated_at(&self) -> ::chrono::DateTime<::chrono::Utc> {
                self.updated_at
            }

            fn deleted_at(&self) -> Option<::chrono::DateTime<::chrono::Utc>> {
                self.deleted_at
            }

            fn status(&self) -> &str {
                &self.status
            }
        }

        // Implement Data trait
        impl $crate::core::entity::Data for $type {
            fn name(&self) -> &str {
                &self.name
            }

            fn indexed_fields() -> &'static [&'static str] {
                &[ $( $indexed_field ),* ]
            }

            fn field_value(&self, field: &str) -> Option<$crate::core::field::FieldValue> {
                match field {
                    "name" => Some($crate::core::field::FieldValue::String(self.name.clone())),
                    "status" => Some($crate::core::field::FieldValue::String(self.status.clone())),
                    _ => None,
                }
            }
        }

        // Utility methods
        impl $type {
            /// Create a new instance of this entity
            pub fn new(
                name: String,
                status: String,
                $( $specific_field: $specific_type ),*
            ) -> Self {
                Self {
                    id: ::uuid::Uuid::new_v4(),
                    entity_type: $type_name.to_string(),
                    created_at: ::chrono::Utc::now(),
                    updated_at: ::chrono::Utc::now(),
                    deleted_at: None,
                    status,
                    name,
                    $( $specific_field ),*
                }
            }

            /// Soft delete this entity (sets deleted_at timestamp)
            pub fn soft_delete(&mut self) {
                self.deleted_at = Some(::chrono::Utc::now());
                self.updated_at = ::chrono::Utc::now();
            }

            /// Restore a soft-deleted entity (clears deleted_at timestamp)
            pub fn restore(&mut self) {
                self.deleted_at = None;
                self.updated_at = ::chrono::Utc::now();
            }

            /// Update the updated_at timestamp to now
            pub fn touch(&mut self) {
                self.updated_at = ::chrono::Utc::now();
            }

            /// Change the entity status
            pub fn set_status(&mut self, status: String) {
                self.status = status;
                self.touch();
            }
        }
    };
}

/// Complete macro to create a Link entity with automatic trait implementations
///
/// # Example
///
/// ```rust,ignore
/// use this::prelude::*;
///
/// impl_link_entity!(
///     UserCompanyLink,
///     "user_company_link",
///     {
///         role: String,
///         start_date: DateTime<Utc>,
///     }
/// );
///
/// // Usage
/// let link = UserCompanyLink::new(
///     "employment".to_string(),
///     user_id,
///     company_id,
///     "active".to_string(),
///     "Senior Developer".to_string(),
///     Utc::now(),
/// );
/// ```
#[macro_export]
macro_rules! impl_link_entity {
    (
        $type:ident,
        $type_name:expr,
        {
            $( $specific_field:ident : $specific_type:ty ),* $(,)?
        }
    ) => {
        #[derive(Debug, Clone, ::serde::Serialize, ::serde::Deserialize)]
        pub struct $type {
            /// Unique identifier for this entity
            pub id: ::uuid::Uuid,

            /// Type of the entity
            #[serde(rename = "type")]
            pub entity_type: String,

            /// When this entity was created
            pub created_at: ::chrono::DateTime<::chrono::Utc>,

            /// When this entity was last updated
            pub updated_at: ::chrono::DateTime<::chrono::Utc>,

            /// When this entity was soft-deleted (if applicable)
            pub deleted_at: Option<::chrono::DateTime<::chrono::Utc>>,

            /// Current status of the entity
            pub status: String,

            /// Type of relationship
            pub link_type: String,

            /// ID of the source entity
            pub source_id: ::uuid::Uuid,

            /// ID of the target entity
            pub target_id: ::uuid::Uuid,
            $( pub $specific_field : $specific_type ),*
        }

        // Implement Entity trait
        impl $crate::core::entity::Entity for $type {
            type Service = ();

            fn resource_name() -> &'static str {
                use std::sync::OnceLock;
                static PLURAL: OnceLock<&'static str> = OnceLock::new();
                PLURAL.get_or_init(|| {
                    Box::leak(
                        $crate::core::pluralize::Pluralizer::pluralize($type_name)
                            .into_boxed_str()
                    )
                })
            }

            fn resource_name_singular() -> &'static str {
                $type_name
            }

            fn service_from_host(
                _host: &::std::sync::Arc<dyn ::std::any::Any + Send + Sync>
            ) -> ::anyhow::Result<::std::sync::Arc<Self::Service>> {
                unimplemented!("service_from_host must be implemented by user")
            }

            fn id(&self) -> ::uuid::Uuid {
                self.id
            }

            fn entity_type(&self) -> &str {
                &self.entity_type
            }

            fn created_at(&self) -> ::chrono::DateTime<::chrono::Utc> {
                self.created_at
            }

            fn updated_at(&self) -> ::chrono::DateTime<::chrono::Utc> {
                self.updated_at
            }

            fn deleted_at(&self) -> Option<::chrono::DateTime<::chrono::Utc>> {
                self.deleted_at
            }

            fn status(&self) -> &str {
                &self.status
            }
        }

        // Implement Link trait
        impl $crate::core::entity::Link for $type {
            fn source_id(&self) -> ::uuid::Uuid {
                self.source_id
            }

            fn target_id(&self) -> ::uuid::Uuid {
                self.target_id
            }

            fn link_type(&self) -> &str {
                &self.link_type
            }
        }

        // Utility methods
        impl $type {
            /// Create a new link instance
            pub fn new(
                link_type: String,
                source_id: ::uuid::Uuid,
                target_id: ::uuid::Uuid,
                status: String,
                $( $specific_field: $specific_type ),*
            ) -> Self {
                Self {
                    id: ::uuid::Uuid::new_v4(),
                    entity_type: $type_name.to_string(),
                    created_at: ::chrono::Utc::now(),
                    updated_at: ::chrono::Utc::now(),
                    deleted_at: None,
                    status,
                    link_type,
                    source_id,
                    target_id,
                    $( $specific_field ),*
                }
            }

            /// Soft delete this link
            pub fn soft_delete(&mut self) {
                self.deleted_at = Some(::chrono::Utc::now());
                self.updated_at = ::chrono::Utc::now();
            }

            /// Restore a soft-deleted link
            #[allow(dead_code)]
            pub fn restore(&mut self) {
                self.deleted_at = None;
                self.updated_at = ::chrono::Utc::now();
            }

            /// Update the updated_at timestamp
            #[allow(dead_code)]
            pub fn touch(&mut self) {
                self.updated_at = ::chrono::Utc::now();
            }

            /// Change the link status
            #[allow(dead_code)]
            pub fn set_status(&mut self, status: String) {
                self.status = status;
                self.touch();
            }
        }
    };
}

/// Extended macro to create a Data entity with validation and filtering
///
/// This macro extends `impl_data_entity!` with declarative validation and filtering support.
///
/// # Example
///
/// ```rust,ignore
/// use this::prelude::*;
///
/// impl_data_entity_validated!(
///     Invoice,
///     "invoice",
///     ["name", "number"],
///     {
///         number: String,
///         amount: f64,
///         due_date: Option<String>,
///     },
///     validate: {
///         create: {
///             number: [required, string_length(3, 50)],
///             amount: [required, positive],
///         },
///         update: {
///             amount: [optional, positive],
///         },
///     },
///     filters: {
///         create: {
///             number: [trim, uppercase],
///             amount: [round_decimals(2)],
///         },
///     }
/// );
/// ```
#[macro_export]
macro_rules! impl_data_entity_validated {
    (
        $type:ident,
        $type_name:expr,
        [ $( $indexed_field:expr ),* $(,)? ],
        {
            $( $specific_field:ident : $specific_type:ty ),* $(,)?
        }
        $(,)?
        validate: {
            $(
                $op:ident: {
                    $(
                        $val_field:ident: [ $( $validator:tt )* ]
                    ),* $(,)?
                }
            ),* $(,)?
        }
        $(,)?
        filters: {
            $(
                $fop:ident: {
                    $(
                        $fil_field:ident: [ $( $filter:tt )* ]
                    ),* $(,)?
                }
            ),* $(,)?
        }
        $(,)?
    ) => {
        // 1. Generate the base entity (reuse existing macro)
        $crate::impl_data_entity!(
            $type,
            $type_name,
            [ $( $indexed_field ),* ],
            {
                $( $specific_field : $specific_type ),*
            }
        );

        // 2. Implement ValidatableEntity trait for validation support
        impl $crate::core::validation::extractor::ValidatableEntity for $type {
            fn validation_config(operation: &str) -> $crate::core::validation::EntityValidationConfig {
                use $crate::core::validation::*;

                let mut config = EntityValidationConfig::new($type_name);

                // Generate validation rules per operation
                $(
                    if operation == stringify!($op) {
                        $(
                            // Add validators for each field
                            $crate::add_validators_for_field!(config, stringify!($val_field), $( $validator )*);
                        )*
                    }
                )*

                // Generate filters per operation
                $(
                    if operation == stringify!($fop) {
                        $(
                            // Add filters for each field
                            $crate::add_filters_for_field!(config, stringify!($fil_field), $( $filter )*);
                        )*
                    }
                )*

                config
            }
        }
    };
}

/// Helper macro to add validators to a field
#[macro_export]
macro_rules! add_validators_for_field {
    // Base case: empty
    ($config:expr, $field:expr,) => {};

    // required
    ($config:expr, $field:expr, required $( $rest:tt )*) => {
        $config.add_validator($field, $crate::core::validation::validators::required());
        $crate::add_validators_for_field!($config, $field, $( $rest )*);
    };

    // optional
    ($config:expr, $field:expr, optional $( $rest:tt )*) => {
        $config.add_validator($field, $crate::core::validation::validators::optional());
        $crate::add_validators_for_field!($config, $field, $( $rest )*);
    };

    // positive
    ($config:expr, $field:expr, positive $( $rest:tt )*) => {
        $config.add_validator($field, $crate::core::validation::validators::positive());
        $crate::add_validators_for_field!($config, $field, $( $rest )*);
    };

    // string_length with parameters
    ($config:expr, $field:expr, string_length($min:expr, $max:expr) $( $rest:tt )*) => {
        $config.add_validator($field, $crate::core::validation::validators::string_length($min, $max));
        $crate::add_validators_for_field!($config, $field, $( $rest )*);
    };

    // max_value with parameter
    ($config:expr, $field:expr, max_value($max:expr) $( $rest:tt )*) => {
        $config.add_validator($field, $crate::core::validation::validators::max_value($max));
        $crate::add_validators_for_field!($config, $field, $( $rest )*);
    };

    // in_list with values
    ($config:expr, $field:expr, in_list($( $value:expr ),* $(,)?) $( $rest:tt )*) => {
        $config.add_validator($field, $crate::core::validation::validators::in_list(vec![$( $value.to_string() ),*]));
        $crate::add_validators_for_field!($config, $field, $( $rest )*);
    };

    // date_format with format string
    ($config:expr, $field:expr, date_format($format:expr) $( $rest:tt )*) => {
        $config.add_validator($field, $crate::core::validation::validators::date_format($format));
        $crate::add_validators_for_field!($config, $field, $( $rest )*);
    };
}

/// Helper macro to add filters to a field
#[macro_export]
macro_rules! add_filters_for_field {
    // Base case: empty
    ($config:expr, $field:expr,) => {};

    // trim
    ($config:expr, $field:expr, trim $( $rest:tt )*) => {
        $config.add_filter($field, $crate::core::validation::filters::trim());
        $crate::add_filters_for_field!($config, $field, $( $rest )*);
    };

    // uppercase
    ($config:expr, $field:expr, uppercase $( $rest:tt )*) => {
        $config.add_filter($field, $crate::core::validation::filters::uppercase());
        $crate::add_filters_for_field!($config, $field, $( $rest )*);
    };

    // lowercase
    ($config:expr, $field:expr, lowercase $( $rest:tt )*) => {
        $config.add_filter($field, $crate::core::validation::filters::lowercase());
        $crate::add_filters_for_field!($config, $field, $( $rest )*);
    };

    // round_decimals with parameter
    ($config:expr, $field:expr, round_decimals($decimals:expr) $( $rest:tt )*) => {
        $config.add_filter($field, $crate::core::validation::filters::round_decimals($decimals));
        $crate::add_filters_for_field!($config, $field, $( $rest )*);
    };
}

#[cfg(test)]
mod tests {
    use crate::prelude::*;

    // Test Data entity
    impl_data_entity!(
        TestUser,
        "test_user",
        ["name", "email"],
        {
            email: String,
        }
    );

    // Test Link entity
    impl_link_entity!(
        TestOwnerLink,
        "test_owner_link",
        {
            since: DateTime<Utc>,
        }
    );

    #[test]
    fn test_data_entity_creation() {
        let user = TestUser::new(
            "John Doe".to_string(),
            "active".to_string(),
            "john@example.com".to_string(),
        );

        assert_eq!(user.name(), "John Doe");
        assert_eq!(user.status(), "active");
        assert_eq!(user.email, "john@example.com");
        assert!(!user.is_deleted());
        assert!(user.is_active());
    }

    #[test]
    fn test_data_entity_soft_delete() {
        let mut user = TestUser::new(
            "John Doe".to_string(),
            "active".to_string(),
            "john@example.com".to_string(),
        );

        assert!(!user.is_deleted());
        user.soft_delete();
        assert!(user.is_deleted());
        assert!(!user.is_active());
    }

    #[test]
    fn test_data_entity_restore() {
        let mut user = TestUser::new(
            "John Doe".to_string(),
            "active".to_string(),
            "john@example.com".to_string(),
        );

        user.soft_delete();
        assert!(user.is_deleted());

        user.restore();
        assert!(!user.is_deleted());
        assert!(user.is_active());
    }

    #[test]
    fn test_link_entity_creation() {
        let user_id = Uuid::new_v4();
        let car_id = Uuid::new_v4();

        let link = TestOwnerLink::new(
            "owner".to_string(),
            user_id,
            car_id,
            "active".to_string(),
            Utc::now(),
        );

        assert_eq!(link.source_id(), user_id);
        assert_eq!(link.target_id(), car_id);
        assert_eq!(link.link_type(), "owner");
        assert_eq!(link.status(), "active");
        assert!(!link.is_deleted());
    }

    #[test]
    fn test_link_entity_soft_delete() {
        let link = TestOwnerLink::new(
            "owner".to_string(),
            Uuid::new_v4(),
            Uuid::new_v4(),
            "active".to_string(),
            Utc::now(),
        );

        let mut link = link;
        assert!(!link.is_deleted());

        link.soft_delete();
        assert!(link.is_deleted());
    }

    #[test]
    fn test_entity_set_status() {
        let mut user = TestUser::new(
            "John Doe".to_string(),
            "active".to_string(),
            "john@example.com".to_string(),
        );

        assert_eq!(user.status(), "active");

        user.set_status("inactive".to_string());
        assert_eq!(user.status(), "inactive");
    }

    #[test]
    fn test_data_entity_field_value_name() {
        let user = TestUser::new(
            "Alice".to_string(),
            "active".to_string(),
            "alice@example.com".to_string(),
        );

        let name_val = user
            .field_value("name")
            .expect("field_value('name') should return Some");
        assert_eq!(
            name_val,
            crate::core::field::FieldValue::String("Alice".to_string())
        );
    }

    #[test]
    fn test_data_entity_field_value_status() {
        let user = TestUser::new(
            "Bob".to_string(),
            "pending".to_string(),
            "bob@example.com".to_string(),
        );

        let status_val = user
            .field_value("status")
            .expect("field_value('status') should return Some");
        assert_eq!(
            status_val,
            crate::core::field::FieldValue::String("pending".to_string())
        );
    }

    #[test]
    fn test_data_entity_field_value_unknown_returns_none() {
        let user = TestUser::new(
            "Charlie".to_string(),
            "active".to_string(),
            "charlie@example.com".to_string(),
        );

        // "email" is a custom field but the default field_value() macro only handles "name" and "status"
        assert!(user.field_value("email").is_none());
        assert!(user.field_value("nonexistent").is_none());
    }

    #[test]
    fn test_data_entity_resource_name() {
        assert_eq!(TestUser::resource_name(), "test_users");
    }

    #[test]
    fn test_data_entity_resource_name_singular() {
        assert_eq!(TestUser::resource_name_singular(), "test_user");
    }

    #[test]
    fn test_link_entity_resource_name() {
        assert_eq!(TestOwnerLink::resource_name(), "test_owner_links");
        assert_eq!(TestOwnerLink::resource_name_singular(), "test_owner_link");
    }

    #[test]
    fn test_data_entity_indexed_fields() {
        let fields = TestUser::indexed_fields();
        assert!(fields.contains(&"name"));
        assert!(fields.contains(&"email"));
        assert_eq!(fields.len(), 2);
    }
}