Browse Source

rustfmt pass.

Kestrel 2 years ago
parent
commit
ce04e995b5
6 changed files with 181 additions and 66 deletions
  1. 47 15
      microrm/src/lib.rs
  2. 23 10
      microrm/src/model.rs
  3. 44 17
      microrm/src/model/create.rs
  4. 12 4
      microrm/src/model/load.rs
  5. 3 1
      microrm/src/model/store.rs
  6. 52 19
      microrm/src/query.rs

+ 47 - 15
microrm/src/lib.rs

@@ -3,31 +3,47 @@ pub mod query;
 
 pub use microrm_macros::Entity;
 
-#[derive(Debug,serde::Serialize,serde::Deserialize,Entity)]
+#[derive(Debug, serde::Serialize, serde::Deserialize, Entity)]
 struct Metaschema {
     key: String,
-    value: String
+    value: String,
 }
 
 pub struct DB {
     conn: rusqlite::Connection,
     schema_hash: String,
-    schema: model::SchemaModel
+    schema: model::SchemaModel,
 }
 
 impl DB {
     pub fn new(schema: model::SchemaModel, path: &str, allow_recreate: bool) -> Self {
-        Self::from_connection(rusqlite::Connection::open(path).expect("Opening database connection failed"), schema, allow_recreate)
+        Self::from_connection(
+            rusqlite::Connection::open(path).expect("Opening database connection failed"),
+            schema,
+            allow_recreate,
+        )
     }
 
     /// For use in tests
     pub fn new_in_memory(schema: model::SchemaModel) -> Self {
-        Self::from_connection(rusqlite::Connection::open_in_memory().expect("Opening database connection failed"), schema, true)
+        Self::from_connection(
+            rusqlite::Connection::open_in_memory().expect("Opening database connection failed"),
+            schema,
+            true,
+        )
     }
 
-    fn from_connection(conn: rusqlite::Connection, schema: model::SchemaModel, allow_recreate: bool) -> Self {
+    fn from_connection(
+        conn: rusqlite::Connection,
+        schema: model::SchemaModel,
+        allow_recreate: bool,
+    ) -> Self {
         let sig = Self::calculate_schema_hash(&schema);
-        let ret = Self { conn, schema_hash: sig, schema: schema.add::<Metaschema>() };
+        let ret = Self {
+            conn,
+            schema_hash: sig,
+            schema: schema.add::<Metaschema>(),
+        };
         ret.check_schema(allow_recreate);
         ret
     }
@@ -36,8 +52,16 @@ impl DB {
         use sha2::Digest;
 
         let mut hasher = sha2::Sha256::new();
-        schema.drop().iter().map(|sql| hasher.update(sql.as_bytes())).count();
-        schema.create().iter().map(|sql| hasher.update(sql.as_bytes())).count();
+        schema
+            .drop()
+            .iter()
+            .map(|sql| hasher.update(sql.as_bytes()))
+            .count();
+        schema
+            .create()
+            .iter()
+            .map(|sql| hasher.update(sql.as_bytes()))
+            .count();
 
         base64::encode(hasher.finalize())
     }
@@ -61,9 +85,18 @@ impl DB {
                 prepared.unwrap().execute([]).expect("Creation sql failed");
             }
 
-            query::add(self, &Metaschema { key: "schema_hash".to_string(), value: self.schema_hash.clone() });
-
-            println!("re-search results: {:?}", query::get_one_by::<Metaschema, _>(self, MetaschemaColumns::Key, "schema_hash"));
+            query::add(
+                self,
+                &Metaschema {
+                    key: "schema_hash".to_string(),
+                    value: self.schema_hash.clone(),
+                },
+            );
+
+            println!(
+                "re-search results: {:?}",
+                query::get_one_by::<Metaschema, _>(self, MetaschemaColumns::Key, "schema_hash")
+            );
         }
     }
 }
