es-entity 0.10.33

Event Sourcing Entity Framework
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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
# Nesting

Building on the aggregate example from the previous chapter, let's implement the nested approach for our `Subscription` and `BillingPeriod` entities.
As discussed, this approach makes the aggregate relationship explicit in the type system and ensures all access to nested entities is moderated through the aggregate root.

## Setting up the Database Tables

First, we need to create the tables for both the parent (`Subscription`) and nested (`BillingPeriod`) entities:

```sql
-- The parent entity table
CREATE TABLE subscriptions (
  id UUID PRIMARY KEY,
  created_at TIMESTAMPTZ NOT NULL
);

CREATE TABLE subscription_events (
  id UUID NOT NULL REFERENCES subscriptions(id),
  sequence INT NOT NULL,
  event_type VARCHAR NOT NULL,
  event JSONB NOT NULL,
  context JSONB DEFAULT NULL,
  recorded_at TIMESTAMPTZ NOT NULL,
  UNIQUE(id, sequence)
);

-- The nested entity table
CREATE TABLE billing_periods (
  id UUID PRIMARY KEY,
  subscription_id UUID NOT NULL REFERENCES subscriptions(id),
  created_at TIMESTAMPTZ NOT NULL
);

CREATE TABLE billing_period_events (
  id UUID NOT NULL REFERENCES billing_periods(id),
  sequence INT NOT NULL,
  event_type VARCHAR NOT NULL,
  event JSONB NOT NULL,
  context JSONB DEFAULT NULL,
  recorded_at TIMESTAMPTZ NOT NULL,
  UNIQUE(id, sequence)
);
```

Note how the nested `index` table (`billing_periods`) includes a foreign key to the parent.

## Defining the Nested Entity

Let's start by implementing the `BillingPeriod` entity that will be nested inside `Subscription`.
There are no special requirements on the child `entity` and it can be setup just like always:

```rust
# extern crate es_entity;
# extern crate sqlx;
# extern crate serde;
# extern crate derive_builder;
# extern crate tokio;
# extern crate anyhow;
use derive_builder::Builder;
use es_entity::*;
use serde::{Deserialize, Serialize};

es_entity::entity_id! {
    SubscriptionId,
    BillingPeriodId
}

#[derive(EsEvent, Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[es_event(id = "BillingPeriodId")]
pub enum BillingPeriodEvent {
    Initialized {
        id: BillingPeriodId,
        subscription_id: SubscriptionId,
    },
    LineItemAdded {
        amount: f64,
        description: String,
    },
    Closed,
}

#[derive(EsEntity, Builder)]
#[builder(pattern = "owned", build_fn(error = "EntityHydrationError"))]
pub struct BillingPeriod {
    pub id: BillingPeriodId,
    pub subscription_id: SubscriptionId,
    pub is_current: bool,
    pub line_items: Vec<LineItem>,
    events: EntityEvents<BillingPeriodEvent>,
}

#[derive(Debug, Clone)]
pub struct LineItem {
    pub amount: f64,
    pub description: String,
}

impl BillingPeriod {
    pub fn add_line_item(&mut self, amount: f64, description: String) -> Idempotent<usize> {
        idempotency_guard!(
            self.events.iter_all().rev(),
            already_applied: BillingPeriodEvent::LineItemAdded { amount: a, description: d, .. }
                if a == &amount && d == &description
        );

        self.line_items.push(LineItem {
            amount,
            description: description.clone(),
        });

        self.events.push(BillingPeriodEvent::LineItemAdded {
            amount,
            description,
        });

        Idempotent::Executed(self.line_items.len())
    }

    pub fn close(&mut self) -> Idempotent<()> {
        idempotency_guard!(
            self.events.iter_all().rev(),
            already_applied: BillingPeriodEvent::Closed
        );

        self.is_current = false;
        self.events.push(BillingPeriodEvent::Closed);

        Idempotent::Executed(())
    }
}

impl TryFromEvents<BillingPeriodEvent> for BillingPeriod {
    fn try_from_events(events: EntityEvents<BillingPeriodEvent>) -> Result<Self, EntityHydrationError> {
        let mut builder = BillingPeriodBuilder::default().is_current(true);
        let mut line_items = Vec::new();

        for event in events.iter_all() {
            match event {
                BillingPeriodEvent::Initialized { id, subscription_id } => {
                    builder = builder.id(*id).subscription_id(*subscription_id);
                }
                BillingPeriodEvent::LineItemAdded { amount, description } => {
                    line_items.push(LineItem {
                        amount: *amount,
                        description: description.clone(),
                    });
                }
                BillingPeriodEvent::Closed => {
                    builder = builder.is_current(false)
                }
            }
        }

        builder
            .line_items(line_items)
            .events(events)
            .build()
    }
}

#[derive(Debug, Clone, Builder)]
pub struct NewBillingPeriod {
    pub id: BillingPeriodId,
    pub subscription_id: SubscriptionId,
}

impl IntoEvents<BillingPeriodEvent> for NewBillingPeriod {
    fn into_events(self) -> EntityEvents<BillingPeriodEvent> {
        EntityEvents::init(
            self.id,
            vec![BillingPeriodEvent::Initialized {
                id: self.id,
                subscription_id: self.subscription_id,
            }],
        )
    }
}
```

