sea-orm-macros 2.0.0-rc.38

Derive macros for SeaORM
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
use super::active_model::DeriveActiveModel;
use super::attributes::compound_attr;
use super::util::{extract_compound_entity, field_not_ignored_compound, is_compound_field};
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote};
use std::collections::HashMap;
use syn::{Attribute, Data, Expr, Fields, LitStr, Type, Visibility};

pub fn expand_derive_active_model_ex(
    vis: &Visibility,
    ident: &Ident,
    data: &Data,
    attrs: &[Attribute],
) -> syn::Result<TokenStream> {
    let mut compact = false;
    let mut model_fields = Vec::new();
    let mut ignored_model_fields = Vec::new();
    let mut field_types: Vec<Type> = Vec::new();
    let mut scalar_fields = Vec::new();
    let mut compound_fields = Vec::new();
    let mut belongs_to_fields = Vec::new();
    let mut belongs_to_self_fields = Vec::new();
    let mut has_one_fields = Vec::new();
    let mut has_many_fields = Vec::new();
    let mut has_many_self_fields = Vec::new();
    let mut has_many_via_fields = Vec::new();
    let mut has_many_via_self_fields = Vec::new();

    let (async_, await_) = async_await();

    attrs
        .iter()
        .filter(|attr| attr.path().is_ident("sea_orm"))
        .try_for_each(|attr| {
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("compact_model") {
                    compact = true;
                } else {
                    // Reads the value expression to advance the parse stream.
                    let _: Option<Expr> = meta.value().and_then(|v| v.parse()).ok();
                }
                Ok(())
            })
        })?;

    let mut entity_count = HashMap::new();

    if let Data::Struct(item_struct) = &data {
        if let Fields::Named(fields) = &item_struct.fields {
            for field in fields.named.iter() {
                if field.ident.is_some() && field_not_ignored_compound(field) {
                    let field_type = &field.ty;
                    let field_type: String = quote! { #field_type }
                        .to_string() // e.g.: "Option < String >"
                        .split_whitespace()
                        .collect(); // Remove all whitespace

                    if is_compound_field(&field_type) {
                        let entity_path = extract_compound_entity(&field_type);
                        *entity_count.entry(entity_path.to_owned()).or_insert(0) += 1;
                    }
                }
            }
        }
    }

    if let Data::Struct(item_struct) = &data {
        if let Fields::Named(fields) = &item_struct.fields {
            for field in fields.named.iter() {
                if let Some(ident) = &field.ident {
                    if field_not_ignored_compound(field) {
                        let field_type = &field.ty;
                        let field_type: String = quote! { #field_type }
                            .to_string() // e.g.: "Option < String >"
                            .split_whitespace()
                            .collect(); // Remove all whitespace

                        let ty = if is_compound_field(&field_type) {
                            compound_fields.push(ident);
                            let entity_path = extract_compound_entity(&field_type);

                            if !compact {
                                let compound_attrs =
                                    compound_attr::SeaOrm::from_attributes(&field.attrs)?;
                                if let Some(relation_enum) = compound_attrs.relation_enum {
                                    if compound_attrs.self_ref.is_some()
                                        && compound_attrs.via.is_none()
                                        && compound_attrs.from.is_some()
                                        && compound_attrs.to.is_some()
                                    {
                                        belongs_to_self_fields
                                            .push((ident.clone(), relation_enum.clone()));
                                    } else if compound_attrs.self_ref.is_some()
                                        && compound_attrs.relation_reverse.is_some()
                                        && compound_attrs.via.is_none()
                                        && compound_attrs.from.is_none()
                                        && compound_attrs.to.is_none()
                                    {
                                        has_many_self_fields
                                            .push((ident.clone(), relation_enum.clone()));
                                    }
                                } else if *entity_count.get(entity_path).unwrap() == 1 {
                                    // can only Related to another Entity once
                                    if compound_attrs.belongs_to.is_some() {
                                        belongs_to_fields.push(ident.clone());
                                    } else if compound_attrs.has_one.is_some() {
                                        has_one_fields.push(ident.clone());
                                    } else if compound_attrs.has_many.is_some()
                                        && compound_attrs.via.is_none()
                                    {
                                        has_many_fields.push(ident.clone());
                                    } else if compound_attrs.has_many.is_some()
                                        && compound_attrs.via.is_some()
                                    {
                                        has_many_via_fields.push((
                                            ident.clone(),
                                            compound_attrs.via.as_ref().unwrap().value(),
                                        ));
                                    }
                                }
                                if compound_attrs.self_ref.is_some()
                                    && compound_attrs.via.is_some()
                                    && compound_attrs.reverse.is_none()
                                {
                                    #[allow(clippy::unnecessary_unwrap)]
                                    has_many_via_self_fields.push((
                                        ident.clone(),
                                        compound_attrs.via.as_ref().unwrap().value(),
                                        false,
                                    ));
                                } else if compound_attrs.self_ref.is_some()
                                    && compound_attrs.via.is_some()
                                    && compound_attrs.reverse.is_some()
                                {
                                    #[allow(clippy::unnecessary_unwrap)]
                                    has_many_via_self_fields.push((
                                        ident.clone(),
                                        compound_attrs.via.as_ref().unwrap().value(),
                                        true,
                                    ));
                                }
                            }

                            if field_type.starts_with("HasOne<") {
                                syn::parse_str(&format!("HasOneModel < {entity_path} >"))?
                            } else {
                                syn::parse_str(&format!("HasManyModel < {entity_path} >"))?
                            }
                        } else {
                            scalar_fields.push(ident);
                            syn::parse_str(&format!("sea_orm::ActiveValue < {field_type} >"))?
                        };
                        model_fields.push(ident);
                        field_types.push(ty);
                    } else {
                        ignored_model_fields.push(ident);
                    }
                }
            }
        }
    }

    let active_model_trait_methods =
        DeriveActiveModel::new(vis, ident, data)?.impl_active_model_trait_methods();

    let active_model_action = expand_active_model_action(
        &belongs_to_fields,
        &belongs_to_self_fields,
        &has_one_fields,
        &has_many_fields,
        &has_many_self_fields,
        &has_many_via_fields,
        &has_many_via_self_fields,
    );

    let active_model_setters = expand_active_model_setters(data)?;

    let mut is_changed_expr = quote!(false);

    for field in scalar_fields.iter() {
        is_changed_expr.extend(quote!(|| self.#field.is_set()));
    }
    for field in compound_fields.iter() {
        is_changed_expr.extend(quote!(|| self.#field.is_changed()));
    }

    Ok(quote! {
        #[doc = " Generated by sea-orm-macros"]
        #[derive(Clone, Debug, PartialEq)]
        #vis struct ActiveModelEx {
            #(
                #[doc = " Generated by sea-orm-macros"]
                pub #model_fields: #field_types
            ),*
        }

        impl ActiveModel {
            #[doc = " Generated by sea-orm-macros"]
            pub fn into_ex(self) -> ActiveModelEx {
                self.into()
            }
        }

        #[automatically_derived]
        impl sea_orm::ActiveModelTrait for ActiveModelEx {
            type Entity = Entity;

            #active_model_trait_methods

            /// Returns true if any field is set or changed. This is recursive.
            fn is_changed(&self) -> bool {
                #is_changed_expr
            }

            fn default() -> Self {
                <ActiveModel as sea_orm::ActiveModelBehavior>::new().into()
            }
        }

        impl ActiveModelEx {
            #[doc = " Generated by sea-orm-macros"]
            pub fn new() -> Self {
                <Self as sea_orm::ActiveModelTrait>::default()
            }

            #active_model_action

            #active_model_setters
        }

        #[automatically_derived]
        impl std::default::Default for ActiveModelEx {
            fn default() -> Self {
                <Self as sea_orm::ActiveModelTrait>::default()
            }
        }

        #[automatically_derived]
        impl std::convert::From<ActiveModel> for ActiveModelEx {
            fn from(m: ActiveModel) -> Self {
                Self {
                    #(#scalar_fields: m.#scalar_fields,)*
                    #(#compound_fields: Default::default(),)*
                }
            }
        }

        #[automatically_derived]
        impl std::convert::From<ActiveModelEx> for ActiveModel {
            fn from(m: ActiveModelEx) -> Self {
                Self {
                    #(#scalar_fields: m.#scalar_fields,)*
                }
            }
        }

        #[automatically_derived]
        impl std::convert::From<ModelEx> for ActiveModelEx {
            fn from(m: ModelEx) -> Self {
                Self {
                    #(#scalar_fields: sea_orm::ActiveValue::Unchanged(m.#scalar_fields),)*
                    #(#compound_fields: m.#compound_fields.into_active_model(),)*
                }
            }
        }

        #[automatically_derived]
        impl std::convert::TryFrom<ActiveModelEx> for ModelEx {
            type Error = sea_orm::DbErr;
            fn try_from(a: ActiveModelEx) -> Result<Self, sea_orm::DbErr> {
                #(if a.#scalar_fields.is_not_set() {
                    return Err(sea_orm::DbErr::AttrNotSet(stringify!(#scalar_fields).to_owned()));
                })*
                Ok(
                    Self {
                        #(#scalar_fields: a.#scalar_fields.unwrap(),)*
                        #(#compound_fields: a.#compound_fields.try_into_model()?,)*
                        #(#ignored_model_fields: Default::default(),)*
                    }
                )
            }
        }

        #[automatically_derived]
        impl sea_orm::IntoActiveModel<ActiveModelEx> for ModelEx {
            fn into_active_model(self) -> ActiveModelEx {
                self.into()
            }
        }

        #[automatically_derived]
        impl sea_orm::TryIntoModel<ModelEx> for ActiveModelEx {
            fn try_into_model(self) -> Result<ModelEx, sea_orm::DbErr> {
                self.try_into()
            }
        }

        impl Model {
            #[doc = " Generated by sea-orm-macros"]
            pub #async_ fn cascade_delete<'a, C>(self, db: &'a C) -> Result<sea_orm::DeleteResult, sea_orm::DbErr>
            where
                C: sea_orm::TransactionTrait,
            {
                self.into_ex().delete(db)#await_
            }
        }

        impl ModelEx {
            #[doc = " Generated by sea-orm-macros"]
            pub #async_ fn delete<'a, C>(self, db: &'a C) -> Result<sea_orm::DeleteResult, sea_orm::DbErr>
            where
                C: sea_orm::TransactionTrait,
            {
                let active_model: ActiveModelEx = self.into();
                active_model.delete(db)#await_
            }
        }

        impl ActiveModel {
            #[doc = " Generated by sea-orm-macros"]
            pub fn builder() -> ActiveModelEx {
                ActiveModelEx::new()
            }
        }
    })
}

fn expand_active_model_action(
    belongs_to: &[Ident],
    belongs_to_self: &[(Ident, LitStr)],
    has_one: &[Ident],
    has_many: &[Ident],
    has_many_self: &[(Ident, LitStr)],
    has_many_via: &[(Ident, String)],
    has_many_via_self: &[(Ident, String, bool)],
) -> TokenStream {
    let mut belongs_to_action = TokenStream::new();
    let mut belongs_to_after_action = TokenStream::new();
    let mut has_one_before_action = TokenStream::new();
    let mut has_one_action = TokenStream::new();
    let mut has_one_delete = TokenStream::new();
    let mut has_many_before_action = TokenStream::new();
    let mut has_many_action = TokenStream::new();
    let mut has_many_delete = TokenStream::new();
    let mut has_many_via_before_action = TokenStream::new();
    let mut has_many_via_action = TokenStream::new();
    let mut has_many_via_delete = TokenStream::new();

    let (async_, await_) = async_await();
    let box_pin = if cfg!(feature = "async") {
        quote!(Box::pin)
    } else {
        quote!()
    };

    for field in belongs_to {
        belongs_to_action.extend(quote! {
            let #field = if let Some(model) = self.#field.take() {
                if model.is_update() {
                    // has primary key
                    self.set_parent_key(&model)?;
                    if model.is_changed() {
                        let model = #box_pin(model.action(action, db))#await_?;
                        Some(model)
                    } else {
                        Some(model)
                    }
                } else {
                    // new model
                    let model = #box_pin(model.action(action, db))#await_?;
                    self.set_parent_key(&model)?;
                    Some(model)
                }
            } else {
                None
            };
        });

        belongs_to_after_action.extend(quote! {
            if let Some(#field) = #field {
                model.#field = HasOneModel::set(#field);
            }
        });
    }

    for (field, relation_enum) in belongs_to_self {
        let relation_enum = Ident::new(&relation_enum.value(), relation_enum.span());
        let relation_enum = quote!(Relation::#relation_enum);

        // belongs to is the exception where action is performed before self
        belongs_to_action.extend(quote! {
            let #field = if let Some(model) = self.#field.take() {
                if model.is_update() {
                    // has primary key
                    self.set_parent_key_for(&model, #relation_enum)?;
                    if model.is_changed() {
                        let model = #box_pin(model.action(action, db))#await_?;
                        Some(model)
                    } else {
                        Some(model)
                    }
                } else {
                    // new model
                    let model = #box_pin(model.action(action, db))#await_?;
                    self.set_parent_key_for(&model, #relation_enum)?;
                    Some(model)
                }
            } else {
                None
            };
        });

        belongs_to_after_action.extend(quote! {
            if let Some(#field) = #field {
                model.#field = HasOneModel::set(#field);
            }
        });
    }

    let delete_associated_model = quote! {
        let mut item = item.into_active_model();
        if item.clear_parent_key::<Entity>()? {
            item.update(db)#await_?;
        } else {
            deleted.merge(item.into_ex().delete(db)#await_?); // deep delete
        }
    };

    for field in has_one {
        has_one_before_action.extend(quote! {
            let #field = self.#field.take();
        });

        has_one_action.extend(quote! {
            if let Some(mut #field) = #field {
                #field.set_parent_key(&model)?;
                if #field.is_changed() {
                    model.#field = HasOneModel::set(#box_pin(#field.action(action, db))#await_?);
                } else {
                    model.#field = HasOneModel::set(#field);
                }
            }
        });

        has_one_delete.extend(quote! {
            if let Some(item) = self.find_related_of(self.#field.empty_slice()).one(db)#await_? {
                #delete_associated_model
            }
        });
    }

    for field in has_many {
        has_many_before_action.extend(quote! {
            let #field = self.#field.take();
        });

        has_many_action.extend(quote! {
            if #field.is_replace() {
                for item in model.find_related_of(#field.as_slice()).all(db)#await_? {
                    if !#field.find(&item) {
                        #delete_associated_model
                    }
                }
            }
            model.#field = #field.empty_holder();
            for mut #field in #field.into_vec() {
                #field.set_parent_key(&model)?;
                if #field.is_changed() {
                    model.#field.push(#box_pin(#field.action(action, db))#await_?);
                } else {
                    model.#field.push(#field);
                }
            }
        });

        has_many_delete.extend(quote! {
            for item in self.find_related_of(self.#field.as_slice()).all(db)#await_? {
                #delete_associated_model
            }
        });
    }

    for (field, relation_enum) in has_many_self {
        let relation_enum = Ident::new(&relation_enum.value(), relation_enum.span());
        let relation_enum = quote!(Relation::#relation_enum);

        let delete_associated_model = quote! {
            let mut item = item.into_active_model();
            if item.clear_parent_key_for_self_rev(#relation_enum)? {
                item.update(db)#await_?;
            } else {
                // attempt to cascade delete may lead to infinite recursion
                return Err(sea_orm::DbErr::RecordNotUpdated);
            }
        };

        has_many_before_action.extend(quote! {
            let #field = self.#field.take();
        });

        has_many_action.extend(quote! {
            if #field.is_replace() {
                for item in model.find_belongs_to_self(#relation_enum, db.get_database_backend())?.all(db)#await_? {
                    if !#field.find(&item) {
                        #delete_associated_model
                    }
                }
            }
            model.#field = #field.empty_holder();
            for mut #field in #field.into_vec() {
                #field.set_parent_key_for_self_rev(&model, #relation_enum)?;
                if #field.is_changed() {
                    model.#field.push(#box_pin(#field.action(action, db))#await_?);
                } else {
                    model.#field.push(#field);
                }
            }
        });

        has_many_delete.extend(quote! {
            for item in self.find_belongs_to_self(#relation_enum, db.get_database_backend())?.all(db)#await_? {
                #delete_associated_model
            }
        });
    }

    for (field, via_entity) in has_many_via {
        let mut via_entity = via_entity.as_str();
        if let Some((prefix, _)) = via_entity.split_once("::") {
            via_entity = prefix;
        }

        let related_entity: TokenStream = format!("super::{via_entity}::Entity").parse().unwrap();

        has_many_via_before_action.extend(quote! {
            let #field = self.#field.take();
        });

        has_many_via_action.extend(quote! {
            model.#field = #field.empty_holder();
            for item in #field.into_vec() {
                if item.is_update() {
                    // has primary key
                    if item.is_changed() {
                        model.#field.push(#box_pin(item.action(action, db))#await_?);
                    } else {
                        model.#field.push(item);
                    }
                } else {
                    // new model
                    model.#field.push(#box_pin(item.action(action, db))#await_?);
                }
            }
            model.establish_links(
                #related_entity,
                model.#field.as_slice(),
                model.#field.is_replace(),
                db
            )#await_?;
        });

        has_many_via_delete.extend(quote! {
            deleted.merge(self.delete_links(#related_entity, db)#await_?);
        });
    }

    for (field, via_entity, reverse) in has_many_via_self {
        let related_entity: TokenStream = format!("super::{via_entity}::Entity").parse().unwrap();
        let establish_links = Ident::new(
            if *reverse {
                "establish_links_self_rev"
            } else {
                "establish_links_self"
            },
            field.span(),
        );

        has_many_via_before_action.extend(quote! {
            let #field = self.#field.take();
        });

        has_many_via_action.extend(quote! {
            model.#field = #field.empty_holder();
            for item in #field.into_vec() {
                if item.is_update() {
                    // has primary key
                    if item.is_changed() {
                        model.#field.push(#box_pin(item.action(action, db))#await_?);
                    } else {
                        model.#field.push(item);
                    }
                } else {
                    // new model
                    model.#field.push(#box_pin(item.action(action, db))#await_?);
                }
            }
            model.#establish_links(
                #related_entity,
                model.#field.as_slice(),
                model.#field.is_replace(),
                db
            )#await_?;
        });

        has_many_via_delete.extend(quote! {
            deleted.merge(self.delete_links_self(#related_entity, db)#await_?);
        });
    }

    quote! {
        #[doc = " Generated by sea-orm-macros"]
        pub #async_ fn insert<'a, C>(self, db: &'a C) -> Result<ModelEx, sea_orm::DbErr>
        where
            C: sea_orm::TransactionTrait,
        {
            let active_model = self.action(sea_orm::ActiveModelAction::Insert, db)#await_?;
            active_model.try_into()
        }

        #[doc = " Generated by sea-orm-macros"]
        pub #async_ fn update<'a, C>(self, db: &'a C) -> Result<ModelEx, sea_orm::DbErr>
        where
            C: sea_orm::TransactionTrait,
        {
            let active_model = self.action(sea_orm::ActiveModelAction::Update, db)#await_?;
            active_model.try_into()
        }

        #[doc = " Generated by sea-orm-macros"]
        pub #async_ fn save<'a, C>(self, db: &'a C) -> Result<Self, sea_orm::DbErr>
        where
            C: sea_orm::TransactionTrait,
        {
            self.action(sea_orm::ActiveModelAction::Save, db)#await_
        }

        #[doc = " Generated by sea-orm-macros"]
        pub #async_ fn delete<'a, C>(self, db: &'a C) -> Result<sea_orm::DeleteResult, sea_orm::DbErr>
        where
            C: sea_orm::TransactionTrait,
        {
            use sea_orm::{IntoActiveModel, TransactionSession};

            let txn = db.begin()#await_?;
            let db = &txn;
            let mut deleted = sea_orm::DeleteResult::empty();

            #has_one_delete
            #has_many_delete
            #has_many_via_delete

            let model: ActiveModel = self.into();
            deleted.merge(model.delete(db)#await_?);

            txn.commit()#await_?;

            Ok(deleted)
        }

        #[doc = " Generated by sea-orm-macros"]
        pub #async_ fn action<'a, C>(mut self, action: sea_orm::ActiveModelAction, db: &'a C) -> Result<Self, sea_orm::DbErr>
        where
            C: sea_orm::TransactionTrait,
        {
            use sea_orm::{HasOneModel, HasManyModel, IntoActiveModel, TransactionSession};
            let txn = db.begin()#await_?;
            let db = &txn;
            let mut deleted = sea_orm::DeleteResult::empty();

            #belongs_to_action
            #has_one_before_action
            #has_many_before_action
            #has_many_via_before_action

            let model: ActiveModel = self.into();

            let mut model: Self = if model.is_changed() {
                match action {
                    sea_orm::ActiveModelAction::Insert => model.insert(db)#await_,
                    sea_orm::ActiveModelAction::Update => model.update(db)#await_,
                    sea_orm::ActiveModelAction::Save => if !model.is_update() {
                        model.insert(db)#await_
                    } else {
                        model.update(db)#await_
                    },
                }?.into_ex().into()
            } else {
                model.into()
            };

            #belongs_to_after_action
            #has_one_action
            #has_many_action
            #has_many_via_action

            txn.commit()#await_?;

            Ok(model)
        }
    }
}

fn expand_active_model_setters(data: &Data) -> syn::Result<TokenStream> {
    let mut setters = TokenStream::new();

    if let Data::Struct(item_struct) = &data {
        if let Fields::Named(fields) = &item_struct.fields {
            for field in &fields.named {
                if let Some(ident) = &field.ident {
                    let field_type = &field.ty;
                    let field_type_str: String = quote! { #field_type }
                        .to_string() // e.g.: "Option < String >"
                        .split_whitespace()
                        .collect(); // Remove all whitespace

                    let mut ignore = false;

                    for attr in field.attrs.iter() {
                        if attr.path().is_ident("sea_orm") {
                            attr.parse_nested_meta(|meta| {
                                if meta.path.is_ident("ignore") {
                                    ignore = true;
                                } else {
                                    // Reads the value expression to advance the parse stream.
                                    let _: Option<Expr> = meta.value().and_then(|v| v.parse()).ok();
                                }

                                Ok(())
                            })?;
                        }
                    }

                    if ignore {
                        continue;
                    }

                    if is_compound_field(&field_type_str) {
                        let entity_path = extract_compound_entity(&field_type_str);
                        let active_model_type: Type = syn::parse_str(&format!(
                            "{}ActiveModelEx",
                            entity_path.trim_end_matches("Entity")
                        ))?;

                        if field_type_str.starts_with("HasOne<") {
                            let setter = format_ident!("set_{}", ident);

                            setters.extend(quote! {
                                #[doc = " Generated by sea-orm-macros"]
                                pub fn #setter(mut self, v: impl Into<#active_model_type>) -> Self {
                                    self.#ident.replace(v.into());
                                    self
                                }
                            });
                        } else {
                            let setter = format_ident!(
                                "add_{}",
                                pluralizer::pluralize(&ident.to_string(), 1, false)
                            );

                            setters.extend(quote! {
                                #[doc = " Generated by sea-orm-macros"]
                                pub fn #setter(mut self, v: impl Into<#active_model_type>) -> Self {
                                    self.#ident.push(v.into());
                                    self
                                }
                            });
                        }
                    } else {
                        let setter = format_ident!("set_{}", ident);

                        setters.extend(quote! {
                            #[doc = " Generated by sea-orm-macros"]
                            pub fn #setter(mut self, v: impl Into<#field_type>) -> Self {
                                self.#ident = sea_orm::Set(v.into());
                                self
                            }
                        });
                    }
                }
            }
        }
    }

    Ok(setters)
}

fn async_await() -> (TokenStream, TokenStream) {
    if cfg!(feature = "async") {
        (quote!(async), quote!(.await))
    } else {
        (quote!(), quote!())
    }
}