@@ -72,14 +105,13 @@ impl DB {
 mod test {
     use super::DB;
 
-    #[derive(serde::Serialize,serde::Deserialize,crate::Entity)]
+    #[derive(serde::Serialize, serde::Deserialize, crate::Entity)]
     struct S1 {
         id: i32,
     }
 
     fn simple_schema() -> super::model::SchemaModel {
-        super::model::SchemaModel::new()
-            .add::<S1>()
+        super::model::SchemaModel::new().add::<S1>()
     }
 
     #[test]

+ 23 - 10
microrm/src/model.rs

@@ -1,12 +1,12 @@
-pub(crate) mod load;
 mod create;
+pub(crate) mod load;
 pub(crate) mod store;
 
 #[derive(Debug)]
 pub enum ModelError {
     DBError(rusqlite::Error),
     LoadError(String),
-    EmptyStoreError
+    EmptyStoreError,
 }
 
 impl From<rusqlite::Error> for ModelError {
@@ -33,15 +33,21 @@ impl serde::de::Error for ModelError {
     }
 }
 
-impl std::error::Error for ModelError { }
+impl std::error::Error for ModelError {}
 
 /// A database entity, aka a struct representing a row in a table
-pub trait Entity : for<'de> serde::Deserialize<'de> + serde::Serialize {
+pub trait Entity: for<'de> serde::Deserialize<'de> + serde::Serialize {
     type Column;
     fn table_name() -> &'static str;
-    fn column_count() -> usize where Self: Sized;
-    fn index(c: Self::Column) -> usize where Self: Sized;
-    fn name(c: Self::Column) -> &'static str where Self: Sized;
+    fn column_count() -> usize
+    where
+        Self: Sized;
+    fn index(c: Self::Column) -> usize
+    where
+        Self: Sized;
+    fn name(c: Self::Column) -> &'static str
+    where
+        Self: Sized;
     fn values(&self) -> Vec<&dyn rusqlite::ToSql>;
 }
 
@@ -54,7 +60,10 @@ pub struct SchemaModel {
 
 impl SchemaModel {
     pub fn new() -> Self {
-        Self { drop: Vec::new(), create: Vec::new() }
+        Self {
+            drop: Vec::new(),
+            create: Vec::new(),
+        }
     }
 
     pub fn add<'de, E: Entity>(mut self) -> Self {
@@ -64,6 +73,10 @@ impl SchemaModel {
         self
     }
 
-    pub fn drop(&self) -> &Vec<String> { &self.drop }
-    pub fn create(&self) -> &Vec<String> { &self.create }
+    pub fn drop(&self) -> &Vec<String> {
+        &self.drop
+    }
+    pub fn create(&self) -> &Vec<String> {
+        &self.create
+    }
 }

+ 44 - 17
microrm/src/model/create.rs

@@ -5,7 +5,7 @@ pub struct CreateDeserializer<'de> {
     table_name: Option<&'static str>,
     column_names: Option<&'static [&'static str]>,
     column_types: Vec<String>,
-    _de: std::marker::PhantomData<&'de u8>
+    _de: std::marker::PhantomData<&'de u8>,
 }
 
 impl<'de, 'a> serde::de::Deserializer<'de> for &'a mut CreateDeserializer<'de> {
@@ -36,9 +36,13 @@ impl<'de, 'a> serde::de::Deserializer<'de> for &'a mut CreateDeserializer<'de> {
         self.column_types.push("varchar".to_owned());
         v.visit_string("".to_owned())
     }
-    
 
-    fn deserialize_struct<V: Visitor<'de>>(self, name: &'static str, fields: &'static [&'static str], v: V) -> Result<V::Value, Self::Error> {
+    fn deserialize_struct<V: Visitor<'de>>(
+        self,
+        name: &'static str,
+        fields: &'static [&'static str],
+        v: V,
+    ) -> Result<V::Value, Self::Error> {
         self.table_name = Some(name);
         self.column_names = Some(fields);
         v.visit_seq(self)
@@ -47,46 +51,69 @@ impl<'de, 'a> serde::de::Deserializer<'de> for &'a mut CreateDeserializer<'de> {
 
 impl<'de> serde::de::SeqAccess<'de> for CreateDeserializer<'de> {
     type Error = super::ModelError;
-    
-    fn next_element_seed<T: serde::de::DeserializeSeed<'de>>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> {
+
+    fn next_element_seed<T: serde::de::DeserializeSeed<'de>>(
+        &mut self,
+        seed: T,
+    ) -> Result<Option<T::Value>, Self::Error> {
         seed.deserialize(self).map(Some)
     }
 }
 