## Defining the Parent Entity with Nested Children

Now let's implement the `Subscription` entity that will contain the nested `BillingPeriod` entities:

```rust
# extern crate es_entity;
# extern crate sqlx;
# extern crate serde;
# extern crate derive_builder;
# extern crate tokio;
# extern crate anyhow;
# use derive_builder::Builder;
# use es_entity::*;
# use serde::{Deserialize, Serialize};
#
# es_entity::entity_id! {
#     SubscriptionId,
#     BillingPeriodId
# }
#
# #[derive(EsEvent, Debug, Clone, Serialize, Deserialize)]
# #[serde(tag = "type", rename_all = "snake_case")]
# #[es_event(id = "BillingPeriodId")]
# pub enum BillingPeriodEvent {
#     Initialized {
#         id: BillingPeriodId,
#         subscription_id: SubscriptionId,
#     },
#     LineItemAdded {
#         amount: f64,
#         description: String,
#     },
#     Closed,
# }
#
# #[derive(EsEntity, Builder)]
# #[builder(pattern = "owned", build_fn(error = "EntityHydrationError"))]
# pub struct BillingPeriod {
#     pub id: BillingPeriodId,
#     pub subscription_id: SubscriptionId,
#     pub is_current: bool,
#     pub line_items: Vec<LineItem>,
#     events: EntityEvents<BillingPeriodEvent>,
# }
#
# #[derive(Debug, Clone)]
# pub struct LineItem {
#     pub amount: f64,
#     pub description: String,
# }
#
# impl BillingPeriod {
#     pub fn add_line_item(&mut self, amount: f64, description: String) -> Idempotent<usize> {
#         idempotency_guard!(
#             self.events.iter_all().rev(),
#             already_applied: BillingPeriodEvent::LineItemAdded { amount: a, description: d, .. }
#                 if a == &amount && d == &description
#         );
#
#         self.line_items.push(LineItem {
#             amount,
#             description: description.clone(),
#         });
#
#         self.events.push(BillingPeriodEvent::LineItemAdded {
#             amount,
#             description,
#         });
#
#         Idempotent::Executed(self.line_items.len())
#     }
#
#     pub fn close(&mut self) -> Idempotent<()> {
#         idempotency_guard!(
#             self.events.iter_all().rev(),
#             already_applied: BillingPeriodEvent::Closed
#         );
#
#         self.is_current = false;
#         self.events.push(BillingPeriodEvent::Closed);
#
#         Idempotent::Executed(())
#     }
# }
#
# impl TryFromEvents<BillingPeriodEvent> for BillingPeriod {
#     fn try_from_events(events: EntityEvents<BillingPeriodEvent>) -> Result<Self, EntityHydrationError> {
#         let mut builder = BillingPeriodBuilder::default().is_current(true);
#         let mut line_items = Vec::new();
#
#         for event in events.iter_all() {
#             match event {
#                 BillingPeriodEvent::Initialized { id, subscription_id } => {
#                     builder = builder.id(*id).subscription_id(*subscription_id);
#                 }
#                 BillingPeriodEvent::LineItemAdded { amount, description } => {
#                     line_items.push(LineItem {
#                         amount: *amount,
#                         description: description.clone(),
#                     });
#                 }
#                 BillingPeriodEvent::Closed => {
#                     builder = builder.is_current(false)
#                 }
#             }
#         }
#
#         builder
#             .line_items(line_items)
#             .events(events)
#             .build()
#     }
# }
#
# #[derive(Debug, Clone, Builder)]
# pub struct NewBillingPeriod {
#     pub id: BillingPeriodId,
#     pub subscription_id: SubscriptionId,
# }
#
# impl IntoEvents<BillingPeriodEvent> for NewBillingPeriod {
#     fn into_events(self) -> EntityEvents<BillingPeriodEvent> {
#         EntityEvents::init(
#             self.id,
#             vec![BillingPeriodEvent::Initialized {
#                 id: self.id,
#                 subscription_id: self.subscription_id,
#             }],
#         )
#     }
# }
#[derive(EsEvent, Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[es_event(id = "SubscriptionId")]
pub enum SubscriptionEvent {
    Initialized { id: SubscriptionId },
    BillingPeriodStarted { period_id: BillingPeriodId },
}

#[derive(EsEntity, Builder)]
#[builder(pattern = "owned", build_fn(error = "EntityHydrationError"))]
pub struct Subscription {
    pub id: SubscriptionId,
    current_period_id: Option<BillingPeriodId>,
    events: EntityEvents<SubscriptionEvent>,

    // The `#[es_entity(nested)]` attribute marks this field as containing nested entities.
    // It must be of type `Nested<T>`.
    // The #[builder(default)] will initialize it as empty.
    // The Repository will load the children after the parent as been hydrated.
    #[es_entity(nested)]
    #[builder(default)]
    billing_periods: Nested<BillingPeriod>,
}

