Kestrel 7 сар өмнө
parent
commit
d88b415152

+ 5 - 6
microrm-macros/src/entity.rs

@@ -1,10 +1,10 @@
 use convert_case::{Case, Casing};
 use quote::{format_ident, quote};
 
-fn extract_doc_comment(attrs: &Vec<syn::Attribute>) -> proc_macro2::TokenStream {
+fn extract_doc_comment(attrs: &[syn::Attribute]) -> proc_macro2::TokenStream {
     attrs
         .iter()
-        .map(|a| match a.parse_meta() {
+        .flat_map(|a| match a.parse_meta() {
             Ok(syn::Meta::NameValue(mnv)) => {
                 if mnv.path.is_ident("doc") {
                     if let syn::Lit::Str(ls) = mnv.lit {
@@ -16,20 +16,19 @@ fn extract_doc_comment(attrs: &Vec<syn::Attribute>) -> proc_macro2::TokenStream
             }
             _ => None,
         })
-        .flatten()
         .next()
         .unwrap_or(quote! { None })
 }
 
-fn is_elided(attrs: &Vec<syn::Attribute>) -> bool {
+fn is_elided(attrs: &[syn::Attribute]) -> bool {
     attrs.iter().filter(|a| a.path.is_ident("elide")).count() > 0
 }
 
-fn is_unique(attrs: &Vec<syn::Attribute>) -> bool {
+fn is_unique(attrs: &[syn::Attribute]) -> bool {
     attrs.iter().filter(|a| a.path.is_ident("unique")).count() > 0
 }
 
-fn is_key(attrs: &Vec<syn::Attribute>) -> bool {
+fn is_key(attrs: &[syn::Attribute]) -> bool {
     attrs.iter().filter(|a| a.path.is_ident("key")).count() > 0
 }
 

+ 30 - 38
microrm/src/cli/clap_interface.rs

@@ -85,7 +85,7 @@ pub enum EntityKey {
 }
 
 impl EntityKey {
-    fn to_string_vec(vec: &Vec<Self>, ic: &impl InterfaceCustomization) -> Vec<String> {
+    fn to_string_vec(vec: &[Self], ic: &impl InterfaceCustomization) -> Vec<String> {
         vec.iter()
             .map(|v| match v {
                 EntityKey::UserInput(s) => s.to_owned(),
@@ -237,14 +237,12 @@ impl<'l, Error: CLIError> Attacher<'l, Error> {
             Ok(None) => {
                 self.err = Some(Error::no_such_entity(
                     E::entity_name(),
-                    format!(
-                        "{}",
-                        self.remote_keys
-                            .iter()
-                            .cloned()
-                            .reduce(|a, b| format!("{},{}", a, b))
-                            .unwrap()
-                    ),
+                    self.remote_keys
+                        .iter()
+                        .cloned()
+                        .reduce(|a, b| format!("{},{}", a, b))
+                        .unwrap()
+                        .to_string(),
                 ));
             }
             Err(e) => {
@@ -348,14 +346,12 @@ impl<O: CLIObject, IC: InterfaceCustomization> ClapInterface<O, IC> {
                     .get()?
                     .ok_or(<O::Error>::no_such_entity(
                         O::entity_name(),
-                        format!(
-                            "{}",
-                            local_keys
-                                .iter()
-                                .cloned()
-                                .reduce(|a, b| format!("{},{}", a, b))
-                                .unwrap()
-                        ),
+                        local_keys
+                            .iter()
+                            .cloned()
+                            .reduce(|a, b| format!("{},{}", a, b))
+                            .unwrap()
+                            .to_string(),
                     ))?;
 
                 let mut attacher = Attacher {
@@ -396,14 +392,12 @@ impl<O: CLIObject, IC: InterfaceCustomization> ClapInterface<O, IC> {
                     .get()?
                     .ok_or(<O::Error>::no_such_entity(
                         O::entity_name(),
-                        format!(
-                            "{}",
-                            local_keys
-                                .iter()
-                                .cloned()
-                                .reduce(|a, b| format!("{},{}", a, b))
-                                .unwrap()
-                        ),
+                        local_keys
+                            .iter()
+                            .cloned()
+                            .reduce(|a, b| format!("{},{}", a, b))
+                            .unwrap()
+                            .to_string(),
                     ))?;
 
                 let mut attacher = Attacher {
@@ -437,13 +431,11 @@ impl<O: CLIObject, IC: InterfaceCustomization> ClapInterface<O, IC> {
                     .get()?
                     .ok_or(<O::Error>::no_such_entity(
                         O::entity_name(),
-                        format!(
-                            "{}",
-                            keys.iter()
-                                .cloned()
-                                .reduce(|a, b| format!("{},{}", a, b))
-                                .unwrap()
-                        ),
+                        keys.iter()
+                            .cloned()
+                            .reduce(|a, b| format!("{},{}", a, b))
+                            .unwrap()
+                            .to_string(),
                     ))?;
                 println!("{:#?}", obj.as_ref());
 
@@ -460,9 +452,9 @@ impl<O: CLIObject, IC: InterfaceCustomization> ClapInterface<O, IC> {
                         &mut self,
                         datum: &EP::Datum,
                     ) {
-                        struct Discriminator<'l, D: Datum>(&'l D, &'static str);
+                        struct Discriminator(&'static str);
 
-                        impl<'l, D: Datum> DatumDiscriminatorRef for Discriminator<'l, D> {
+                        impl DatumDiscriminatorRef for Discriminator {
                             fn visit_serialized<
                                 T: serde::Serialize + serde::de::DeserializeOwned,
                             >(
@@ -473,23 +465,23 @@ impl<O: CLIObject, IC: InterfaceCustomization> ClapInterface<O, IC> {
                             fn visit_bare_field<T: Datum>(&mut self, _: &T) {}
                             fn visit_entity_id<E: Entity>(&mut self, _: &E::ID) {}
                             fn visit_assoc_map<E: Entity>(&mut self, amap: &AssocMap<E>) {
-                                inspect_ai(self.1, amap);
+                                inspect_ai(self.0, amap);
                             }
                             fn visit_assoc_domain<R: microrm::schema::Relation>(
                                 &mut self,
                                 adomain: &microrm::schema::AssocDomain<R>,
                             ) {
-                                inspect_ai(self.1, adomain);
+                                inspect_ai(self.0, adomain);
                             }
                             fn visit_assoc_range<R: microrm::schema::Relation>(
                                 &mut self,
                                 arange: &microrm::schema::AssocRange<R>,
                             ) {
-                                inspect_ai(self.1, arange);
+                                inspect_ai(self.0, arange);
                             }
                         }
 
-                        datum.accept_discriminator_ref(&mut Discriminator(datum, EP::part_name()));
+                        datum.accept_discriminator_ref(&mut Discriminator(EP::part_name()));
                     }
                 }
 

+ 19 - 16
microrm/src/db.rs

@@ -1,7 +1,11 @@
 use crate::{DBResult, Error};
 use libsqlite3_sys as sq;
 use std::{
-    cell::Cell, collections::HashMap, ffi::{CStr, CString}, pin::Pin, sync::{Arc, Mutex}
+    cell::Cell,
+    collections::HashMap,
+    ffi::{CStr, CString},
+    pin::Pin,
+    sync::{Arc, Mutex},
 };
 
 fn check_rcode<'a>(sql: impl FnOnce() -> Option<&'a str>, rcode: i32) -> Result<(), Error> {
@@ -172,10 +176,8 @@ impl Connection {
                 let stmt = e.insert(Statement { sqlite: conn, stmt });
 
                 run_query(stmt.make_context()?)
-            },
-            Entry::Occupied(mut e) => {
-                run_query(e.get_mut().make_context()?)
-            },
+            }
+            Entry::Occupied(mut e) => run_query(e.get_mut().make_context()?),
         }
     }
 }
@@ -242,7 +244,7 @@ impl Statement {
         Ok(StatementContext {
             stmt: self,
             owned_strings: Default::default(),
-            done: false.into()
+            done: false.into(),
         })
     }
 }
@@ -323,7 +325,7 @@ impl<'a> StatementRow<'a> {
 
 pub struct StatementContext<'a> {
     stmt: &'a Statement,
-    owned_strings: Vec<Pin<Box<String>>>,
+    owned_strings: Vec<Pin<String>>,
     done: Cell<bool>,
 }
 
@@ -332,31 +334,32 @@ impl<'a> StatementContext<'a> {
         bindable.bind(self, index)
     }
 
-    pub fn transfer(&mut self, s: Pin<Box<String>>) {
+    pub fn transfer(&mut self, s: Pin<String>) {
         self.owned_strings.push(s);
     }
 
     fn step(&self) -> DBResult<bool> {
         if self.done.get() {
-            return Ok(false)
+            return Ok(false);
         }
         match unsafe { sq::sqlite3_step(self.stmt.stmt) } {
             sq::SQLITE_ROW => Ok(true),
             sq::SQLITE_DONE => {
                 self.done.set(true);
                 Ok(false)
-            },
+            }
             sq::SQLITE_BUSY => {
                 log::trace!("Concurrent database access!");
                 todo!()
-            },
+            }
             sq::SQLITE_CONSTRAINT => {
-                let msg = unsafe {
-                    CStr::from_ptr(sq::sqlite3_errmsg(self.stmt.sqlite))
-                }.to_str().unwrap().to_string();
+                let msg = unsafe { CStr::from_ptr(sq::sqlite3_errmsg(self.stmt.sqlite)) }
+                    .to_str()
+                    .unwrap()
+                    .to_string();
                 log::trace!("SQLite constraint violation: {msg}");
-                return Err(Error::ConstraintViolation(""))
-            },
+                Err(Error::ConstraintViolation(""))
+            }
             err => {
                 log::trace!("unexpected error during sqlite3_step: {:?}", err);
                 check_rcode(|| None, err)?;

+ 3 - 3
microrm/src/schema.rs

@@ -504,11 +504,11 @@ impl<T: 'static + serde::Serialize + serde::de::DeserializeOwned + std::fmt::Deb
     }
 
     fn bind_to(&self, stmt: &mut StatementContext, index: i32) {
-        let json = Box::pin(
+        let json = std::pin::Pin::new(
             serde_json::to_string(&self.wrapped).expect("couldn't serialize object into JSON"),
         );
 
-        <String as Datum>::bind_to(&*json.as_ref(), stmt, index);
+        <&str as Datum>::bind_to(&&*json.as_ref(), stmt, index);
 
         // transfer ownership so that the data is still around for later
         stmt.transfer(json);
@@ -574,7 +574,7 @@ impl<T: Entity> IDMap<T> {
     }
 }
 
-impl<'l, T: Entity> Insertable<T> for IDMap<T> {
+impl<T: Entity> Insertable<T> for IDMap<T> {
     /// Insert a new Entity into this map, and return its new ID.
     fn insert(&self, value: T) -> DBResult<T::ID> {
         let txn = Transaction::new(self.conn())?;

+ 2 - 2
microrm/src/schema/build.rs

@@ -181,7 +181,7 @@ pub(crate) fn collect_from_database<DB: Database>() -> DatabaseSchema {
 
                     assoc_table
                         .constraints
-                        .push(format!("unique(`range`, `domain`)"));
+                        .push("unique(`range`, `domain`)".to_string());
 
                     tables.insert(assoc_table_name.clone(), assoc_table);
                 }
@@ -209,7 +209,7 @@ pub(crate) fn collect_from_database<DB: Database>() -> DatabaseSchema {
 
                     assoc_table
                         .constraints
-                        .push(format!("unique(`range`, `domain`)"));
+                        .push("unique(`range`, `domain`)".to_string());
                     tables.insert(assoc_table_name.clone(), assoc_table);
                 }
             }

+ 1 - 3
microrm/src/schema/collect.rs

@@ -9,9 +9,7 @@ pub enum PartType {
     /// stores sql data type
     Datum(&'static str),
     /// stores the entity name
-    IDReference(
-        &'static str,
-    ),
+    IDReference(&'static str),
     AssocDomain {
         table_name: String,
         range_name: &'static str,

+ 2 - 4
microrm/src/schema/datum/datum_common.rs

@@ -171,14 +171,12 @@ impl<T: Datum> Datum for Option<T> {
     where
         Self: Sized,
     {
-        let rval = if stmt.read::<db::IsNull>(*index)?.0 {
+        if stmt.read::<db::IsNull>(*index)?.0 {
             *index += 1;
             Ok(None)
         } else {
             T::build_from(adata, stmt, index).map(Some)
-        };
-
-        rval
+        }
     }
 }
 

+ 1 - 0
microrm/src/schema/datum/datum_list.rs

@@ -67,6 +67,7 @@ macro_rules! datum_list {
 
         impl<$( $ty: ConcreteDatum ),*> ConcreteDatumList for ($($ty),*) {
             fn build_equivalent<'l>(mut from: impl Iterator<Item = &'l str>) -> Option<impl QueryEquivalentList<Self> + 'l> {
+                #[allow(clippy::eq_op)]
                 Some((
                         $( if $n == $n { StringQuery( from.next()? ) } else { panic!() } ),*
                 ))