-pub fn sql_for<'de, T: crate::model::Entity>() -> (String,String) {
-    let mut cd = CreateDeserializer { table_name: None, column_names: None, column_types: Vec::new(), _de: std::marker::PhantomData{} };
+pub fn sql_for<'de, T: crate::model::Entity>() -> (String, String) {
+    let mut cd = CreateDeserializer {
+        table_name: None,
+        column_names: None,
+        column_types: Vec::new(),
+        _de: std::marker::PhantomData {},
+    };
 
     T::deserialize(&mut cd).expect("SQL creation failed!");
 
     (
-        format!("DROP TABLE IF EXISTS {}", <T as crate::model::Entity>::table_name()),
-        format!("CREATE TABLE {} ({})",
+        format!(
+            "DROP TABLE IF EXISTS {}",
+            <T as crate::model::Entity>::table_name()
+        ),
+        format!(
+            "CREATE TABLE {} ({})",
             <T as crate::model::Entity>::table_name(),
-            cd.column_names.unwrap().iter().zip(cd.column_types.iter())
-                .map(|(n,t)| n.to_string() + " " + t).collect::<Vec<_>>().join(",")
-            )
+            cd.column_names
+                .unwrap()
+                .iter()
+                .zip(cd.column_types.iter())
+                .map(|(n, t)| n.to_string() + " " + t)
+                .collect::<Vec<_>>()
+                .join(",")
+        ),
     )
 }
 
 #[cfg(test)]
 mod test {
-    #[derive(serde::Serialize,serde::Deserialize,crate::Entity)]
+    #[derive(serde::Serialize, serde::Deserialize, crate::Entity)]
     struct Empty {}
 
-    #[derive(serde::Serialize,serde::Deserialize,crate::Entity)]
+    #[derive(serde::Serialize, serde::Deserialize, crate::Entity)]
     struct Single {
-        e: i32
+        e: i32,
     }
 
     #[test]
     fn example_sql_for() {
         assert_eq!(
             super::sql_for::<Empty>(),
-            ("DROP TABLE IF EXISTS empty".to_owned(), "CREATE TABLE empty ()".to_owned())
+            (
+                "DROP TABLE IF EXISTS empty".to_owned(),
+                "CREATE TABLE empty ()".to_owned()
+            )
         );
         assert_eq!(
             super::sql_for::<Single>(),
-            ("DROP TABLE IF EXISTS single".to_owned(), "CREATE TABLE single (e integer)".to_owned())
+            (
+                "DROP TABLE IF EXISTS single".to_owned(),
+                "CREATE TABLE single (e integer)".to_owned()
+            )
         );
     }
 }

+ 12 - 4
microrm/src/model/load.rs

@@ -4,7 +4,7 @@ use rusqlite::Row;
 
 pub struct RowDeserializer<'de> {
     row: &'de Row<'de>,
-    col_index: usize
+    col_index: usize,
 }
 
 impl<'de> RowDeserializer<'de> {
@@ -57,7 +57,12 @@ impl<'de, 'a> serde::de::Deserializer<'de> for &'a mut RowDeserializer<'de> {
         res
     }
 
-    fn deserialize_struct<V: Visitor<'de>>(self, _name: &'static str, _fields: &'static [&'static str], v: V) -> Result<V::Value, Self::Error> {
+    fn deserialize_struct<V: Visitor<'de>>(
+        self,
+        _name: &'static str,
+        _fields: &'static [&'static str],
+        v: V,
+    ) -> Result<V::Value, Self::Error> {
         v.visit_seq(self)
     }
 
@@ -70,8 +75,11 @@ impl<'de, 'a> serde::de::Deserializer<'de> for &'a mut RowDeserializer<'de> {
 
 impl<'de> serde::de::SeqAccess<'de> for RowDeserializer<'de> {
     type Error = super::ModelError;
-    
-    fn next_element_seed<T: serde::de::DeserializeSeed<'de>>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> {
+
+    fn next_element_seed<T: serde::de::DeserializeSeed<'de>>(
+        &mut self,
+        seed: T,
+    ) -> Result<Option<T::Value>, Self::Error> {
         seed.deserialize(self).map(Some)
     }
 }

+ 3 - 1
microrm/src/model/store.rs

@@ -1,3 +1,5 @@
-pub fn serialize_as_row<'data, T: crate::model::Entity>(value: &'data T) -> Vec<&'data dyn rusqlite::ToSql> {
+pub fn serialize_as_row<'data, T: crate::model::Entity>(
+    value: &'data T,
+) -> Vec<&'data dyn rusqlite::ToSql> {
     value.values()
 }

+ 52 - 19
microrm/src/query.rs

@@ -1,49 +1,70 @@
 pub use crate::DB;
 