impl Subscription {
    pub fn start_new_billing_period(&mut self) -> Idempotent<BillingPeriodId> {
        // Close the current billing period if there is one
        if let Some(current_id) = self.current_period_id {
            if let Some(current_period) = self.billing_periods.get_persisted_mut(&current_id) {
                current_period.close();
            }
        }

        // Create the new billing period
        let new_period = NewBillingPeriod {
            id: BillingPeriodId::new(),
            subscription_id: self.id,
        };

        let id = new_period.id;
        self.billing_periods.add_new(new_period);

        // Update the current period tracking
        self.current_period_id = Some(id);
        self.events.push(SubscriptionEvent::BillingPeriodStarted { period_id: id });

        Idempotent::Executed(id)
    }

    pub fn add_line_item_to_current_billing_period(&mut self, amount: f64, description: String) -> Idempotent<usize> {
        // Use the tracked current period ID to access the billing period directly
        if let Some(current_id) = self.current_period_id {
            if let Some(current_period) = self.billing_periods.get_persisted_mut(&current_id) {
                return current_period.add_line_item(amount, description);
            }
        }

        Idempotent::AlreadyApplied
    }
}

impl TryFromEvents<SubscriptionEvent> for Subscription {
    fn try_from_events(events: EntityEvents<SubscriptionEvent>) -> Result<Self, EntityHydrationError> {
        let mut builder = SubscriptionBuilder::default();

        for event in events.iter_all() {
            match event {
                SubscriptionEvent::Initialized { id } => {
                    builder = builder.id(*id);
                }
                SubscriptionEvent::BillingPeriodStarted { period_id } => {
                    builder = builder.current_period_id(Some(*period_id));
                }
            }
        }

        builder
            .events(events)
            .build()
    }
}

