123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315 |
- use proc_macro::TokenStream;
- use quote::{format_ident, quote};
- use syn::{parse_macro_input, DeriveInput};
- use convert_case::{Case, Casing};
- fn parse_microrm_ref(attrs: &[syn::Attribute]) -> proc_macro2::TokenStream {
- for attr in attrs {
- if attr.path.segments.is_empty() {
- continue;
- }
- if attr.tokens.is_empty() && attr.path.segments.last().unwrap().ident == "microrm_internal"
- {
- return quote! { crate };
- }
- }
- quote! { ::microrm }
- }
- fn parse_fk(attrs: &[syn::Attribute]) -> bool {
- for attr in attrs {
- if attr.path.segments.len() == 1 && attr.path.segments.last().unwrap().ident == "microrm_foreign" {
- return true
- }
- }
- false
- }
- pub fn derive_entity(tokens: TokenStream) -> TokenStream {
- let input = parse_macro_input!(tokens as DeriveInput);
- let microrm_ref = parse_microrm_ref(&input.attrs);
- let struct_name = &input.ident;
- let enum_name = format_ident!("{}Columns", &input.ident);
- let id_name = format_ident!("{}ID", &input.ident);
- let table_name = format!("{}", struct_name).to_case(Case::Snake);
- let st = match input.data {
- syn::Data::Struct(st) => st,
- _ => panic!("Can only use derive(Entity) on structs!"),
- };
- let fields = match st.fields {
- syn::Fields::Named(fields) => fields,
- _ => panic!("Can only use derive(Entity) on non-unit structs with named fields!"),
- };
- let mut variants = Vec::new();
- let mut field_names = Vec::new();
- let mut field_numbers = Vec::new();
- let mut value_references = Vec::new();
- let mut foreign_keys = Vec::new();
- let mut foreign_key_impls = Vec::new();
- for name in fields.named.iter() {
- let converted_case =
- format!("{}", name.ident.as_ref().unwrap().clone()).to_case(Case::UpperCamel);
- let converted_case = format_ident!("{}", converted_case);
- variants.push(converted_case.clone());
- let field_name = name.ident.as_ref().unwrap().clone();
- let field_name_str = format!("{}", field_name);
- field_names.push(quote! { Self::Column::
- let nn = field_numbers.len() + 1;
- field_numbers.push(quote! {
- if parse_fk(&name.attrs) {
- let fk_struct_name = format_ident!("{}{}ForeignKey", struct_name, converted_case);
- let ty = &name.ty;
- foreign_keys.push(quote!{
- &
- });
- foreign_key_impls.push(quote!{
- struct
- col:
- }
- impl
- fn local_column(&self) -> &
- fn foreign_table_name(&self) -> &'static str {
- <<#ty as #microrm_ref::model::EntityID>::Entity as #microrm_ref::model::Entity>::table_name()
- }
- fn foreign_column_name(&self) -> &'static str {
- "id"
- }
- }
- });
- }
- value_references.push(quote! { &self.
- }
- let field_count = fields.named.iter().count();
- quote!{
-
-
-
-
- pub enum
- ID,
-
- }
-
-
- pub struct
-
- impl
- type Entity =
- }
- impl std::convert::From<usize> for
- fn from(i: usize) -> Self {
- match i {
- 0 => Self::ID,
-
- _ => {
- panic!("Given invalid usize to convert to column")
- },
- }
- }
- }
- impl
- type Entity =
- fn from_raw_id(raw: i64) -> Self { Self(raw) }
- fn raw_id(&self) -> i64 { self.0 }
- }
- impl
- fn bind_to(&self, stmt: &mut
- use #microrm_ref::re_export::sqlite::Bindable;
- self.0.bind(stmt, col)
- }
- fn build_from(stmt: &sqlite::Statement, col_offset: usize) -> sqlite::Result<(Self, usize)> where Self: Sized {
- stmt.read::<i64>(col_offset).map(|x| (
- }
- }
-
- impl
- type Column =
- type ID =
- fn table_name() -> &'static str { #table_name }
- fn column_count() -> usize {
- // +1 for ID column
- #field_count + 1
- }
- fn index(c: Self::Column) -> usize {
- c as usize
- }
- fn name(c: Self::Column) -> &'static str {
- match c {
- Self::Column::ID => "ID",
-
- }
- }
- fn values(&self) -> Vec<&dyn
- vec![
- }
- fn foreign_keys() -> &'static [&'static dyn
- &[
- }
- }
-
-
- }.into()
- }
- pub fn derive_modelable(tokens: TokenStream) -> TokenStream {
- let input = parse_macro_input!(tokens as DeriveInput);
- let microrm_ref = parse_microrm_ref(&input.attrs);
- let ident = input.ident;
- quote!{
- impl
- fn bind_to(&self, stmt: &mut
- use #microrm_ref::re_export::sqlite;
- use #microrm_ref::model::Modelable;
- serde_json::to_string(self).expect("can be serialized").bind_to(stmt, col)
- }
- fn build_from(stmt: &
- use #microrm_ref::re_export::sqlite;
- use #microrm_ref::model::Modelable;
- let str_data = stmt.read::<String>(col_offset).map_err(|e| sqlite::Error { code: None, message: Some(e.to_string()) })?;
- let data = serde_json::from_str(str_data.as_str()).map_err(|e| sqlite::Error { code: None, message: Some(e.to_string()) })?;
- Ok((data,1))
- }
- }
- }.into()
- }
- type ColumnList = syn::punctuated::Punctuated::<syn::TypePath, syn::Token![,]>;
- struct MakeIndexParams {
- unique: Option<syn::Token![!]>,
- name: syn::Ident,
-
- comma: syn::Token![,],
- columns: ColumnList
- }
- impl syn::parse::Parse for MakeIndexParams {
- fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
- Ok(Self {
- unique: input.parse()?,
- name: input.parse()?,
- comma: input.parse()?,
- columns: ColumnList::parse_separated_nonempty(input)?
- })
- }
- }
- fn do_make_index(tokens: TokenStream, microrm_ref: proc_macro2::TokenStream) -> TokenStream {
- let input = parse_macro_input!(tokens as MakeIndexParams);
- let index_struct_name = input.name;
- let first_col = input.columns.first().unwrap();
- let mut column_type_path = first_col.path.clone();
-
- column_type_path.segments.pop();
- let last = column_type_path.segments.pop().expect("Full path to EntityColumn variant");
- column_type_path.segments.push(last.value().clone());
- let index_entity_type_name = format_ident!("{}Entity", index_struct_name);
- let columns = input.columns.clone().into_iter();
- let index_sql_name = format!("{}", index_struct_name).to_case(Case::Snake);
- let unique = input.unique.is_some();
- quote!{
- pub struct
- type
- impl
- type IndexedEntity =
- fn index_name() -> &'static str {
- #index_sql_name
- }
- fn columns() -> &'static [
- &[
- }
- fn unique() -> bool where Self: Sized {
-
- }
- }
- }.into()
- }
- pub fn make_index(tokens: TokenStream) -> TokenStream {
- do_make_index(tokens, quote!{ ::microrm })
- }
- pub fn make_index_internal(tokens: TokenStream) -> TokenStream {
- do_make_index(tokens, quote!{ crate })
- }
-
|