-
-
Notifications
You must be signed in to change notification settings - Fork 521
/
entity_model.rs
355 lines (333 loc) Β· 16.5 KB
/
entity_model.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
use crate::util::{escape_rust_keyword, trim_starting_raw_identifier};
use heck::{CamelCase, SnakeCase};
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, quote_spanned};
use syn::{
parse::Error, punctuated::Punctuated, spanned::Spanned, token::Comma, Attribute, Data, Fields,
Lit, LitStr, Meta, Type,
};
/// Method to derive an Model
pub fn expand_derive_entity_model(data: Data, attrs: Vec<Attribute>) -> syn::Result<TokenStream> {
// if #[sea_orm(table_name = "foo", schema_name = "bar")] specified, create Entity struct
let mut table_name = None;
let mut schema_name = quote! { None };
let mut table_iden = false;
attrs.iter().for_each(|attr| {
if attr.path.get_ident().map(|i| i == "sea_orm") != Some(true) {
return;
}
if let Ok(list) = attr.parse_args_with(Punctuated::<Meta, Comma>::parse_terminated) {
for meta in list.iter() {
if let Meta::NameValue(nv) = meta {
if let Some(ident) = nv.path.get_ident() {
if ident == "table_name" {
table_name = Some(nv.lit.clone());
} else if ident == "schema_name" {
let name = &nv.lit;
schema_name = quote! { Some(#name) };
}
}
} else if let Meta::Path(path) = meta {
if let Some(ident) = path.get_ident() {
if ident == "table_iden" {
table_iden = true;
}
}
}
}
}
});
let entity_def = table_name
.as_ref()
.map(|table_name| {
quote! {
#[derive(Copy, Clone, Default, Debug, sea_orm::prelude::DeriveEntity)]
pub struct Entity;
#[automatically_derived]
impl sea_orm::prelude::EntityName for Entity {
fn schema_name(&self) -> Option<&str> {
#schema_name
}
fn table_name(&self) -> &str {
#table_name
}
}
}
})
.unwrap_or_default();
// generate Column enum and it's ColumnTrait impl
let mut columns_enum: Punctuated<_, Comma> = Punctuated::new();
let mut columns_trait: Punctuated<_, Comma> = Punctuated::new();
let mut primary_keys: Punctuated<_, Comma> = Punctuated::new();
let mut primary_key_types: Punctuated<_, Comma> = Punctuated::new();
let mut auto_increment = true;
if table_iden {
if let Some(table_name) = table_name {
let table_field_name = Ident::new("Table", Span::call_site());
columns_enum.push(quote! {
#[sea_orm(table_name=#table_name)]
#[strum(disabled)]
#table_field_name
});
columns_trait.push(
quote! { Self::#table_field_name => panic!("Table cannot be used as a column") },
);
}
}
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 original_field_name = trim_starting_raw_identifier(ident);
let mut field_name =
Ident::new(&original_field_name.to_camel_case(), Span::call_site());
let mut nullable = false;
let mut default_value = None;
let mut default_expr = None;
let mut indexed = false;
let mut ignore = false;
let mut unique = false;
let mut sql_type = None;
let mut column_name = if original_field_name
!= original_field_name.to_camel_case().to_snake_case()
{
// `to_snake_case` was used to trim prefix and tailing underscore
Some(original_field_name.to_snake_case())
} else {
None
};
let mut enum_name = None;
let mut is_primary_key = false;
// search for #[sea_orm(primary_key, auto_increment = false, column_type = "String(Some(255))", default_value = "new user", default_expr = "gen_random_uuid()", column_name = "name", enum_name = "Name", nullable, indexed, unique)]
for attr in field.attrs.iter() {
if let Some(ident) = attr.path.get_ident() {
if ident != "sea_orm" {
continue;
}
} else {
continue;
}
// single param
if let Ok(list) =
attr.parse_args_with(Punctuated::<Meta, Comma>::parse_terminated)
{
for meta in list.iter() {
match meta {
Meta::NameValue(nv) => {
if let Some(name) = nv.path.get_ident() {
if name == "column_type" {
if let Lit::Str(litstr) = &nv.lit {
let ty: TokenStream =
syn::parse_str(&litstr.value())?;
sql_type = Some(ty);
} else {
return Err(Error::new(
field.span(),
format!("Invalid column_type {:?}", nv.lit),
));
}
} else if name == "auto_increment" {
if let Lit::Bool(litbool) = &nv.lit {
auto_increment = litbool.value();
} else {
return Err(Error::new(
field.span(),
format!(
"Invalid auto_increment = {:?}",
nv.lit
),
));
}
} else if name == "default_value" {
default_value = Some(nv.lit.to_owned());
} else if name == "default_expr" {
default_expr = Some(nv.lit.to_owned());
} else if name == "column_name" {
if let Lit::Str(litstr) = &nv.lit {
column_name = Some(litstr.value());
} else {
return Err(Error::new(
field.span(),
format!("Invalid column_name {:?}", nv.lit),
));
}
} else if name == "enum_name" {
if let Lit::Str(litstr) = &nv.lit {
let ty: Ident =
syn::parse_str(&litstr.value())?;
enum_name = Some(ty);
} else {
return Err(Error::new(
field.span(),
format!("Invalid enum_name {:?}", nv.lit),
));
}
}
}
}
Meta::Path(p) => {
if let Some(name) = p.get_ident() {
if name == "ignore" {
ignore = true;
break;
} else if name == "primary_key" {
is_primary_key = true;
primary_key_types.push(field.ty.clone());
} else if name == "nullable" {
nullable = true;
} else if name == "indexed" {
indexed = true;
} else if name == "unique" {
unique = true;
}
}
}
_ => {}
}
}
}
}
if let Some(enum_name) = enum_name {
field_name = enum_name;
}
field_name = Ident::new(&escape_rust_keyword(field_name), Span::call_site());
let variant_attrs = match &column_name {
Some(column_name) => quote! {
#[sea_orm(column_name = #column_name)]
},
None => quote! {},
};
if ignore {
continue;
} else {
columns_enum.push(quote! {
#variant_attrs
#field_name
});
}
if is_primary_key {
primary_keys.push(quote! {
#variant_attrs
#field_name
});
}
let col_type = match sql_type {
Some(t) => quote! { sea_orm::prelude::ColumnType::#t.def() },
None => {
let field_type = &field.ty;
let temp = quote! { #field_type }
.to_string() //E.g.: "Option < String >"
.replace(' ', "");
let temp = if temp.starts_with("Option<") {
nullable = true;
&temp[7..(temp.len() - 1)]
} else {
temp.as_str()
};
let col_type = match temp {
"char" => quote! { Char(None) },
"String" | "&str" => quote! { String(None) },
"i8" => quote! { TinyInteger },
"u8" => quote! { TinyUnsigned },
"i16" => quote! { SmallInteger },
"u16" => quote! { SmallUnsigned },
"i32" => quote! { Integer },
"u32" => quote! { Unsigned },
"i64" => quote! { BigInteger },
"u64" => quote! { BigUnsigned },
"f32" => quote! { Float },
"f64" => quote! { Double },
"bool" => quote! { Boolean },
"Date" | "NaiveDate" => quote! { Date },
"Time" | "NaiveTime" => quote! { Time },
"DateTime" | "NaiveDateTime" => {
quote! { DateTime }
}
"DateTimeUtc" | "DateTimeLocal" | "DateTimeWithTimeZone" => {
quote! { TimestampWithTimeZone }
}
"Uuid" => quote! { Uuid },
"Json" => quote! { Json },
"Decimal" => quote! { Decimal(None) },
"Vec<u8>" => quote! { Binary },
_ => {
// Assumed it's ActiveEnum if none of the above type matches
quote! {}
}
};
if col_type.is_empty() {
let field_span = field.span();
let ty: Type = LitStr::new(temp, field_span).parse()?;
let def = quote_spanned! { field_span => {
std::convert::Into::<sea_orm::ColumnType>::into(
<#ty as sea_orm::sea_query::ValueType>::column_type()
)
.def()
}};
quote! { #def }
} else {
quote! { sea_orm::prelude::ColumnType::#col_type.def() }
}
}
};
let mut match_row = quote! { Self::#field_name => #col_type };
if nullable {
match_row = quote! { #match_row.nullable() };
}
if indexed {
match_row = quote! { #match_row.indexed() };
}
if unique {
match_row = quote! { #match_row.unique() };
}
if let Some(default_value) = default_value {
match_row = quote! { #match_row.default_value(#default_value) };
}
if let Some(default_expr) = default_expr {
match_row = quote! { #match_row.default_expr(#default_expr) };
}
columns_trait.push(match_row);
}
}
}
}
let primary_key = {
let auto_increment = auto_increment && primary_keys.len() == 1;
let primary_key_types = if primary_key_types.len() == 1 {
let first = primary_key_types.first();
quote! { #first }
} else {
quote! { (#primary_key_types) }
};
quote! {
#[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)]
pub enum PrimaryKey {
#primary_keys
}
#[automatically_derived]
impl PrimaryKeyTrait for PrimaryKey {
type ValueType = #primary_key_types;
fn auto_increment() -> bool {
#auto_increment
}
}
}
};
Ok(quote! {
#[derive(Copy, Clone, Debug, sea_orm::prelude::EnumIter, sea_orm::prelude::DeriveColumn)]
pub enum Column {
#columns_enum
}
#[automatically_derived]
impl sea_orm::prelude::ColumnTrait for Column {
type EntityName = Entity;
fn def(&self) -> sea_orm::prelude::ColumnDef {
match self {
#columns_trait
}
}
}
#entity_def
#primary_key
})
}