#[derive(Debug, Clone, Builder)]
pub struct NewSubscription {
    pub id: SubscriptionId,
}

impl IntoEvents<SubscriptionEvent> for NewSubscription {
    fn into_events(self) -> EntityEvents<SubscriptionEvent> {
        EntityEvents::init(
            self.id,
            vec![SubscriptionEvent::Initialized { id: self.id }],
        )
    }
}
```

The key points to note:
1. The `billing_periods` field is marked with `#[es_entity(nested)]`
2. The field type is `Nested<BillingPeriod>` which is a special container for nested entities
3. We use `add_new()` to add new nested entities
4. We mutate the children via `get_persisted_mut()`.

Under the hood the `EsEntity` macro will create an implementation of the `Parent` trait:
```rust,ignore
pub trait Parent<T: EsEntity> {
    fn new_children_mut(&mut self) -> &mut Vec<<T as EsEntity>::New>;
    fn iter_persisted_children_mut<'a>(&'a mut self) -> impl Iterator<Item = &'a mut T>
    where
        T: 'a;
    fn inject_children(&mut self, entities: impl IntoIterator<Item = T>);
}
```

for every field marked `#[es_entity(nested)]`.


## Setting up the Repositories

The repository setup is where the magic happens for nested entities.
We need to configure both the parent and child repositories with special attributes.
It is recommended to put both Repositories in the same file but only mark the parent one as `pub`.
This leverages the rust module system to enforce that the children cannot be accessed directly.

