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
use std::convert::TryFrom;
use canyon_entities::field_annotation::EntityFieldAnnotation;
use proc_macro2::Ident;
use syn::{Attribute, DeriveInput, Fields, Generics, Type, Visibility};
/// Provides a convenient way of store the data for the TokenStream
/// received on a macro
#[allow(dead_code)]
pub struct MacroTokens<'a> {
pub vis: &'a Visibility,
pub ty: &'a Ident,
pub generics: &'a Generics,
pub attrs: &'a Vec<Attribute>,
pub fields: &'a Fields,
}
impl<'a> MacroTokens<'a> {
pub fn new(ast: &'a DeriveInput) -> Self {
Self {
vis: &ast.vis,
ty: &ast.ident,
generics: &ast.generics,
attrs: &ast.attrs,
fields: match &ast.data {
syn::Data::Struct(ref s) => &s.fields,
_ => panic!("This derive macro can only be automatically derived for structs"),
},
}
}
/// Gives a Vec of tuples that contains the visibility, the name and
/// the type of every field on a Struct
pub fn _fields_with_visibility_and_types(&self) -> Vec<(Visibility, Ident, Type)> {
self.fields
.iter()
.map(|field| {
(
field.vis.clone(),
field.ident.as_ref().unwrap().clone(),
field.ty.clone(),
)
})
.collect::<Vec<_>>()
}
/// Gives a Vec of tuples that contains the name and
/// the type of every field on a Struct
pub fn _fields_with_types(&self) -> Vec<(Ident, Type)> {
self.fields
.iter()
.map(|field| (field.ident.as_ref().unwrap().clone(), field.ty.clone()))
.collect::<Vec<_>>()
}
/// Gives a Vec of Ident with the fields of a Struct
pub fn get_struct_fields(&self) -> Vec<Ident> {
self.fields
.iter()
.map(|field| field.ident.as_ref().unwrap().clone())
.collect::<Vec<_>>()
}
/// Gives a Vec populated with the name of the fields of the struct
pub fn _get_struct_fields_as_collection_strings(&self) -> Vec<String> {
self.get_struct_fields()
.iter()
.map(|ident| ident.to_owned().to_string())
.collect::<Vec<String>>()
}
/// Returns a Vec populated with the name of the fields of the struct
/// already quote scaped for avoid the upper case column name mangling.
///
/// If the type contains a `#[primary_key]` annotation (and), returns the
/// name of the columns without the fields that maps against the column designed as
/// primary key (if its present and its autoincremental attribute is set to true)
/// (autoincremental = true) or its without the autoincremental attribute, which leads
/// to the same behaviour.
///
/// Returns every field if there's no PK, or if it's present but autoincremental = false
pub fn get_column_names_pk_parsed(&self) -> Vec<String> {
self.fields
.iter()
.filter(|field| {
if !field.attrs.is_empty() {
field.attrs.iter().any(|attr| {
let a = attr.path.segments[0].clone().ident;
let b = attr.tokens.to_string();
!(a == "primary_key" || b.contains("false"))
})
} else {
true
}
})
.map(|c| format!("\"{}\"", c.ident.as_ref().unwrap()))
.collect::<Vec<String>>()
}
/// Retrieves the fields of the Struct as continuous String, comma separated
pub fn get_struct_fields_as_strings(&self) -> String {
let column_names: String = self
.get_struct_fields()
.iter()
.map(|ident| ident.to_owned().to_string())
.collect::<Vec<String>>()
.iter()
.map(|column| column.to_owned() + ", ")
.collect::<String>();
let mut column_names_as_chars = column_names.chars();
column_names_as_chars.next_back();
column_names_as_chars.next_back();
column_names_as_chars.as_str().to_owned()
}
/// Retrieves the value of the index of an annotated field with #[primary_key]
pub fn get_pk_index(&self) -> Option<usize> {
let mut pk_index = None;
for (idx, field) in self.fields.iter().enumerate() {
for attr in &field.attrs {
if attr.path.segments[0].clone().ident == "primary_key" {
pk_index = Some(idx);
}
}
}
pk_index
}
/// Utility for find the primary key attribute (if exists) and the
/// column name (field) which belongs
pub fn get_primary_key_annotation(&self) -> Option<String> {
let f = self.fields.iter().find(|field| {
field
.attrs
.iter()
.map(|attr| attr.path.segments[0].clone().ident)
.map(|ident| ident.to_string())
.find(|a| a == "primary_key")
== Some("primary_key".to_string())
});
f.map(|v| v.ident.clone().unwrap().to_string())
}
/// Utility for find the `foreign_key` attributes (if exists)
pub fn get_fk_annotations(&self) -> Vec<(&Ident, EntityFieldAnnotation)> {
let mut foreign_key_annotations = Vec::new();
self.fields.iter().for_each(|field| {
let attrs = field
.attrs
.iter()
.filter(|attr| attr.path.segments[0].clone().ident == "foreign_key");
attrs.for_each(|attr| {
let fk_parse = EntityFieldAnnotation::try_from(&attr);
if let Ok(fk_annotation) = fk_parse {
foreign_key_annotations.push((field.ident.as_ref().unwrap(), fk_annotation))
}
});
});
foreign_key_annotations
}
/// Boolean that returns true if the type contains a `#[primary_key]`
/// annotation. False otherwise.
pub fn type_has_primary_key(&self) -> bool {
self.fields.iter().any(|field| {
field
.attrs
.iter()
.map(|attr| attr.path.segments[0].clone().ident)
.map(|ident| ident.to_string())
.find(|a| a == "primary_key")
== Some("primary_key".to_string())
})
}
/// Returns an String ready to be inserted on the VALUES Sql clause
/// representing generic query parameters ($x).
///
/// Already returns the correct number of placeholders, skipping one
/// entry in the type contains a `#[primary_key]`
pub fn placeholders_generator(&self) -> String {
let mut placeholders = String::new();
if self.type_has_primary_key() {
for num in 1..self.fields.len() {
if num < self.fields.len() - 1 {
placeholders.push_str(&("$".to_owned() + &(num).to_string() + ", "));
} else {
placeholders.push_str(&("$".to_owned() + &(num).to_string()));
}
}
} else {
for num in 1..self.fields.len() + 1 {
if num < self.fields.len() {
placeholders.push_str(&("$".to_owned() + &(num).to_string() + ", "));
} else {
placeholders.push_str(&("$".to_owned() + &(num).to_string()));
}
}
}
placeholders
}
}