-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
64 lines (57 loc) · 2.18 KB
/
lib.rs
File metadata and controls
64 lines (57 loc) · 2.18 KB
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
use attribute::parse_db_row_attr;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput, Fields, Result};
mod attribute;
#[proc_macro_derive(FromRow, attributes(db_row))]
pub fn derive_from_row(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let syn::Data::Struct(data) = input.data else {
return TokenStream::from(
syn::Error::new(input.ident.span(), "Only structs can derive `FromRow`")
.to_compile_error(),
);
};
let struct_name = input.ident;
let fields = data
.fields
.iter()
.enumerate()
.map(|(i, field)| {
let attr = parse_db_row_attr(field.attrs.as_slice())?;
Ok(match field.ident.as_ref() {
Some(name) => {
let db_name = attr.rename.unwrap_or(name.to_string());
match attr.default {
true => quote! { #name: row.try_get(#db_name).unwrap_or_default() },
false => quote! { #name: row.try_get(#db_name)? },
}
}
None => match (attr.rename, attr.default) {
(Some(db_name), true) => quote! { row.try_get(#db_name).unwrap_or_default() },
(Some(db_name), false) => quote! { row.try_get(#db_name)? },
(None, true) => quote! { row.try_get(#i).unwrap_or_default() },
(None, false) => quote! { row.try_get(#i)? },
}
})
})
.collect::<Result<Vec<_>>>();
let fields = match fields {
Ok(ts) => ts,
Err(e) => return e.to_compile_error().into(),
};
let struct_self = match data.fields {
Fields::Named(_) => quote! { Self {#(#fields),*} },
Fields::Unnamed(_) => quote! { Self(#(#fields),*) },
Fields::Unit => quote! { Self },
};
quote! {
#[automatically_derived]
impl ::taom_database::FromRow for #struct_name {
fn from_row(row: ::tokio_postgres::Row) -> Result<Self, ::tokio_postgres::Error> {
Ok(#struct_self)
}
}
}
.into()
}