```rust
# extern crate es_entity;
# extern crate sqlx;
# extern crate serde;
# extern crate derive_builder;
# extern crate tokio;
# extern crate anyhow;
# use derive_builder::Builder;
# use es_entity::*;
# use serde::{Deserialize, Serialize};
#
# es_entity::entity_id! {
#     SubscriptionId,
#     BillingPeriodId
# }
#
# #[derive(EsEvent, Debug, Clone, Serialize, Deserialize)]
# #[serde(tag = "type", rename_all = "snake_case")]
# #[es_event(id = "BillingPeriodId")]
# pub enum BillingPeriodEvent {
#     Initialized {
#         id: BillingPeriodId,
#         subscription_id: SubscriptionId,
#     },
#     LineItemAdded {
#         amount: f64,
#         description: String,
#     },
#     Closed,
# }
#
# #[derive(EsEntity, Builder)]
# #[builder(pattern = "owned", build_fn(error = "EntityHydrationError"))]
# pub struct BillingPeriod {
#     pub id: BillingPeriodId,
#     pub subscription_id: SubscriptionId,
#     pub is_current: bool,
#     pub line_items: Vec<LineItem>,
#     events: EntityEvents<BillingPeriodEvent>,
# }
#
# #[derive(Debug, Clone)]
# pub struct LineItem {
#     pub amount: f64,
#     pub description: String,
# }
#
# impl BillingPeriod {
#     pub fn add_line_item(&mut self, amount: f64, description: String) -> Idempotent<usize> {
#         idempotency_guard!(
#             self.events.iter_all().rev(),
#             already_applied: BillingPeriodEvent::LineItemAdded { amount: a, description: d, .. }
#                 if a == &amount && d == &description
#         );
#
#         self.line_items.push(LineItem {
#             amount,
#             description: description.clone(),
#         });
#
#         self.events.push(BillingPeriodEvent::LineItemAdded {
#             amount,
#             description,
#         });
#
#         Idempotent::Executed(self.line_items.len())
#     }
#
#     pub fn close(&mut self) -> Idempotent<()> {
#         idempotency_guard!(
#             self.events.iter_all().rev(),
#             already_applied: BillingPeriodEvent::Closed
#         );
#
#         self.is_current = false;
#         self.events.push(BillingPeriodEvent::Closed);
#
#         Idempotent::Executed(())
#     }
# }
#
# impl TryFromEvents<BillingPeriodEvent> for BillingPeriod {
#     fn try_from_events(events: EntityEvents<BillingPeriodEvent>) -> Result<Self, EntityHydrationError> {
#         let mut builder = BillingPeriodBuilder::default().is_current(true);
#         let mut line_items = Vec::new();
#
#         for event in events.iter_all() {
#             match event {
#                 BillingPeriodEvent::Initialized { id, subscription_id } => {
#                     builder = builder.id(*id).subscription_id(*subscription_id);
#                 }
#                 BillingPeriodEvent::LineItemAdded { amount, description } => {
#                     line_items.push(LineItem {
#                         amount: *amount,
#                         description: description.clone(),
#                     });
#                 }
#                 BillingPeriodEvent::Closed => {
#                     builder = builder.is_current(false)
#                 }
#             }
#         }
#
#         builder
#             .line_items(line_items)
#             .events(events)
#             .build()
#     }
# }
#
# #[derive(Debug, Clone, Builder)]
# pub struct NewBillingPeriod {
#     pub id: BillingPeriodId,
#     pub subscription_id: SubscriptionId,
# }
#
# impl IntoEvents<BillingPeriodEvent> for NewBillingPeriod {
#     fn into_events(self) -> EntityEvents<BillingPeriodEvent> {
#         EntityEvents::init(
#             self.id,
#             vec![BillingPeriodEvent::Initialized {
#                 id: self.id,
#                 subscription_id: self.subscription_id,
#             }],
#         )
#     }
# }
# #[derive(EsEvent, Debug, Clone, Serialize, Deserialize)]
# #[serde(tag = "type", rename_all = "snake_case")]
# #[es_event(id = "SubscriptionId")]
# pub enum SubscriptionEvent {
#     Initialized { id: SubscriptionId },
#     BillingPeriodStarted { period_id: BillingPeriodId },
# }
#
# #[derive(EsEntity, Builder)]
# #[builder(pattern = "owned", build_fn(error = "EntityHydrationError"))]
# pub struct Subscription {
#     pub id: SubscriptionId,
#     current_period_id: Option<BillingPeriodId>,
#     events: EntityEvents<SubscriptionEvent>,
#
#     #[es_entity(nested)]
#     #[builder(default)]
#     billing_periods: Nested<BillingPeriod>,
# }
#
# impl TryFromEvents<SubscriptionEvent> for Subscription {
#     fn try_from_events(events: EntityEvents<SubscriptionEvent>) -> Result<Self, EntityHydrationError> {
#         let mut builder = SubscriptionBuilder::default();
#
#         for event in events.iter_all() {
#             match event {
#                 SubscriptionEvent::Initialized { id } => {
#                     builder = builder.id(*id);
#                 }
#                 SubscriptionEvent::BillingPeriodStarted { period_id } => {
#                     builder = builder.current_period_id(Some(*period_id));
#                 }
#             }
#         }
#
#         builder
#             .events(events)
#             .build()
#     }
# }
#
# #[derive(Debug, Clone, Builder)]
# pub struct NewSubscription {
#     pub id: SubscriptionId,
# }
#
# impl IntoEvents<SubscriptionEvent> for NewSubscription {
#     fn into_events(self) -> EntityEvents<SubscriptionEvent> {
#         EntityEvents::init(
#             self.id,
#             vec![SubscriptionEvent::Initialized { id: self.id }],
#         )
#     }
# }
# fn main() {}
#[derive(EsRepo)]
#[es_repo(
    entity = "BillingPeriod",
    columns(
        // The foreign key of the parent marked by `parent`.
        subscription_id(ty = "SubscriptionId", update(persist = false), parent)
    )
)]
// private struct
struct BillingPeriods {
    pool: sqlx::PgPool,
}

#[derive(EsRepo)]
#[es_repo(entity = "Subscription")]
pub struct Subscriptions {
    pool: sqlx::PgPool,

    // Mark this field as containing the nested repository
    #[es_repo(nested)]
    billing_periods: BillingPeriods,
}

impl Subscriptions {
    pub fn new(pool: sqlx::PgPool) -> Self {
        Self {
            pool: pool.clone(),
            billing_periods: BillingPeriods { pool },
        }
    }
}
```

