lib.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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,Hash)]
  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::model::Modelable for #id_name {
  130. fn bind_to(&self, stmt: &mut #microrm_ref::re_export::sqlite::Statement, col: usize) -> #microrm_ref::re_export::sqlite::Result<()> {
  131. use #microrm_ref::re_export::sqlite::Bindable;
  132. self.0.bind(stmt, col)
  133. }
  134. fn build_from(stmt: &sqlite::Statement, col_offset: usize) -> sqlite::Result<(Self, usize)> where Self: Sized {
  135. stmt.read::<i64>(col_offset).map(|x| (#id_name(x), 1))
  136. }
  137. }
  138. // Implementations for #struct_name
  139. impl #microrm_ref::model::Entity for #struct_name {
  140. type Column = #enum_name;
  141. type ID = #id_name;
  142. fn table_name() -> &'static str { #table_name }
  143. fn column_count() -> usize {
  144. // +1 for ID column
  145. #field_count + 1
  146. }
  147. fn index(c: Self::Column) -> usize {
  148. c as usize
  149. }
  150. fn name(c: Self::Column) -> &'static str {
  151. match c {
  152. Self::Column::ID => "ID",
  153. #(#field_names),*
  154. }
  155. }
  156. fn values(&self) -> Vec<&dyn #microrm_ref::model::Modelable> {
  157. vec![ #(#value_references),* ]
  158. }
  159. fn foreign_keys() -> &'static [&'static dyn #microrm_ref::model::EntityForeignKey<Self::Column>] {
  160. &[#(#foreign_keys),*]
  161. }
  162. }
  163. // Foreign key struct implementations
  164. #(#foreign_key_impls)*
  165. }.into()
  166. }
  167. /// Marks a struct as able to be directly used in an Entity to correspond to a single database column.
  168. #[proc_macro_derive(Modelable, attributes(microrm_internal))]
  169. pub fn derive_modelable(tokens: TokenStream) -> TokenStream {
  170. let input = parse_macro_input!(tokens as DeriveInput);
  171. let microrm_ref = parse_microrm_ref(&input.attrs);
  172. let ident = input.ident;
  173. quote!{
  174. impl #microrm_ref::model::Modelable for #ident {
  175. fn bind_to(&self, stmt: &mut #microrm_ref::re_export::sqlite::Statement, col: usize) -> #microrm_ref::re_export::sqlite::Result<()> {
  176. use #microrm_ref::re_export::sqlite;
  177. use #microrm_ref::model::Modelable;
  178. serde_json::to_string(self).expect("can be serialized").bind_to(stmt, col)
  179. }
  180. fn build_from(stmt: &#microrm_ref::re_export::sqlite::Statement, col_offset: usize) -> #microrm_ref::re_export::sqlite::Result<(Self,usize)> {
  181. use #microrm_ref::re_export::sqlite;
  182. use #microrm_ref::model::Modelable;
  183. let str_data = stmt.read::<String>(col_offset).map_err(|e| sqlite::Error { code: None, message: Some(e.to_string()) })?;
  184. let data = serde_json::from_str(str_data.as_str()).map_err(|e| sqlite::Error { code: None, message: Some(e.to_string()) })?;
  185. Ok((data,1))
  186. }
  187. }
  188. }.into()
  189. }
  190. type ColumnList = syn::punctuated::Punctuated::<syn::TypePath, syn::Token![,]>;
  191. struct MakeIndexParams {
  192. unique: Option<syn::Token![!]>,
  193. name: syn::Ident,
  194. #[allow(dead_code)]
  195. comma: syn::Token![,],
  196. columns: ColumnList
  197. }
  198. impl syn::parse::Parse for MakeIndexParams {
  199. fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
  200. Ok(Self {
  201. unique: input.parse()?,
  202. name: input.parse()?,
  203. comma: input.parse()?,
  204. columns: ColumnList::parse_separated_nonempty(input)?
  205. })
  206. }
  207. }
  208. fn do_make_index(tokens: TokenStream, microrm_ref: proc_macro2::TokenStream) -> TokenStream {
  209. let input = parse_macro_input!(tokens as MakeIndexParams);
  210. let index_struct_name = input.name;
  211. let first_col = input.columns.first().unwrap();
  212. let mut column_type_path = first_col.path.clone();
  213. // remove variant name
  214. column_type_path.segments.pop();
  215. let last = column_type_path.segments.pop().expect("Full path to EntityColumn variant");
  216. column_type_path.segments.push(last.value().clone());
  217. let index_entity_type_name = format_ident!("{}Entity", index_struct_name);
  218. let columns = input.columns.clone().into_iter();
  219. let index_sql_name = format!("{}", index_struct_name).to_case(Case::Snake);
  220. let unique = input.unique.is_some();
  221. quote!{
  222. pub struct #index_struct_name {}
  223. type #index_entity_type_name = <#column_type_path as #microrm_ref::model::EntityColumns>::Entity;
  224. impl #microrm_ref::model::Index for #index_struct_name {
  225. type IndexedEntity = #index_entity_type_name;
  226. fn index_name() -> &'static str {
  227. #index_sql_name
  228. }
  229. fn columns() -> &'static [#column_type_path] where Self: Sized {
  230. &[#(#columns),*]
  231. }
  232. fn unique() -> bool where Self: Sized {
  233. #unique
  234. }
  235. }
  236. }.into()
  237. }
  238. /// Defines a struct to represent a optionally-unique index on a table.
  239. ///
  240. /// Suppose the following `Entity` definition is used:
  241. ///
  242. /// ```ignore
  243. /// #[derive(Entity,Serialize,Deserialize)]
  244. /// struct SystemUser {
  245. /// username: String,
  246. /// hashed_password: String
  247. /// }
  248. /// ```
  249. ///
  250. /// We can now use `make_index!` to define an index on the username field:
  251. /// ```ignore
  252. /// make_index!(SystemUsernameIndex, SystemUserColumns::Username)
  253. /// ```
  254. ///
  255. /// This index can be made unique by adding a `!` prior to the type name, as:
  256. /// ```ignore
  257. /// make_index!(!SystemUsernameUniqueIndex, SystemUserColumns::Username)
  258. /// ```
  259. #[proc_macro]
  260. pub fn make_index(tokens: TokenStream) -> TokenStream {
  261. do_make_index(tokens, quote!{ ::microrm })
  262. }
  263. /// For internal use inside the microrm library. See `make_index`.
  264. #[proc_macro]
  265. pub fn make_index_internal(tokens: TokenStream) -> TokenStream {
  266. do_make_index(tokens, quote!{ crate })
  267. }
  268. // , attributes(microrm_internal))]