-#[derive(Clone,Copy,Debug)]
-pub struct ID (i64);
+#[derive(Clone, Copy, Debug)]
+pub struct ID(i64);
 
 #[derive(Debug)]
 pub struct WithID<T: crate::model::Entity + crate::model::Entity> {
     wrap: T,
-    id: ID
+    id: ID,
 }
 
 impl<T: crate::model::Entity + crate::model::Entity> WithID<T> {
     fn wrap(what: T, raw_id: i64) -> Self {
-        Self { wrap: what, id: ID { 0: raw_id } }
+        Self {
+            wrap: what,
+            id: ID { 0: raw_id },
+        }
     }
 }
 
 impl<T: crate::model::Entity + crate::model::Entity> WithID<T> {
-    pub fn id(&self) -> ID { self.id }
+    pub fn id(&self) -> ID {
+        self.id
+    }
 }
 
 impl<T: crate::model::Entity + crate::model::Entity> AsRef<T> for WithID<T> {
-    fn as_ref(&self) -> &T { return &self.wrap }
+    fn as_ref(&self) -> &T {
+        return &self.wrap;
+    }
 }
 
 impl<T: crate::model::Entity + crate::model::Entity> std::ops::Deref for WithID<T> {
     type Target = T;
-    fn deref(&self) -> &Self::Target { &self.wrap }
+    fn deref(&self) -> &Self::Target {
+        &self.wrap
+    }
 }
 
 impl<T: crate::model::Entity + crate::model::Entity> std::ops::DerefMut for WithID<T> {
-    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.wrap }
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.wrap
+    }
 }
 
-
 /// Search for an entity by a property
 pub fn get_one_by<T: crate::model::Entity, V: rusqlite::ToSql>(
-    db: &DB, c: <T as crate::model::Entity>::Column, val: V) -> Option<WithID<T>> {
-
+    db: &DB,
+    c: <T as crate::model::Entity>::Column,
+    val: V,
+) -> Option<WithID<T>> {
     let table_name = <T as crate::model::Entity>::table_name();
     let column_name = <T as crate::model::Entity>::name(c);
-    let mut prepared = db.conn.prepare(&format!("SELECT rowid, tbl.* FROM {} tbl WHERE {} = ?1", table_name, column_name)).ok()?;
+    let mut prepared = db
+        .conn
+        .prepare(&format!(
+            "SELECT rowid, tbl.* FROM {} tbl WHERE {} = ?1",
+            table_name, column_name
+        ))
+        .ok()?;
 
     let result = prepared.query_row([&val], |row| {
         let mut deser = crate::model::load::RowDeserializer::from_row(row);
-        Ok(WithID::wrap(T::deserialize(&mut deser).expect("deserialization works"), row.get(0).expect("can get rowid")))
+        Ok(WithID::wrap(
+            T::deserialize(&mut deser).expect("deserialization works"),
+            row.get(0).expect("can get rowid"),
+        ))
     });
 
     result.ok()
@@ -53,9 +74,16 @@ pub fn get_one_by<T: crate::model::Entity, V: rusqlite::ToSql>(
 pub fn add<T: crate::model::Entity + serde::Serialize>(db: &DB, m: &T) -> Option<ID> {
     let row = crate::model::store::serialize_as_row(m);
 
-    let placeholders = (0..<T as crate::model::Entity>::column_count()).map(|n| format!("?{}", n+1)).collect::<Vec<_>>().join(",");
+    let placeholders = (0..<T as crate::model::Entity>::column_count())
+        .map(|n| format!("?{}", n + 1))
+        .collect::<Vec<_>>()
+        .join(",");
 
-    let res = db.conn.prepare(&format!("INSERT INTO {} VALUES ({})", <T as crate::model::Entity>::table_name(), placeholders));
+    let res = db.conn.prepare(&format!(
+        "INSERT INTO {} VALUES ({})",
+        <T as crate::model::Entity>::table_name(),
+        placeholders
+    ));
     let mut prepared = res.ok()?;
 
     // make sure we bound enough things
@@ -66,13 +94,18 @@ pub fn add<T: crate::model::Entity + serde::Serialize>(db: &DB, m: &T) -> Option
 }
 
 pub struct Context<'a> {
-    db: &'a DB
+    db: &'a DB,
 }
 
 impl<'a> Context<'a> {
-    pub fn get_one_by<T: crate::model::Entity + for<'de> serde::Deserialize<'de>, V: rusqlite::ToSql>(
-        &self, c: <T as crate::model::Entity>::Column, val: V) -> Option<WithID<T>> {
-
+    pub fn get_one_by<
+        T: crate::model::Entity + for<'de> serde::Deserialize<'de>,
+        V: rusqlite::ToSql,
+    >(
+        &self,
+        c: <T as crate::model::Entity>::Column,
+        val: V,
+    ) -> Option<WithID<T>> {
         get_one_by(self.db, c, val)
     }
 }