The important configuration here:
1. The child repository (`BillingPeriods`) marks the foreign key column with `parent`.
2. The parent repository (`Subscriptions`) includes the child repository as a field marked with `#[es_repo(nested)]`

## Using Nested Entities

Now we can use our aggregate with full type safety and automatic loading of nested entities:

```rust
# extern crate es_entity;
# extern crate sqlx;
# extern crate serde;
# extern crate derive_builder;
# extern crate tokio;
# extern crate anyhow;
# use derive_builder::Builder;
# use es_entity::*;
# use serde::{Deserialize, Serialize};
# es_entity::entity_id! {
#     SubscriptionId,
#     BillingPeriodId
# }
# #[derive(EsEvent, Debug, Clone, Serialize, Deserialize)]
# #[serde(tag = "type", rename_all = "snake_case")]
# #[es_event(id = "BillingPeriodId")]
# pub enum BillingPeriodEvent {
#     Initialized {
#         id: BillingPeriodId,
#         subscription_id: SubscriptionId,
#     },
#     LineItemAdded {
#         amount: f64,
#         description: String,
#     },
#     Closed,
# }
# #[derive(EsEntity, Builder)]
# #[builder(pattern = "owned", build_fn(error = "EntityHydrationError"))]
# pub struct BillingPeriod {
#     pub id: BillingPeriodId,
#     pub subscription_id: SubscriptionId,
#     pub is_current: bool,
#     pub line_items: Vec<LineItem>,
#     events: EntityEvents<BillingPeriodEvent>,
# }
# #[derive(Debug, Clone)]
# pub struct LineItem {
#     pub amount: f64,
#     pub description: String,
# }
# impl BillingPeriod {
#     pub fn add_line_item(&mut self, amount: f64, description: String) -> Idempotent<usize> {
#         if !self.is_current {
#             unreachable!()
#         }
#         idempotency_guard!(
#             self.events.iter_all().rev(),
#             already_applied: BillingPeriodEvent::LineItemAdded { amount: a, description: d, .. }
#                 if a == &amount && d == &description
#         );
#         self.line_items.push(LineItem {
#             amount,
#             description: description.clone(),
#         });
#         self.events.push(BillingPeriodEvent::LineItemAdded {
#             amount,
#             description,
#         });
#         Idempotent::Executed(self.line_items.len())
#     }
#     pub fn close(&mut self) -> Idempotent<()> {
#         idempotency_guard!(
#             self.events.iter_all().rev(),
#             already_applied: BillingPeriodEvent::Closed
#         );
#         self.is_current = false;
#         self.events.push(BillingPeriodEvent::Closed);
#         Idempotent::Executed(())
#     }
# }
# impl TryFromEvents<BillingPeriodEvent> for BillingPeriod {
#     fn try_from_events(events: EntityEvents<BillingPeriodEvent>) -> Result<Self, EntityHydrationError> {
#         let mut builder = BillingPeriodBuilder::default();
#         let mut line_items = Vec::new();
#         let mut is_current = true;
#         for event in events.iter_all() {
#             match event {
#                 BillingPeriodEvent::Initialized { id, subscription_id } => {
#                     builder = builder.id(*id).subscription_id(*subscription_id);
#                 }
#                 BillingPeriodEvent::LineItemAdded { amount, description } => {
#                     line_items.push(LineItem {
#                         amount: *amount,
#                         description: description.clone(),
#                     });
#                 }
#                 BillingPeriodEvent::Closed => {
#                     is_current = false;
#                 }
#             }
#         }
#         builder
#             .is_current(is_current)
#             .line_items(line_items)
#             .events(events)
#             .build()
#     }
# }
# #[derive(Debug, Clone, Builder)]
# pub struct NewBillingPeriod {
#     pub id: BillingPeriodId,
#     pub subscription_id: SubscriptionId,
# }
# impl IntoEvents<BillingPeriodEvent> for NewBillingPeriod {
#     fn into_events(self) -> EntityEvents<BillingPeriodEvent> {
#         EntityEvents::init(
#             self.id,
#             vec![BillingPeriodEvent::Initialized {
#                 id: self.id,
#                 subscription_id: self.subscription_id,
#             }],
#         )
#     }
# }
# #[derive(EsEvent, Debug, Clone, Serialize, Deserialize)]
# #[serde(tag = "type", rename_all = "snake_case")]
# #[es_event(id = "SubscriptionId")]
# pub enum SubscriptionEvent {
#     Initialized { id: SubscriptionId },
#     BillingPeriodStarted { period_id: BillingPeriodId },
# }
# #[derive(EsEntity, Builder)]
# #[builder(pattern = "owned", build_fn(error = "EntityHydrationError"))]
# pub struct Subscription {
#     pub id: SubscriptionId,
#     current_period_id: Option<BillingPeriodId>,
#     events: EntityEvents<SubscriptionEvent>,
#     #[es_entity(nested)]
#     #[builder(default)]
#     billing_periods: Nested<BillingPeriod>,
# }
# impl Subscription {
#     pub fn start_new_billing_period(&mut self) -> Idempotent<BillingPeriodId> {
#         if let Some(current_id) = self.current_period_id {
#             if let Some(current_period) = self.billing_periods.get_persisted_mut(&current_id) {
#                 current_period.close();
#             }
#         }
#         let new_period = NewBillingPeriod {
#             id: BillingPeriodId::new(),
#             subscription_id: self.id,
#         };
#         let id = new_period.id;
#         self.billing_periods.add_new(new_period);
#         self.current_period_id = Some(id);
#         self.events.push(SubscriptionEvent::BillingPeriodStarted { period_id: id });
#         Idempotent::Executed(id)
#     }
#     pub fn add_line_item_to_current_billing_period(&mut self, amount: f64, description: String) -> Idempotent<usize> {
#         if let Some(current_id) = self.current_period_id {
#             if let Some(current_period) = self.billing_periods.get_persisted_mut(&current_id) {
#                 return current_period.add_line_item(amount, description);
#             }
#         }
#         Idempotent::AlreadyApplied
#     }
#     pub fn current_billing_period(&self) -> Option<&BillingPeriod> {
#         self.current_period_id
#             .and_then(|id| self.billing_periods.get_persisted(&id))
#     }
# }
# impl TryFromEvents<SubscriptionEvent> for Subscription {
#     fn try_from_events(events: EntityEvents<SubscriptionEvent>) -> Result<Self, EntityHydrationError> {
#         let mut builder = SubscriptionBuilder::default();
#         let mut current_period_id = None;
#         for event in events.iter_all() {
#             match event {
#                 SubscriptionEvent::Initialized { id } => {
#                     builder = builder.id(*id);
#                 }
#                 SubscriptionEvent::BillingPeriodStarted { period_id } => {
#                     current_period_id = Some(*period_id);
#                 }
#             }
#         }
#         builder
#             .current_period_id(current_period_id)
#             .events(events)
#             .build()
#     }
# }
# #[derive(Debug, Clone, Builder)]
# pub struct NewSubscription {
#     pub id: SubscriptionId,
# }
# impl IntoEvents<SubscriptionEvent> for NewSubscription {
#     fn into_events(self) -> EntityEvents<SubscriptionEvent> {
#         EntityEvents::init(
#             self.id,
#             vec![SubscriptionEvent::Initialized { id: self.id }],
#         )
#     }
# }
# #[derive(EsRepo)]
# #[es_repo(
#     entity = "BillingPeriod",
#     columns(
#         subscription_id(ty = "SubscriptionId", update(persist = false), parent)
#     )
# )]
# pub struct BillingPeriods {
#     pool: sqlx::PgPool,
# }
# #[derive(EsRepo)]
# #[es_repo(entity = "Subscription")]
# pub struct Subscriptions {
#     pool: sqlx::PgPool,
#     #[es_repo(nested)]
#     billing_periods: BillingPeriods,
# }
# impl Subscriptions {
#     pub fn new(pool: sqlx::PgPool) -> Self {
#         Self {
#             pool: pool.clone(),
#             billing_periods: BillingPeriods { pool },
#         }
#     }
# }
# async fn init_pool() -> anyhow::Result<sqlx::PgPool> {
#     let pg_con = format!("postgres://user:password@localhost:5432/pg");
#     Ok(sqlx::PgPool::connect(&pg_con).await?)
# }
#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let subscriptions = Subscriptions::new(init_pool().await?);

    // Create a new subscription
    let subscription_id = SubscriptionId::new();
    let new_subscription = NewSubscription { id: subscription_id };
    let mut subscription = subscriptions.create(new_subscription).await?;

    // Start a billing period
    subscription.start_new_billing_period();

    // Add some line items to the current period
    subscription.add_line_item_to_current_billing_period(
        100.0,
        "Monthly subscription fee".to_string()
    );
    subscription.add_line_item_to_current_billing_period(
        25.0,
        "Additional service charge".to_string()
    );

    // Persist all changes (both parent and nested entities)
    subscriptions.update(&mut subscription).await?;

    // Load the subscription - nested entities are automatically loaded
    let loaded = subscriptions.find_by_id(subscription_id).await?;

    // Access the current billing period
    if let Some(current_period) = loaded.current_billing_period() {
        println!("Current period has {} line items", current_period.line_items.len());
        for item in &current_period.line_items {
            println!("  - {}: ${}", item.description, item.amount);
        }
    }

    Ok(())
}
```

