mysql_common_derive/from_row/structs/
mod.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
use darling::FromAttributes;
use proc_macro2::{Span, TokenStream};
use proc_macro_error2::abort;
use quote::{ToTokens, TokenStreamExt};
use syn::ext::IdentExt;
use syn::spanned::Spanned;

use crate::from_value::enums::attrs::container::Crate;

mod attrs;

pub fn impl_from_row_for_struct(
    attrs: &[syn::Attribute],
    ident: &proc_macro2::Ident,
    generics: &syn::Generics,
    data_struct: &syn::DataStruct,
) -> crate::Result<TokenStream> {
    let fields = match &data_struct.fields {
        syn::Fields::Named(fields) => fields,
        syn::Fields::Unnamed(_) => {
            return Err(crate::Error::StructsWithUnnamedFieldsNotSupported(
                data_struct.struct_token.span,
            ))
        }
        syn::Fields::Unit => {
            return Err(crate::Error::UnitStructsNotSupported(
                data_struct.struct_token.span,
            ))
        }
    };

    let item_attrs = <attrs::container::Mysql as FromAttributes>::from_attributes(attrs)?;

    let derived = GenericStruct {
        ident,
        fields,
        item_attrs,
        generics,
    };
    Ok(quote::quote! { #derived })
}

struct GenericStruct<'a> {
    ident: &'a proc_macro2::Ident,
    item_attrs: attrs::container::Mysql,
    fields: &'a syn::FieldsNamed,
    generics: &'a syn::Generics,
}

impl ToTokens for GenericStruct<'_> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self {
            ident,
            item_attrs,
            fields,
            generics,
        } = self;

        let crat = match self.item_attrs.crate_name {
            Crate::NotFound => abort!(crate::Error::NoCrateNameFound),
            Crate::Multiple => abort!(crate::Error::MultipleCratesFound),
            Crate::Itself => syn::Ident::new("crate", Span::call_site()),
            Crate::Found(ref name) => syn::Ident::new(name, Span::call_site()),
        };

        let impl_generics = (!generics.params.is_empty()).then(|| {
            let generics = self.generics.params.iter();
            quote::quote!(< #(#generics,)* >)
        });

        let ident_generics = (!generics.params.is_empty()).then(|| {
            let generics = self.generics.params.iter().map(|g| match g {
                syn::GenericParam::Type(x) => {
                    let ident = &x.ident;
                    quote::quote!(#ident)
                }
                syn::GenericParam::Lifetime(x) => {
                    let lifetime = &x.lifetime;
                    quote::quote!(#lifetime)
                }
                syn::GenericParam::Const(x) => {
                    let ident = &x.ident;
                    quote::quote!(#ident)
                }
            });
            quote::quote!(< #(#generics,)* >)
        });

        let bounds = item_attrs.bound.as_ref().map(|bound| {
            let bound = bound.0.iter();
            quote::quote!(where #(#bound,)*)
        });

        let table_name_constant = item_attrs.table_name.as_ref().map(|name| {
            let lit = syn::LitStr::new(name, name.span());
            quote::quote!(const TABLE_NAME: &'static str = #lit;)
        });

        let fields_attrs = fields
            .named
            .iter()
            .map(|f| <attrs::field::Mysql as FromAttributes>::from_attributes(&f.attrs))
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e: darling::Error| abort!(crate::Error::from(e)))
            .unwrap();

        let fields_names = fields
            .named
            .iter()
            .zip(&fields_attrs)
            .map(|(f, attrs)| {
                let mut name = f.ident.as_ref().unwrap().unraw().to_string();

                if let Some(ref r) = item_attrs.rename_all {
                    name = r.rename(&name);
                }

                if let Some(ref n) = attrs.rename {
                    name = n.clone();
                }

                name
            })
            .collect::<Vec<_>>();

        let field_ident = fields
            .named
            .iter()
            .map(|f| f.ident.as_ref().unwrap())
            .collect::<Vec<_>>();

        let filed_name_constant = fields.named.iter().zip(&fields_names).map(|(f, name)| {
            let ident = f.ident.as_ref().unwrap().unraw();
            let lit = syn::LitStr::new(name, f.span());
            let const_name = syn::Ident::new(
                &format!("{}_FIELD", heck::AsShoutySnakeCase(ident.to_string())),
                f.span(),
            );

            quote::quote!(const #const_name: &'static str = #lit;)
        });

        let take_field = fields
            .named
            .iter()
            .zip(&fields_attrs)
            .zip(&fields_names)
            .enumerate()
            .map(|(i, ((f, attrs), name))| {
                let ident = f.ident.as_ref().unwrap();
                let ty = &f.ty;
                let lit = syn::LitStr::new(name, ident.span());

                let place = field_ident
                    .iter()
                    .zip(&fields_attrs)
                    .zip(&fields_names)
                    .take(i)
                    .map(|((f, attrs), name)| {
                        let lit = syn::LitStr::new(name, f.span());
                        if attrs.json {
                            quote::quote!(
                                row.place(*indexes.get(#lit).unwrap(), #f.rollback())
                            )
                        } else {
                            quote::quote!(
                                row.place(*indexes.get(#lit).unwrap(), #f.into())
                            )
                        }
                    });

                let intermediate_ty = if attrs.json {
                    quote::quote!(<#crat::Deserialized<#ty> as FromValue>::Intermediate)
                } else {
                    quote::quote!(<#ty as FromValue>::Intermediate)
                };

                let try_from = if let Some(ref path) = attrs.with {
                    let path = &path.0;
                    quote::quote!( #path(x) )
                } else {
                    quote::quote!( <#intermediate_ty as std::convert::TryFrom<Value>>::try_from(x) )
                };

                quote::quote!(
                    let #ident = {
                        let val = match row.take_opt::<Value, &str>(#lit) {
                            Some(Ok(x)) => match #try_from {
                                Ok(x) => Some(x),
                                Err(e) => {
                                    row.place(*indexes.get(#lit).unwrap(), e.0);
                                    None
                                }
                            },
                            Some(_) => unreachable!("unable to convert Value to Value"),
                            None => None,
                        };

                        if let Some(val) = val {
                            val
                        } else {
                            #(#place;)*
                            return Err(FromRowError(row));
                        }
                    }
                )
            })
            .collect::<Vec<_>>();

        let set_field = fields
            .named
            .iter()
            .zip(&fields_attrs)
            .map(|(f, attrs)| {
                let ident = f.ident.as_ref().unwrap();
                let ty = &f.ty;
                if attrs.json {
                    quote::quote!(#ident: #ident.commit().0)
                } else if attrs.with.is_some() {
                    quote::quote!( #ident )
                } else {
                    quote::quote!(#ident: <<#ty as FromValue>::Intermediate as std::convert::Into<#ty>>::into(#ident))
                }
            })
            .collect::<Vec<_>>();

        let new_tokens = quote::quote!(
            impl #impl_generics #ident #ident_generics {
                #table_name_constant
                #(#filed_name_constant)*
            }

            impl #impl_generics #crat::prelude::FromRow for #ident #ident_generics
            #bounds {
                fn from_row_opt(
                    mut row: #crat::Row,
                ) -> std::result::Result<Self, #crat::FromRowError>
                where
                    Self: Sized,
                {
                    use #crat::prelude::*;
                    use #crat::Value;
                    use #crat::FromRowError;

                    let columns = row.columns();
                    let indexes = columns.iter().enumerate().fold(
                        std::collections::HashMap::new(),
                        |mut acc, (i, col)| {
                            acc.insert(col.name_str(), i);
                            acc
                        },
                    );

                    #(#take_field;)*

                    Ok(Self {
                        #(#set_field,)*
                    })
                }
            }
        );

        tokens.append_all(new_tokens);
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn derive_from_row_named_struct() {
        let code = r#"
            #[derive(FromRow)]
            #[mysql(crate_name = "mysql_common")]
            struct Foo {
                id: u64,
                #[mysql(rename = "def", json)]
                definition: serde_json::Value,
                child: Option<u64>,
            }
        "#;
        let input = syn::parse_str::<syn::DeriveInput>(code).unwrap();
        let derived = super::super::impl_from_row(&input).unwrap();
        eprintln!("{}", derived);
    }

    #[test]
    fn derive_struct_with_raw_identifiers() {
        let code = r#"
            #[derive(FromRow)]
            #[mysql(crate_name = "mysql_common")]
            struct Foo {
                r#type: u64,
            }
        "#;
        let input = syn::parse_str::<syn::DeriveInput>(code).unwrap();
        let derived = super::super::impl_from_row(&input).unwrap();
        eprintln!("{}", derived);
    }
}