lib.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. use proc_macro::TokenStream;
  2. use quote::{format_ident, quote};
  3. use syn::{parse_macro_input, DeriveInput};
  4. use convert_case::{Case, Casing};
  5. fn parse_microrm_ref(attrs: &[syn::Attribute]) -> proc_macro2::TokenStream {
  6. for attr in attrs {
  7. if attr.path.segments.is_empty() {
  8. continue;
  9. }
  10. if attr.tokens.is_empty() && attr.path.segments.last().unwrap().ident == "microrm_internal"
  11. {
  12. return quote! { crate };
  13. }
  14. }
  15. quote! { ::microrm }
  16. }
  17. fn parse_fk(attrs: &[syn::Attribute]) -> bool {
  18. for attr in attrs {
  19. if attr.path.segments.len() == 1 && attr.path.segments.last().unwrap().ident == "microrm_foreign" {
  20. return true
  21. }
  22. }
  23. false
  24. }
  25. /// Turns a serializable/deserializable struct into a microrm entity model.
  26. ///
  27. /// There are two important visible effects:
  28. /// - Provides an implementation of `microrm::model::Entity`
  29. /// - Defines a <struct-name>Columns enum
  30. ///
  31. /// Note that names are converted from CamelCase to snake_case and vice versa
  32. /// where applicable, so a struct named `TestModel` is given a table name `test_model`
  33. /// and a struct field named `field_name` is given a variant name of `FieldName`.
  34. ///
  35. /// The `#[microrm...]` attributes can be used to control the derivation somewhat.
  36. /// The following are understood for the Entity struct:
  37. /// - `#[microrm_internal]`: this is internal to the microrm crate (of extremely limited usefulness
  38. /// outside the microrm library)
  39. /// The following are understood on individual fields
  40. /// - `#[microrm_foreign]`: this is a foreign key (and the field must be of a type implementing `EntityID`)
  41. #[proc_macro_derive(Entity, attributes(microrm_internal, microrm_foreign))]
  42. pub fn derive_entity(tokens: TokenStream) -> TokenStream {
  43. let input = parse_macro_input!(tokens as DeriveInput);
  44. let microrm_ref = parse_microrm_ref(&input.attrs);
  45. let struct_name = &input.ident;
  46. let enum_name = format_ident!("{}Columns", &input.ident);
  47. let id_name = format_ident!("{}ID", &input.ident);
  48. let table_name = format!("{}", struct_name).to_case(Case::Snake);
  49. let st = match input.data {
  50. syn::Data::Struct(st) => st,
  51. _ => panic!("Can only use derive(Entity) on structs!"),
  52. };
  53. let fields = match st.fields {
  54. syn::Fields::Named(fields) => fields,
  55. _ => panic!("Can only use derive(Entity) on non-unit structs with named fields!"),
  56. };
  57. let mut variants = Vec::new();
  58. let mut field_names = Vec::new();
  59. let mut field_numbers = Vec::new();
  60. let mut value_references = Vec::new();
  61. let mut foreign_keys = Vec::new();
  62. let mut foreign_key_impls = Vec::new();
  63. for name in fields.named.iter() {
  64. let converted_case =
  65. format!("{}", name.ident.as_ref().unwrap().clone()).to_case(Case::UpperCamel);
  66. let converted_case = format_ident!("{}", converted_case);
  67. variants.push(converted_case.clone());
  68. let field_name = name.ident.as_ref().unwrap().clone();
  69. let field_name_str = format!("{}", field_name);
  70. field_names.push(quote! { Self::Column::#converted_case => #field_name_str });
  71. let nn = field_numbers.len() + 1;
  72. field_numbers.push(quote! { #nn => Self::#converted_case, });
  73. if parse_fk(&name.attrs) {
  74. let fk_struct_name = format_ident!("{}{}ForeignKey", struct_name, converted_case);
  75. let ty = &name.ty;
  76. foreign_keys.push(quote!{
  77. &#fk_struct_name { col: #enum_name::#converted_case }
  78. });
  79. foreign_key_impls.push(quote!{
  80. struct #fk_struct_name {
  81. col: #enum_name
  82. }
  83. impl #microrm_ref::model::EntityForeignKey<#enum_name> for #fk_struct_name {
  84. fn local_column(&self) -> &#enum_name { &self.col }
  85. fn foreign_table_name(&self) -> &'static str {
  86. <<#ty as #microrm_ref::model::EntityID>::Entity as #microrm_ref::model::Entity>::table_name()
  87. }
  88. fn foreign_column_name(&self) -> &'static str {
  89. "id"
  90. }
  91. }
  92. });
  93. }
  94. value_references.push(quote! { &self. #field_name });
  95. }
  96. let field_count = fields.named.iter().count();
  97. quote!{
  98. // Related types for #struct_name
  99. #[derive(Clone,Copy,PartialEq)]
  100. #[allow(unused)]
  101. #[repr(usize)]
  102. pub enum #enum_name {
  103. ID,
  104. #(#variants),*
  105. }
  106. #[derive(Debug,PartialEq,Clone,Copy,#microrm_ref::re_export::serde::Serialize,#microrm_ref::re_export::serde::Deserialize)]
  107. #[allow(unused)]
  108. pub struct #id_name (i64);
  109. // Implementations for related types
  110. impl #microrm_ref::model::EntityColumns for #enum_name {
  111. type Entity = #struct_name;
  112. }
  113. impl std::convert::From<usize> for #enum_name {
  114. fn from(i: usize) -> Self {
  115. match i {
  116. 0 => Self::ID,
  117. #(#field_numbers)*
  118. _ => {
  119. panic!("Given invalid usize to convert to column")
  120. },
  121. }
  122. }
  123. }
  124. impl #microrm_ref::model::EntityID for #id_name {
  125. type Entity = #struct_name;
  126. fn from_raw_id(raw: i64) -> Self { Self(raw) }
  127. fn raw_id(&self) -> i64 { self.0 }
  128. }
  129. impl #microrm_ref::re_export::rusqlite::ToSql for #id_name {
  130. fn to_sql(&self) -> #microrm_ref::re_export::rusqlite::Result<#microrm_ref::re_export::rusqlite::types::ToSqlOutput<'_>> {
  131. self.0.to_sql()
  132. }
  133. }
  134. // Implementations for #struct_name
  135. impl #microrm_ref::model::Entity for #struct_name {
  136. type Column = #enum_name;
  137. type ID = #id_name;
  138. fn table_name() -> &'static str { #table_name }
  139. fn column_count() -> usize {
  140. // +1 for ID column
  141. #field_count + 1
  142. }
  143. fn index(c: Self::Column) -> usize {
  144. c as usize
  145. }
  146. fn name(c: Self::Column) -> &'static str {
  147. match c {
  148. Self::Column::ID => "ID",
  149. #(#field_names),*
  150. }
  151. }
  152. fn values(&self) -> Vec<&dyn #microrm_ref::re_export::rusqlite::ToSql> {
  153. vec![ #(#value_references),* ]
  154. }
  155. fn foreign_keys() -> &'static [&'static dyn #microrm_ref::model::EntityForeignKey<Self::Column>] {
  156. &[#(#foreign_keys),*]
  157. }
  158. }
  159. // Foreign key struct implementations
  160. #(#foreign_key_impls)*
  161. }.into()
  162. }
  163. /// Marks a struct as able to be directly used in an Entity to correspond to a single database column.
  164. #[proc_macro_derive(Modelable, attributes(microrm_internal))]
  165. pub fn derive_modelable(tokens: TokenStream) -> TokenStream {
  166. let input = parse_macro_input!(tokens as DeriveInput);
  167. let microrm_ref = parse_microrm_ref(&input.attrs);
  168. let ident = input.ident;
  169. quote!{
  170. impl #microrm_ref::re_export::rusqlite::ToSql for #ident {
  171. fn to_sql(&self) -> #microrm_ref::re_export::rusqlite::Result<#microrm_ref::re_export::rusqlite::types::ToSqlOutput<'_>> {
  172. use #microrm_ref::re_export::rusqlite::types::{ToSqlOutput,Value};
  173. Ok(ToSqlOutput::Owned(Value::Text(#microrm_ref::re_export::serde_json::to_string(self).expect("can be serialized"))))
  174. }
  175. }
  176. }.into()
  177. }