One thing to note is that  the `_in_op` functions of the parent repository now require an `AtomicOperation` argument since we must load all the entities in a consistent snapshot:
```rust,ignore
async fn find_by_id_in_op<OP>(op: OP, id: EntityId)
where
    OP: AtomicOperation;

// The version of the queries in Repositories without nested children
// cannot be used here as it would not load parent + children from a consistent snapshot.
// async fn find_by_id_in_op<'a, OP>(op: OP, id: EntityId)
// where
//     OP: IntoOneTimeExecutor<'a>;
```

## Benefits of the Nested Approach

This approach provides several key benefits:

1. **Type Safety**: The aggregate boundary is enforced at compile time
2. **Atomic Updates**: All changes to the aggregate are persisted together
3. **Automatic Loading**: When you load the parent, all nested entities are loaded automatically
4. **Encapsulation**: All access to nested entities goes through the aggregate root
5. **Consistency**: The parent entity can enforce invariants across all its children

## Performance Considerations

While nesting provides strong consistency guarantees, there are some performance implications to consider:

1. **Loading**: All nested entities are loaded when the parent is loaded. For aggregates with many children, this could impact performance.
2. **Updates**: All nested entities are checked for changes during updates, even if only one was modified.
3. **Memory**: The entire aggregate is held in memory, which could be significant for large aggregates.

For these reasons, it's important to keep aggregates small and focused on a specific consistency boundary.

## When to Use Nesting

Use the nested approach when:
- You have a true invariant that spans multiple entities
- The child entities have no meaning without the parent
- You need to enforce consistency rules across the relationship
- The number of child entities is reasonably bounded

Avoid nesting when:
- The relationship is merely associative
- Child entities can exist independently
- You expect unbounded growth in the number of children
- Performance requirements dictate more granular loading/updating

Remember, as discussed in the aggregates chapter, there are often alternative designs that can avoid the need for nesting while still maintaining consistency.