-
-
Notifications
You must be signed in to change notification settings - Fork 521
/
writer.rs
2496 lines (2387 loc) Β· 88 KB
/
writer.rs
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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::{util::escape_rust_keyword, ActiveEnum, Entity};
use heck::ToUpperCamelCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use std::{collections::BTreeMap, str::FromStr};
use syn::{punctuated::Punctuated, token::Comma};
use tracing::info;
#[derive(Clone, Debug)]
pub struct EntityWriter {
pub(crate) entities: Vec<Entity>,
pub(crate) enums: BTreeMap<String, ActiveEnum>,
}
pub struct WriterOutput {
pub files: Vec<OutputFile>,
}
pub struct OutputFile {
pub name: String,
pub content: String,
}
#[derive(PartialEq, Eq, Debug)]
pub enum WithSerde {
None,
Serialize,
Deserialize,
Both,
}
#[derive(Debug)]
pub enum DateTimeCrate {
Chrono,
Time,
}
#[derive(Debug)]
pub struct EntityWriterContext {
pub(crate) expanded_format: bool,
pub(crate) with_serde: WithSerde,
pub(crate) with_copy_enums: bool,
pub(crate) date_time_crate: DateTimeCrate,
pub(crate) schema_name: Option<String>,
pub(crate) lib: bool,
pub(crate) serde_skip_hidden_column: bool,
pub(crate) serde_skip_deserializing_primary_key: bool,
pub(crate) model_extra_derives: TokenStream,
pub(crate) model_extra_attributes: TokenStream,
pub(crate) enum_extra_derives: TokenStream,
pub(crate) enum_extra_attributes: TokenStream,
pub(crate) seaography: bool,
}
impl WithSerde {
pub fn extra_derive(&self) -> TokenStream {
let mut extra_derive = match self {
Self::None => {
quote! {}
}
Self::Serialize => {
quote! {
Serialize
}
}
Self::Deserialize => {
quote! {
Deserialize
}
}
Self::Both => {
quote! {
Serialize, Deserialize
}
}
};
if !extra_derive.is_empty() {
extra_derive = quote! { , #extra_derive }
}
extra_derive
}
}
/// Converts *_extra_derives argument to token stream
pub(crate) fn bonus_derive<T, I>(extra_derives: I) -> TokenStream
where
T: Into<String>,
I: IntoIterator<Item = T>,
{
extra_derives.into_iter().map(Into::<String>::into).fold(
TokenStream::default(),
|acc, derive| {
let tokens: TokenStream = derive.parse().unwrap();
quote! { #acc, #tokens }
},
)
}
/// convert *_extra_attributes argument to token stream
pub(crate) fn bonus_attributes<T, I>(attributes: I) -> TokenStream
where
T: Into<String>,
I: IntoIterator<Item = T>,
{
attributes.into_iter().map(Into::<String>::into).fold(
TokenStream::default(),
|acc, attribute| {
let tokens: TokenStream = attribute.parse().unwrap();
quote! {
#acc
#[#tokens]
}
},
)
}
impl FromStr for WithSerde {
type Err = crate::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"none" => Self::None,
"serialize" => Self::Serialize,
"deserialize" => Self::Deserialize,
"both" => Self::Both,
v => {
return Err(crate::Error::TransformError(format!(
"Unsupported enum variant '{v}'"
)))
}
})
}
}
impl EntityWriterContext {
#[allow(clippy::too_many_arguments)]
pub fn new(
expanded_format: bool,
with_serde: WithSerde,
with_copy_enums: bool,
date_time_crate: DateTimeCrate,
schema_name: Option<String>,
lib: bool,
serde_skip_deserializing_primary_key: bool,
serde_skip_hidden_column: bool,
model_extra_derives: Vec<String>,
model_extra_attributes: Vec<String>,
enum_extra_derives: Vec<String>,
enum_extra_attributes: Vec<String>,
seaography: bool,
) -> Self {
Self {
expanded_format,
with_serde,
with_copy_enums,
date_time_crate,
schema_name,
lib,
serde_skip_deserializing_primary_key,
serde_skip_hidden_column,
model_extra_derives: bonus_derive(model_extra_derives),
model_extra_attributes: bonus_attributes(model_extra_attributes),
enum_extra_derives: bonus_derive(enum_extra_derives),
enum_extra_attributes: bonus_attributes(enum_extra_attributes),
seaography,
}
}
}
impl EntityWriter {
pub fn generate(self, context: &EntityWriterContext) -> WriterOutput {
let mut files = Vec::new();
files.extend(self.write_entities(context));
files.push(self.write_index_file(context.lib, context.seaography));
files.push(self.write_prelude());
if !self.enums.is_empty() {
files.push(self.write_sea_orm_active_enums(
&context.with_serde,
context.with_copy_enums,
&context.enum_extra_derives,
&context.enum_extra_attributes,
));
}
WriterOutput { files }
}
pub fn write_entities(&self, context: &EntityWriterContext) -> Vec<OutputFile> {
self.entities
.iter()
.map(|entity| {
let entity_file = format!("{}.rs", entity.get_table_name_snake_case());
let column_info = entity
.columns
.iter()
.map(|column| column.get_info(&context.date_time_crate))
.collect::<Vec<String>>();
// Serde must be enabled to use this
let serde_skip_deserializing_primary_key = context
.serde_skip_deserializing_primary_key
&& matches!(context.with_serde, WithSerde::Both | WithSerde::Deserialize);
let serde_skip_hidden_column = context.serde_skip_hidden_column
&& matches!(
context.with_serde,
WithSerde::Both | WithSerde::Serialize | WithSerde::Deserialize
);
info!("Generating {}", entity_file);
for info in column_info.iter() {
info!(" > {}", info);
}
let mut lines = Vec::new();
Self::write_doc_comment(&mut lines);
let code_blocks = if context.expanded_format {
Self::gen_expanded_code_blocks(
entity,
&context.with_serde,
&context.date_time_crate,
&context.schema_name,
serde_skip_deserializing_primary_key,
serde_skip_hidden_column,
&context.model_extra_derives,
&context.model_extra_attributes,
context.seaography,
)
} else {
Self::gen_compact_code_blocks(
entity,
&context.with_serde,
&context.date_time_crate,
&context.schema_name,
serde_skip_deserializing_primary_key,
serde_skip_hidden_column,
&context.model_extra_derives,
&context.model_extra_attributes,
context.seaography,
)
};
Self::write(&mut lines, code_blocks);
OutputFile {
name: entity_file,
content: lines.join("\n\n"),
}
})
.collect()
}
pub fn write_index_file(&self, lib: bool, seaography: bool) -> OutputFile {
let mut lines = Vec::new();
Self::write_doc_comment(&mut lines);
let code_blocks: Vec<TokenStream> = self.entities.iter().map(Self::gen_mod).collect();
Self::write(
&mut lines,
vec![quote! {
pub mod prelude;
}],
);
lines.push("".to_owned());
Self::write(&mut lines, code_blocks);
if !self.enums.is_empty() {
Self::write(
&mut lines,
vec![quote! {
pub mod sea_orm_active_enums;
}],
);
}
if seaography {
lines.push("".to_owned());
let ts = Self::gen_seaography_entity_mod(&self.entities, &self.enums);
Self::write(&mut lines, vec![ts]);
}
let file_name = match lib {
true => "lib.rs".to_owned(),
false => "mod.rs".to_owned(),
};
OutputFile {
name: file_name,
content: lines.join("\n"),
}
}
pub fn write_prelude(&self) -> OutputFile {
let mut lines = Vec::new();
Self::write_doc_comment(&mut lines);
let code_blocks = self.entities.iter().map(Self::gen_prelude_use).collect();
Self::write(&mut lines, code_blocks);
OutputFile {
name: "prelude.rs".to_owned(),
content: lines.join("\n"),
}
}
pub fn write_sea_orm_active_enums(
&self,
with_serde: &WithSerde,
with_copy_enums: bool,
extra_derives: &TokenStream,
extra_attributes: &TokenStream,
) -> OutputFile {
let mut lines = Vec::new();
Self::write_doc_comment(&mut lines);
Self::write(&mut lines, vec![Self::gen_import(with_serde)]);
lines.push("".to_owned());
let code_blocks = self
.enums
.values()
.map(|active_enum| {
active_enum.impl_active_enum(
with_serde,
with_copy_enums,
extra_derives,
extra_attributes,
)
})
.collect();
Self::write(&mut lines, code_blocks);
OutputFile {
name: "sea_orm_active_enums.rs".to_owned(),
content: lines.join("\n"),
}
}
pub fn write(lines: &mut Vec<String>, code_blocks: Vec<TokenStream>) {
lines.extend(
code_blocks
.into_iter()
.map(|code_block| code_block.to_string())
.collect::<Vec<_>>(),
);
}
pub fn write_doc_comment(lines: &mut Vec<String>) {
let ver = env!("CARGO_PKG_VERSION");
let comments = vec![format!(
"//! `SeaORM` Entity, @generated by sea-orm-codegen {ver}"
)];
lines.extend(comments);
lines.push("".to_owned());
}
#[allow(clippy::too_many_arguments)]
pub fn gen_expanded_code_blocks(
entity: &Entity,
with_serde: &WithSerde,
date_time_crate: &DateTimeCrate,
schema_name: &Option<String>,
serde_skip_deserializing_primary_key: bool,
serde_skip_hidden_column: bool,
model_extra_derives: &TokenStream,
model_extra_attributes: &TokenStream,
seaography: bool,
) -> Vec<TokenStream> {
let mut imports = Self::gen_import(with_serde);
imports.extend(Self::gen_import_active_enum(entity));
let mut code_blocks = vec![
imports,
Self::gen_entity_struct(),
Self::gen_impl_entity_name(entity, schema_name),
Self::gen_model_struct(
entity,
with_serde,
date_time_crate,
serde_skip_deserializing_primary_key,
serde_skip_hidden_column,
model_extra_derives,
model_extra_attributes,
),
Self::gen_column_enum(entity),
Self::gen_primary_key_enum(entity),
Self::gen_impl_primary_key(entity, date_time_crate),
Self::gen_relation_enum(entity),
Self::gen_impl_column_trait(entity),
Self::gen_impl_relation_trait(entity),
];
code_blocks.extend(Self::gen_impl_related(entity));
code_blocks.extend(Self::gen_impl_conjunct_related(entity));
code_blocks.extend([Self::gen_impl_active_model_behavior()]);
if seaography {
code_blocks.extend([Self::gen_related_entity(entity)]);
}
code_blocks
}
#[allow(clippy::too_many_arguments)]
pub fn gen_compact_code_blocks(
entity: &Entity,
with_serde: &WithSerde,
date_time_crate: &DateTimeCrate,
schema_name: &Option<String>,
serde_skip_deserializing_primary_key: bool,
serde_skip_hidden_column: bool,
model_extra_derives: &TokenStream,
model_extra_attributes: &TokenStream,
seaography: bool,
) -> Vec<TokenStream> {
let mut imports = Self::gen_import(with_serde);
imports.extend(Self::gen_import_active_enum(entity));
let mut code_blocks = vec![
imports,
Self::gen_compact_model_struct(
entity,
with_serde,
date_time_crate,
schema_name,
serde_skip_deserializing_primary_key,
serde_skip_hidden_column,
model_extra_derives,
model_extra_attributes,
),
Self::gen_compact_relation_enum(entity),
];
code_blocks.extend(Self::gen_impl_related(entity));
code_blocks.extend(Self::gen_impl_conjunct_related(entity));
code_blocks.extend([Self::gen_impl_active_model_behavior()]);
if seaography {
code_blocks.extend([Self::gen_related_entity(entity)]);
}
code_blocks
}
pub fn gen_import(with_serde: &WithSerde) -> TokenStream {
let prelude_import = quote!(
use sea_orm::entity::prelude::*;
);
match with_serde {
WithSerde::None => prelude_import,
WithSerde::Serialize => {
quote! {
#prelude_import
use serde::Serialize;
}
}
WithSerde::Deserialize => {
quote! {
#prelude_import
use serde::Deserialize;
}
}
WithSerde::Both => {
quote! {
#prelude_import
use serde::{Deserialize,Serialize};
}
}
}
}
pub fn gen_entity_struct() -> TokenStream {
quote! {
#[derive(Copy, Clone, Default, Debug, DeriveEntity)]
pub struct Entity;
}
}
pub fn gen_impl_entity_name(entity: &Entity, schema_name: &Option<String>) -> TokenStream {
let schema_name = match Self::gen_schema_name(schema_name) {
Some(schema_name) => quote! {
fn schema_name(&self) -> Option<&str> {
Some(#schema_name)
}
},
None => quote! {},
};
let table_name = entity.table_name.as_str();
let table_name = quote! {
fn table_name(&self) -> &str {
#table_name
}
};
quote! {
impl EntityName for Entity {
#schema_name
#table_name
}
}
}
pub fn gen_import_active_enum(entity: &Entity) -> TokenStream {
entity
.columns
.iter()
.fold(
(TokenStream::new(), Vec::new()),
|(mut ts, mut enums), col| {
if let sea_query::ColumnType::Enum { name, .. } = col.get_inner_col_type() {
if !enums.contains(&name) {
enums.push(name);
let enum_name =
format_ident!("{}", name.to_string().to_upper_camel_case());
ts.extend([quote! {
use super::sea_orm_active_enums::#enum_name;
}]);
}
}
(ts, enums)
},
)
.0
}
pub fn gen_model_struct(
entity: &Entity,
with_serde: &WithSerde,
date_time_crate: &DateTimeCrate,
serde_skip_deserializing_primary_key: bool,
serde_skip_hidden_column: bool,
model_extra_derives: &TokenStream,
model_extra_attributes: &TokenStream,
) -> TokenStream {
let column_names_snake_case = entity.get_column_names_snake_case();
let column_rs_types = entity.get_column_rs_types(date_time_crate);
let if_eq_needed = entity.get_eq_needed();
let serde_attributes = entity.get_column_serde_attributes(
serde_skip_deserializing_primary_key,
serde_skip_hidden_column,
);
let extra_derive = with_serde.extra_derive();
quote! {
#[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel #if_eq_needed #extra_derive #model_extra_derives)]
#model_extra_attributes
pub struct Model {
#(
#serde_attributes
pub #column_names_snake_case: #column_rs_types,
)*
}
}
}
pub fn gen_column_enum(entity: &Entity) -> TokenStream {
let column_variants = entity.columns.iter().map(|col| {
let variant = col.get_name_camel_case();
let mut variant = quote! { #variant };
if !col.is_snake_case_name() {
let column_name = &col.name;
variant = quote! {
#[sea_orm(column_name = #column_name)]
#variant
};
}
variant
});
quote! {
#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
pub enum Column {
#(#column_variants,)*
}
}
}
pub fn gen_primary_key_enum(entity: &Entity) -> TokenStream {
let primary_key_names_camel_case = entity.get_primary_key_names_camel_case();
quote! {
#[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)]
pub enum PrimaryKey {
#(#primary_key_names_camel_case,)*
}
}
}
pub fn gen_impl_primary_key(entity: &Entity, date_time_crate: &DateTimeCrate) -> TokenStream {
let primary_key_auto_increment = entity.get_primary_key_auto_increment();
let value_type = entity.get_primary_key_rs_type(date_time_crate);
quote! {
impl PrimaryKeyTrait for PrimaryKey {
type ValueType = #value_type;
fn auto_increment() -> bool {
#primary_key_auto_increment
}
}
}
}
pub fn gen_relation_enum(entity: &Entity) -> TokenStream {
let relation_enum_name = entity.get_relation_enum_name();
quote! {
#[derive(Copy, Clone, Debug, EnumIter)]
pub enum Relation {
#(#relation_enum_name,)*
}
}
}
pub fn gen_impl_column_trait(entity: &Entity) -> TokenStream {
let column_names_camel_case = entity.get_column_names_camel_case();
let column_defs = entity.get_column_defs();
quote! {
impl ColumnTrait for Column {
type EntityName = Entity;
fn def(&self) -> ColumnDef {
match self {
#(Self::#column_names_camel_case => #column_defs,)*
}
}
}
}
}
pub fn gen_impl_relation_trait(entity: &Entity) -> TokenStream {
let relation_enum_name = entity.get_relation_enum_name();
let relation_defs = entity.get_relation_defs();
let quoted = if relation_enum_name.is_empty() {
quote! {
panic!("No RelationDef")
}
} else {
quote! {
match self {
#(Self::#relation_enum_name => #relation_defs,)*
}
}
};
quote! {
impl RelationTrait for Relation {
fn def(&self) -> RelationDef {
#quoted
}
}
}
}
pub fn gen_impl_related(entity: &Entity) -> Vec<TokenStream> {
entity
.relations
.iter()
.filter(|rel| !rel.self_referencing && rel.num_suffix == 0 && rel.impl_related)
.map(|rel| {
let enum_name = rel.get_enum_name();
let module_name = rel.get_module_name();
let inner = quote! {
fn to() -> RelationDef {
Relation::#enum_name.def()
}
};
if module_name.is_some() {
quote! {
impl Related<super::#module_name::Entity> for Entity { #inner }
}
} else {
quote! {
impl Related<Entity> for Entity { #inner }
}
}
})
.collect()
}
/// Used to generate `enum RelatedEntity` that is useful to the Seaography project
pub fn gen_related_entity(entity: &Entity) -> TokenStream {
let related_enum_name = entity.get_related_entity_enum_name();
let related_attrs = entity.get_related_entity_attrs();
quote! {
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelatedEntity)]
pub enum RelatedEntity {
#(
#related_attrs
#related_enum_name
),*
}
}
}
pub fn gen_impl_conjunct_related(entity: &Entity) -> Vec<TokenStream> {
let table_name_camel_case = entity.get_table_name_camel_case_ident();
let via_snake_case = entity.get_conjunct_relations_via_snake_case();
let to_snake_case = entity.get_conjunct_relations_to_snake_case();
let to_upper_camel_case = entity.get_conjunct_relations_to_upper_camel_case();
via_snake_case
.into_iter()
.zip(to_snake_case)
.zip(to_upper_camel_case)
.map(|((via_snake_case, to_snake_case), to_upper_camel_case)| {
quote! {
impl Related<super::#to_snake_case::Entity> for Entity {
fn to() -> RelationDef {
super::#via_snake_case::Relation::#to_upper_camel_case.def()
}
fn via() -> Option<RelationDef> {
Some(super::#via_snake_case::Relation::#table_name_camel_case.def().rev())
}
}
}
})
.collect()
}
pub fn gen_impl_active_model_behavior() -> TokenStream {
quote! {
impl ActiveModelBehavior for ActiveModel {}
}
}
pub fn gen_mod(entity: &Entity) -> TokenStream {
let table_name_snake_case_ident = format_ident!(
"{}",
escape_rust_keyword(entity.get_table_name_snake_case_ident())
);
quote! {
pub mod #table_name_snake_case_ident;
}
}
pub fn gen_seaography_entity_mod(
entities: &[Entity],
enums: &BTreeMap<String, ActiveEnum>,
) -> TokenStream {
let mut ts = TokenStream::new();
for entity in entities {
let table_name_snake_case_ident = format_ident!(
"{}",
escape_rust_keyword(entity.get_table_name_snake_case_ident())
);
ts = quote! {
#ts
#table_name_snake_case_ident,
}
}
ts = quote! {
seaography::register_entity_modules!([
#ts
]);
};
let mut enum_ts = TokenStream::new();
for active_enum in enums.values() {
let enum_name = &active_enum.enum_name.to_string();
let enum_iden = format_ident!("{}", enum_name.to_upper_camel_case());
enum_ts = quote! {
#enum_ts
sea_orm_active_enums::#enum_iden
}
}
if !enum_ts.is_empty() {
ts = quote! {
#ts
seaography::register_active_enums!([
#enum_ts
]);
};
}
ts
}
pub fn gen_prelude_use(entity: &Entity) -> TokenStream {
let table_name_snake_case_ident = entity.get_table_name_snake_case_ident();
let table_name_camel_case_ident = entity.get_table_name_camel_case_ident();
quote! {
pub use super::#table_name_snake_case_ident::Entity as #table_name_camel_case_ident;
}
}
#[allow(clippy::too_many_arguments)]
pub fn gen_compact_model_struct(
entity: &Entity,
with_serde: &WithSerde,
date_time_crate: &DateTimeCrate,
schema_name: &Option<String>,
serde_skip_deserializing_primary_key: bool,
serde_skip_hidden_column: bool,
model_extra_derives: &TokenStream,
model_extra_attributes: &TokenStream,
) -> TokenStream {
let table_name = entity.table_name.as_str();
let column_names_snake_case = entity.get_column_names_snake_case();
let column_rs_types = entity.get_column_rs_types(date_time_crate);
let if_eq_needed = entity.get_eq_needed();
let primary_keys: Vec<String> = entity
.primary_keys
.iter()
.map(|pk| pk.name.clone())
.collect();
let attrs: Vec<TokenStream> = entity
.columns
.iter()
.map(|col| {
let mut attrs: Punctuated<_, Comma> = Punctuated::new();
let is_primary_key = primary_keys.contains(&col.name);
if !col.is_snake_case_name() {
let column_name = &col.name;
attrs.push(quote! { column_name = #column_name });
}
if is_primary_key {
attrs.push(quote! { primary_key });
if !col.auto_increment {
attrs.push(quote! { auto_increment = false });
}
}
if let Some(ts) = col.get_col_type_attrs() {
attrs.extend([ts]);
if !col.not_null {
attrs.push(quote! { nullable });
}
};
if col.unique {
attrs.push(quote! { unique });
}
let mut ts = quote! {};
if !attrs.is_empty() {
for (i, attr) in attrs.into_iter().enumerate() {
if i > 0 {
ts = quote! { #ts, };
}
ts = quote! { #ts #attr };
}
ts = quote! { #[sea_orm(#ts)] };
}
let serde_attribute = col.get_serde_attribute(
is_primary_key,
serde_skip_deserializing_primary_key,
serde_skip_hidden_column,
);
ts = quote! {
#ts
#serde_attribute
};
ts
})
.collect();
let schema_name = match Self::gen_schema_name(schema_name) {
Some(schema_name) => quote! {
schema_name = #schema_name,
},
None => quote! {},
};
let extra_derive = with_serde.extra_derive();
quote! {
#[derive(Clone, Debug, PartialEq, DeriveEntityModel #if_eq_needed #extra_derive #model_extra_derives)]
#[sea_orm(
#schema_name
table_name = #table_name
)]
#model_extra_attributes
pub struct Model {
#(
#attrs
pub #column_names_snake_case: #column_rs_types,
)*
}
}
}
pub fn gen_compact_relation_enum(entity: &Entity) -> TokenStream {
let relation_enum_name = entity.get_relation_enum_name();
let attrs = entity.get_relation_attrs();
quote! {
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#(
#attrs
#relation_enum_name,
)*
}
}
}
pub fn gen_schema_name(schema_name: &Option<String>) -> Option<TokenStream> {
schema_name
.as_ref()
.map(|schema_name| quote! { #schema_name })
}
}
#[cfg(test)]
mod tests {
use crate::{
entity::writer::{bonus_attributes, bonus_derive},
Column, ConjunctRelation, DateTimeCrate, Entity, EntityWriter, PrimaryKey, Relation,
RelationType, WithSerde,
};
use pretty_assertions::assert_eq;
use proc_macro2::TokenStream;
use quote::quote;
use sea_query::{Alias, ColumnType, ForeignKeyAction, RcOrArc, SeaRc, StringLen};
use std::io::{self, BufRead, BufReader, Read};
fn setup() -> Vec<Entity> {
vec![
Entity {
table_name: "cake".to_owned(),
columns: vec![
Column {
name: "id".to_owned(),
col_type: ColumnType::Integer,
auto_increment: true,
not_null: true,
unique: false,
},
Column {
name: "name".to_owned(),
col_type: ColumnType::Text,
auto_increment: false,
not_null: false,
unique: false,
},
],
relations: vec![Relation {
ref_table: "fruit".to_owned(),
columns: vec![],
ref_columns: vec![],
rel_type: RelationType::HasMany,
on_delete: None,
on_update: None,
self_referencing: false,
num_suffix: 0,
impl_related: true,
}],
conjunct_relations: vec![ConjunctRelation {
via: "cake_filling".to_owned(),
to: "filling".to_owned(),
}],
primary_keys: vec![PrimaryKey {
name: "id".to_owned(),
}],
},
Entity {
table_name: "_cake_filling_".to_owned(),
columns: vec![
Column {
name: "cake_id".to_owned(),
col_type: ColumnType::Integer,
auto_increment: false,
not_null: true,
unique: false,
},
Column {
name: "filling_id".to_owned(),
col_type: ColumnType::Integer,
auto_increment: false,
not_null: true,
unique: false,
},
],
relations: vec![
Relation {
ref_table: "cake".to_owned(),
columns: vec!["cake_id".to_owned()],
ref_columns: vec!["id".to_owned()],
rel_type: RelationType::BelongsTo,
on_delete: Some(ForeignKeyAction::Cascade),
on_update: Some(ForeignKeyAction::Cascade),
self_referencing: false,
num_suffix: 0,
impl_related: true,
},
Relation {
ref_table: "filling".to_owned(),
columns: vec!["filling_id".to_owned()],
ref_columns: vec!["id".to_owned()],
rel_type: RelationType::BelongsTo,
on_delete: Some(ForeignKeyAction::Cascade),
on_update: Some(ForeignKeyAction::Cascade),
self_referencing: false,
num_suffix: 0,
impl_related: true,
},
],
conjunct_relations: vec![],
primary_keys: vec![
PrimaryKey {
name: "cake_id".to_owned(),
},
PrimaryKey {
name: "filling_id".to_owned(),
},
],
},
Entity {
table_name: "cake_filling_price".to_owned(),
columns: vec![
Column {
name: "cake_id".to_owned(),
col_type: ColumnType::Integer,
auto_increment: false,
not_null: true,
unique: false,
},
Column {
name: "filling_id".to_owned(),
col_type: ColumnType::Integer,
auto_increment: false,
not_null: true,
unique: false,
},
Column {
name: "price".to_owned(),
col_type: ColumnType::Decimal(None),
auto_increment: false,
not_null: true,