Browse Source

rustfmt pass.

Kestrel 1 year ago
parent
commit
3671738490

+ 19 - 11
microrm-macros/src/database.rs

@@ -1,15 +1,21 @@
 use convert_case::{Case, Casing};
-use quote::{quote, format_ident};
+use quote::{format_ident, quote};
 
 pub fn derive(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
-    let input : syn::DeriveInput = syn::parse_macro_input!(tokens);
-
-    let items = if let syn::Data::Struct(syn::DataStruct { struct_token: _, fields: syn::Fields::Named(fields), semi_token: _ } ) = input.data {
-        fields.named.into_iter().map(|f| {
-            (f.ident.unwrap(), f.ty)
-        }).collect::<Vec<_>>()
-    }
-    else {
+    let input: syn::DeriveInput = syn::parse_macro_input!(tokens);
+
+    let items = if let syn::Data::Struct(syn::DataStruct {
+        struct_token: _,
+        fields: syn::Fields::Named(fields),
+        semi_token: _,
+    }) = input.data
+    {
+        fields
+            .named
+            .into_iter()
+            .map(|f| (f.ident.unwrap(), f.ty))
+            .collect::<Vec<_>>()
+    } else {
         panic!("Can only derive Database on data structs with named fields!");
     };
 
@@ -18,7 +24,8 @@ pub fn derive(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
     let db_ident = input.ident;
 
     let items = items.iter().map(|field| {
-        let item_combined_name = format_ident!("{}{}", db_ident, field.0.to_string().to_case(Case::Snake));
+        let item_combined_name =
+            format_ident!("{}{}", db_ident, field.0.to_string().to_case(Case::Snake));
         let item_base_name = &field.0.to_string();
         let item_type = &field.1;
 
@@ -42,7 +49,8 @@ pub fn derive(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
                 #(#items)*
             }
         }
-    }.into();
+    }
+    .into();
     println!("out: {}", out);
     out
 }

+ 21 - 10
microrm-macros/src/entity.rs

@@ -1,22 +1,32 @@
 use convert_case::{Case, Casing};
-use quote::{quote, format_ident};
+use quote::{format_ident, quote};
 
 pub fn derive(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
-    let input : syn::DeriveInput = syn::parse_macro_input!(tokens);
+    let input: syn::DeriveInput = syn::parse_macro_input!(tokens);
 
-    let parts = if let syn::Data::Struct(syn::DataStruct { struct_token: _, fields: syn::Fields::Named(fields), semi_token: _ } ) = input.data {
-        fields.named.into_iter().map(|f| {
-            (f.ident.unwrap(), f.ty)
-        }).collect::<Vec<_>>()
-    }
-    else {
+    let parts = if let syn::Data::Struct(syn::DataStruct {
+        struct_token: _,
+        fields: syn::Fields::Named(fields),
+        semi_token: _,
+    }) = input.data
+    {
+        fields
+            .named
+            .into_iter()
+            .map(|f| (f.ident.unwrap(), f.ty))
+            .collect::<Vec<_>>()
+    } else {
         panic!("Can only derive Entity on data structs with named fields!");
     };
 
     let entity_ident = input.ident;
 
     let part_bodies = parts.iter().map(|part| {
-        let part_combined_name = format_ident!("{}{}", entity_ident, part.0.to_string().to_case(Case::Snake));
+        let part_combined_name = format_ident!(
+            "{}{}",
+            entity_ident,
+            part.0.to_string().to_case(Case::Snake)
+        );
         let part_base_name = &part.0.to_string();
         let part_type = &part.1;
         quote! {
@@ -42,5 +52,6 @@ pub fn derive(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
                 );*
             }
         }
-    }.into()
+    }
+    .into()
 }

+ 0 - 59
microrm/benches/simple_in_memory.rs

@@ -1,59 +0,0 @@
-use criterion::{black_box, criterion_group, criterion_main, Criterion};
-
-use microrm::{make_index, Entity, prelude::*};
-use rand::prelude::*;
-use serde::{Deserialize, Serialize};
-
-#[global_allocator]
-static GLOBAL: &stats_alloc::StatsAlloc<std::alloc::System> = &stats_alloc::INSTRUMENTED_SYSTEM;
-
-#[derive(Entity, serde::Serialize, serde::Deserialize)]
-pub struct RowIDIndexed {
-    val: usize,
-}
-
-const MAX_ID: usize = 100;
-
-fn rowid_indexed(c: &mut Criterion) {
-    let schema = microrm::Schema::new().entity::<RowIDIndexed>();
-    let db = microrm::DB::new_in_memory(schema).unwrap();
-    let qi = db.query_interface();
-
-    for i in 0..MAX_ID {
-        qi.add(&RowIDIndexed { val: i * i }).unwrap();
-    }
-
-    let mut reg = stats_alloc::Region::new(&GLOBAL);
-
-    qi.get().by_id(&RowIDIndexedID(1)).exec().unwrap();
-
-    println!(
-        "allocations for single get by_id: {}",
-        reg.change_and_reset().allocations
-    );
-
-    qi.get().by_id(&RowIDIndexedID(1)).exec().unwrap();
-
-    println!(
-        "allocations for second get by_id: {}",
-        reg.change_and_reset().allocations
-    );
-
-    c.bench_function("select 1", |b| {
-        b.iter(|| qi.get().by_id(&RowIDIndexedID(1)).one().unwrap())
-    });
-
-    fn random_id() -> RowIDIndexedID {
-        let res = RowIDIndexedID((rand::random::<usize>() % MAX_ID) as i64 + 1);
-        res
-    }
-
-    c.bench_function("select random", |b| {
-        b.iter(|| {
-            qi.get().by_id(&random_id()).one().unwrap();
-        });
-    });
-}
-
-criterion_group!(benches, rowid_indexed);
-criterion_main!(benches);

+ 49 - 25
microrm/src/db.rs

@@ -4,9 +4,7 @@ pub struct Unique<T: EntityDatum> {
     _ghost: std::marker::PhantomData<T>,
 }
 
-impl<T: EntityDatum> EntityDatum for Unique<T> {
-    
-}
+impl<T: EntityDatum> EntityDatum for Unique<T> {}
 
 pub struct IDMap<T: Entity> {
     conn: std::cell::OnceCell<std::sync::Arc<sqlite::ConnectionThreadSafe>>,
@@ -20,22 +18,30 @@ pub struct AssocSet<T: Entity> {
 
 pub struct Index<T: Entity, Key: EntityDatum> {
     conn: std::cell::OnceCell<std::sync::Arc<sqlite::ConnectionThreadSafe>>,
-    _ghost: std::marker::PhantomData<(T,Key)>,
+    _ghost: std::marker::PhantomData<(T, Key)>,
 }
 
 pub trait DatabaseItem {
     fn item_key() -> &'static str;
     fn dependency_keys() -> &'static [&'static str];
 
-    fn is_index() -> bool { false }
-    fn index_over() -> &'static str { unreachable!() }
-    fn index_columns() -> &'static [&'static str] { unreachable!() }
+    fn is_index() -> bool {
+        false
+    }
+    fn index_over() -> &'static str {
+        unreachable!()
+    }
+    fn index_columns() -> &'static [&'static str] {
+        unreachable!()
+    }
 
     fn accept_entity_visitor(visitor: &mut impl EntityVisitor);
 }
 
 pub trait DatabaseItemVisitor {
-    fn visit<DI: DatabaseItem>(&mut self) where Self: Sized;
+    fn visit<DI: DatabaseItem>(&mut self)
+    where
+        Self: Sized;
 }
 
 pub trait DatabaseSpec {
@@ -45,7 +51,10 @@ pub trait DatabaseSpec {
 
 impl<T: Entity> DatabaseSpec for IDMap<T> {
     fn give_connection(&mut self, conn: std::sync::Arc<sqlite::ConnectionThreadSafe>) {
-        self.conn.set(conn).ok().expect("couldn't set once_cell with sqlite connection!");
+        self.conn
+            .set(conn)
+            .ok()
+            .expect("couldn't set once_cell with sqlite connection!");
     }
     fn accept_entity_visitor(visitor: &mut impl EntityVisitor) {
         visitor.visit::<T>()
@@ -53,14 +62,15 @@ impl<T: Entity> DatabaseSpec for IDMap<T> {
 }
 
 pub trait Database {
-    fn accept_item_visitor(visitor: &mut impl DatabaseItemVisitor) where Self: Sized;
+    fn accept_item_visitor(visitor: &mut impl DatabaseItemVisitor)
+    where
+        Self: Sized;
 }
 
-
 #[cfg(test)]
 mod simple_test {
     use super::*;
-    use crate::entity::{EntityPart,EntityPartVisitor};
+    use crate::entity::{EntityPart, EntityPartVisitor};
     // simple hand-built database example
 
     struct SimpleEntity {
@@ -74,12 +84,18 @@ mod simple_test {
     struct SimpleEntityName;
     impl EntityPart for SimpleEntityName {
         type Datum = String;
-        fn part_name() -> &'static str { "name" }
-        fn is_unique() -> bool { true }
+        fn part_name() -> &'static str {
+            "name"
+        }
+        fn is_unique() -> bool {
+            true
+        }
     }
 
     impl Entity for SimpleEntity {
-        fn entity_name() -> &'static str { "simple_entity" }
+        fn entity_name() -> &'static str {
+            "simple_entity"
+        }
         fn accept_part_visitor(visitor: &mut impl EntityPartVisitor) {
             visitor.visit::<SimpleEntityName>();
         }
@@ -90,11 +106,18 @@ mod simple_test {
     }
 
     impl Database for SimpleDatabase {
-        fn accept_item_visitor(visitor: &mut impl DatabaseItemVisitor) where Self: Sized {
+        fn accept_item_visitor(visitor: &mut impl DatabaseItemVisitor)
+        where
+            Self: Sized,
+        {
             struct SimpleDatabaseStringsItem;
             impl DatabaseItem for SimpleDatabaseStringsItem {
-                fn item_key() -> &'static str { "strings" }
-                fn dependency_keys() -> &'static [&'static str] { &[] }
+                fn item_key() -> &'static str {
+                    "strings"
+                }
+                fn dependency_keys() -> &'static [&'static str] {
+                    &[]
+                }
 
                 fn accept_entity_visitor(visitor: &mut impl EntityVisitor) {
                     visitor.visit::<SimpleEntity>();
@@ -107,7 +130,7 @@ mod simple_test {
 
     #[test]
     fn part_visitor() {
-        struct V { 
+        struct V {
             v: Vec<std::any::TypeId>,
         }
         impl EntityPartVisitor for V {
@@ -118,7 +141,10 @@ mod simple_test {
 
         let mut vis = V { v: vec![] };
         SimpleEntity::accept_part_visitor(&mut vis);
-        assert_eq!(vis.v.as_slice(), &[std::any::TypeId::of::<SimpleEntityName>()]);
+        assert_eq!(
+            vis.v.as_slice(),
+            &[std::any::TypeId::of::<SimpleEntityName>()]
+        );
     }
 }
 
@@ -129,12 +155,12 @@ mod derive_test {
     use super::IDMap;
     #[derive(Entity)]
     struct SimpleEntity {
-        name: super::Unique<String>
+        name: super::Unique<String>,
     }
 
     #[derive(Database)]
     struct SimpleDB {
-        entities: IDMap<SimpleEntity>
+        entities: IDMap<SimpleEntity>,
     }
 
     #[test]
@@ -143,10 +169,8 @@ mod derive_test {
     }
 }
 
-
-
 /*
-// pub trait 
+// pub trait
 
 pub struct Skill { }
 impl Entity for Skill {}

+ 18 - 6
microrm/src/entity.rs

@@ -1,19 +1,31 @@
 /// Represents a data field in an Entity
 pub trait EntityDatum: 'static {
-    
+    fn sql_type() -> &'static str;
 }
 
-impl EntityDatum for String {}
+impl EntityDatum for String {
+    fn sql_type() -> &'static str {
+        "text"
+    }
+}
 
 /// A single data field in an Entity
 pub trait EntityPart: 'static {
     type Datum: EntityDatum;
 
     fn part_name() -> &'static str;
-    fn is_unique() -> bool { false }
-    fn is_assoc() -> bool { false }
-    fn assoc_name() -> &'static str { unreachable!() }
-    fn visit_assoc(_: &mut impl EntityVisitor) { unreachable!() }
+    fn is_unique() -> bool {
+        false
+    }
+    fn is_assoc() -> bool {
+        false
+    }
+    fn assoc_name() -> &'static str {
+        unreachable!()
+    }
+    fn visit_assoc(_: &mut impl EntityVisitor) {
+        unreachable!()
+    }
 }
 
 /// Visitor for traversing all `EntityPart`s in an `Entity`

+ 1 - 1
microrm/src/lib.rs

@@ -1,3 +1,3 @@
+pub mod db;
 pub mod entity;
 pub mod schema;
-pub mod db;

+ 5 - 5
microrm/src/schema.rs

@@ -1,15 +1,16 @@
+use crate::db::{Database, DatabaseItem, DatabaseItemVisitor};
 use crate::entity::{Entity, EntityVisitor};
-use crate::db::{Database,DatabaseItem,DatabaseItemVisitor};
 
 mod entity;
 
-
-
 pub fn collect_from_database<DB: Database>() {
     struct IV(entity::EntityStateContainer);
 
     impl DatabaseItemVisitor for IV {
-        fn visit<DI: DatabaseItem>(&mut self) where Self: Sized {
+        fn visit<DI: DatabaseItem>(&mut self)
+        where
+            Self: Sized,
+        {
             DI::accept_entity_visitor(&mut self.0.make_context(DI::item_key()));
         }
     }
@@ -20,4 +21,3 @@ pub fn collect_from_database<DB: Database>() {
 
     println!("collected base info from database: {:?}", iv.0);
 }
-

+ 9 - 7
microrm/src/schema/entity.rs

@@ -1,6 +1,6 @@
 use std::collections::HashMap;
 
-use crate::entity::{Entity,EntityVisitor, EntityPartVisitor, EntityPart};
+use crate::entity::{Entity, EntityDatum, EntityPart, EntityPartVisitor, EntityVisitor};
 
 #[derive(Debug)]
 pub enum PartType {
@@ -11,7 +11,7 @@ pub enum PartType {
 #[derive(Debug)]
 pub struct PartState {
     name: &'static str,
-    ty: PartType
+    ty: PartType,
 }
 
 impl PartState {
@@ -20,8 +20,8 @@ impl PartState {
             name: EP::part_name(),
             ty: match EP::is_assoc() {
                 true => PartType::Assoc(EP::assoc_name()),
-                false => PartType::Datum("datum placeholder"),
-            }
+                false => PartType::Datum(EP::Datum::sql_type()),
+            },
         }
     }
 }
@@ -37,7 +37,6 @@ pub struct EntityState {
 
 impl EntityState {
     fn build<E: Entity>(context: &'static str) -> Self {
-
         #[derive(Default)]
         struct PartVisitor(Vec<PartState>);
         impl EntityPartVisitor for PartVisitor {
@@ -67,7 +66,7 @@ impl EntityStateContainer {
     pub fn make_context(&mut self, context: &'static str) -> EntityContext {
         EntityContext {
             context,
-            container: self
+            container: self,
         }
     }
 }
@@ -80,7 +79,10 @@ pub struct EntityContext<'a> {
 impl<'a> EntityVisitor for EntityContext<'a> {
     fn visit<E: Entity>(&mut self) {
         println!("visiting entity in context");
-        let entry = self.container.states.entry((self.context, E::entity_name()));
+        let entry = self
+            .container
+            .states
+            .entry((self.context, E::entity_name()));
         // three cases:
         // 1. we haven't seen this entity in this context before
         // 2. we've seen this entity in this context before