|
@@ -1,11 +1,13 @@
|
|
-use std::hash::Hash;
|
|
|
|
|
|
+use crate::prelude::*;
|
|
|
|
+use std::hash::{Hash,Hasher};
|
|
|
|
|
|
use crate::entity::{Entity, EntityColumn, EntityID};
|
|
use crate::entity::{Entity, EntityColumn, EntityID};
|
|
use crate::model::Modelable;
|
|
use crate::model::Modelable;
|
|
|
|
|
|
-// pub mod expr;
|
|
|
|
-// pub mod condition;
|
|
|
|
-pub mod builder;
|
|
|
|
|
|
+
|
|
|
|
+pub mod build;
|
|
|
|
+
|
|
|
|
+pub use build::{Filterable, Resolvable};
|
|
|
|
|
|
/// Wraps an entity with its ID, for example as a query result.
|
|
/// Wraps an entity with its ID, for example as a query result.
|
|
///
|
|
///
|
|
@@ -59,7 +61,7 @@ impl<T: Entity> std::ops::DerefMut for WithID<T> {
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
-type CacheIndex = (&'static str, std::any::TypeId, u64);
|
|
|
|
|
|
+type CacheIndex = u64;
|
|
|
|
|
|
/// The query interface for a database.
|
|
/// The query interface for a database.
|
|
///
|
|
///
|
|
@@ -76,8 +78,6 @@ pub struct QueryInterface<'l> {
|
|
prevent_send: std::marker::PhantomData<*mut ()>,
|
|
prevent_send: std::marker::PhantomData<*mut ()>,
|
|
}
|
|
}
|
|
|
|
|
|
-const NO_HASH: u64 = 0;
|
|
|
|
-
|
|
|
|
impl<'l> QueryInterface<'l> {
|
|
impl<'l> QueryInterface<'l> {
|
|
pub fn new(db: &'l crate::DB) -> Self {
|
|
pub fn new(db: &'l crate::DB) -> Self {
|
|
Self {
|
|
Self {
|
|
@@ -87,336 +87,128 @@ impl<'l> QueryInterface<'l> {
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
- /// Helper function to process an expected single result
|
|
|
|
- /// Note that this errors out if there is more than a single result
|
|
|
|
|
|
+ /// Helper function to process an expected single result, discarding the rest
|
|
fn expect_one_result<T>(
|
|
fn expect_one_result<T>(
|
|
&self,
|
|
&self,
|
|
stmt: &mut sqlite::Statement,
|
|
stmt: &mut sqlite::Statement,
|
|
- with_result: &mut dyn FnMut(&mut sqlite::Statement) -> Option<T>,
|
|
|
|
- ) -> Option<T> {
|
|
|
|
- let state = stmt.next().ok()?;
|
|
|
|
|
|
+ with_result: &mut dyn FnMut(&mut sqlite::Statement) -> Result<T, crate::Error>,
|
|
|
|
+ ) -> Result<Option<T>, crate::Error> {
|
|
|
|
+ let state = stmt.next()?;
|
|
if state != sqlite::State::Row {
|
|
if state != sqlite::State::Row {
|
|
- return None;
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- let res = with_result(stmt);
|
|
|
|
-
|
|
|
|
- let state = stmt.next().ok()?;
|
|
|
|
- if state != sqlite::State::Done {
|
|
|
|
- return None;
|
|
|
|
|
|
+ return Ok(None)
|
|
|
|
+ // return Err(crate::Error::ExecFailure)
|
|
}
|
|
}
|
|
|
|
|
|
- res
|
|
|
|
|
|
+ Ok(Some(with_result(stmt)?))
|
|
}
|
|
}
|
|
|
|
|
|
/// Helper function to process an expected zero results
|
|
/// Helper function to process an expected zero results
|
|
/// Note that this errors out if there is any result
|
|
/// Note that this errors out if there is any result
|
|
- fn expect_no_result(&self, stmt: &mut sqlite::Statement) -> Option<()> {
|
|
|
|
- let state = stmt.next().ok()?;
|
|
|
|
|
|
+ fn expect_no_result(&self, stmt: &mut sqlite::Statement) -> Result<(), crate::Error> {
|
|
|
|
+ let state = stmt.next()?;
|
|
if state != sqlite::State::Done {
|
|
if state != sqlite::State::Done {
|
|
- return None;
|
|
|
|
|
|
+ return Err(crate::Error::ExecFailure);
|
|
}
|
|
}
|
|
|
|
|
|
- Some(())
|
|
|
|
|
|
+ Ok(())
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
impl<'l> QueryInterface<'l> {
|
|
impl<'l> QueryInterface<'l> {
|
|
- fn cached_query<Return>(
|
|
|
|
|
|
+ fn with_cache<
|
|
|
|
+ Return,
|
|
|
|
+ Create: Fn() -> sqlite::Statement<'l>,
|
|
|
|
+ With: FnMut(&mut sqlite::Statement<'l>) -> Return,
|
|
|
|
+ >(
|
|
&self,
|
|
&self,
|
|
- context: &'static str,
|
|
|
|
- ty: std::any::TypeId,
|
|
|
|
- create: &dyn Fn() -> sqlite::Statement<'l>,
|
|
|
|
- with: &mut dyn FnMut(&mut sqlite::Statement<'l>) -> Return,
|
|
|
|
- ) -> Return {
|
|
|
|
|
|
+ hash: u64,
|
|
|
|
+ create: Create,
|
|
|
|
+ mut with: With,
|
|
|
|
+ ) -> Return
|
|
|
|
+ where {
|
|
let mut cache = self.cache.lock().expect("Couldn't acquire cache?");
|
|
let mut cache = self.cache.lock().expect("Couldn't acquire cache?");
|
|
- let key = (context, ty, NO_HASH);
|
|
|
|
- let query = cache.entry(key).or_insert_with(create);
|
|
|
|
-
|
|
|
|
|
|
+ let query = cache.entry(hash).or_insert_with(create);
|
|
query.reset().expect("Couldn't reset query");
|
|
query.reset().expect("Couldn't reset query");
|
|
with(query)
|
|
with(query)
|
|
}
|
|
}
|
|
|
|
+}
|
|
|
|
|
|
- fn cached_query_column<T: Entity, Return>(
|
|
|
|
- &self,
|
|
|
|
- context: &'static str,
|
|
|
|
- ty: std::any::TypeId,
|
|
|
|
- variant: &[&dyn EntityColumn<Entity = T>],
|
|
|
|
- create: &dyn Fn() -> sqlite::Statement<'l>,
|
|
|
|
- with: &mut dyn FnMut(&mut sqlite::Statement<'l>) -> Return,
|
|
|
|
- ) -> Return {
|
|
|
|
- use std::hash::Hasher;
|
|
|
|
-
|
|
|
|
- let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
|
|
|
- for v in variant {
|
|
|
|
- v.column_typeid().hash(&mut hasher);
|
|
|
|
- }
|
|
|
|
- let hash = hasher.finish();
|
|
|
|
-
|
|
|
|
- let mut cache = self.cache.lock().expect("Couldn't acquire cache?");
|
|
|
|
- let key = (context, ty, hash);
|
|
|
|
- let query = cache.entry(key).or_insert_with(create);
|
|
|
|
-
|
|
|
|
- query.reset().expect("Couldn't reset query");
|
|
|
|
- with(query)
|
|
|
|
|
|
+impl<'l> QueryInterface<'l> {
|
|
|
|
+ pub fn insert<T: Entity + serde::Serialize>(&self, m: &T) -> Result<<T as Entity>::ID, crate::Error> {
|
|
|
|
+ self.add(m)
|
|
}
|
|
}
|
|
|
|
|
|
- /// Search for an entity by a property
|
|
|
|
- pub fn get_one_by<C: EntityColumn, V: Modelable>(
|
|
|
|
- &self,
|
|
|
|
- col: C,
|
|
|
|
- val: V,
|
|
|
|
- ) -> Option<WithID<C::Entity>> {
|
|
|
|
- let table_name = <C::Entity>::table_name();
|
|
|
|
- let column_name = col.name();
|
|
|
|
-
|
|
|
|
- self.cached_query_column(
|
|
|
|
- "get_one_by",
|
|
|
|
- std::any::TypeId::of::<C::Entity>(),
|
|
|
|
- &[&col],
|
|
|
|
|
|
+ /// Add an entity to its table
|
|
|
|
+ pub fn add<T: Entity + serde::Serialize>(&self, m: &T) -> Result<<T as Entity>::ID, crate::Error> {
|
|
|
|
+ let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
|
|
|
+ "add".hash(&mut hasher);
|
|
|
|
+ std::any::TypeId::of::<T>().hash(&mut hasher);
|
|
|
|
+ self.with_cache(
|
|
|
|
+ hasher.finish(),
|
|
&|| {
|
|
&|| {
|
|
|
|
+ let placeholders = (0..(<T as Entity>::column_count() - 1))
|
|
|
|
+ .map(|_| "?".to_string())
|
|
|
|
+ .collect::<Vec<_>>()
|
|
|
|
+ .join(",");
|
|
|
|
+
|
|
self.db
|
|
self.db
|
|
.conn
|
|
.conn
|
|
.prepare(&format!(
|
|
.prepare(&format!(
|
|
- "SELECT * FROM \"{}\" WHERE \"{}\" = ?",
|
|
|
|
- table_name, column_name
|
|
|
|
|
|
+ "INSERT INTO \"{}\" VALUES (NULL, {}) RETURNING \"id\"",
|
|
|
|
+ <T as Entity>::table_name(),
|
|
|
|
+ placeholders
|
|
))
|
|
))
|
|
.expect("")
|
|
.expect("")
|
|
},
|
|
},
|
|
- &mut |stmt| {
|
|
|
|
- val.bind_to(stmt, 1).ok()?;
|
|
|
|
-
|
|
|
|
- self.expect_one_result(stmt, &mut |stmt| {
|
|
|
|
- let id: i64 = stmt.read(0).ok()?;
|
|
|
|
- Some(WithID::wrap(
|
|
|
|
- <<C as EntityColumn>::Entity>::build_from(stmt).ok()?,
|
|
|
|
- id,
|
|
|
|
- ))
|
|
|
|
- })
|
|
|
|
- },
|
|
|
|
- )
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- /// Search for an entity by multiple properties
|
|
|
|
- pub fn get_one_by_multi<T: Entity>(
|
|
|
|
- &self,
|
|
|
|
- c: &[&dyn EntityColumn<Entity = T>],
|
|
|
|
- val: &[&dyn crate::model::Modelable],
|
|
|
|
- ) -> Option<WithID<T>> {
|
|
|
|
- let table_name = T::table_name();
|
|
|
|
-
|
|
|
|
- assert_eq!(c.len(), val.len());
|
|
|
|
-
|
|
|
|
- self.cached_query_column(
|
|
|
|
- "get_one_by_multi",
|
|
|
|
- std::any::TypeId::of::<T>(),
|
|
|
|
- c,
|
|
|
|
- &|| {
|
|
|
|
- let query = format!(
|
|
|
|
- "SELECT * FROM \"{}\" WHERE {}",
|
|
|
|
- table_name,
|
|
|
|
- c.iter()
|
|
|
|
- .map(|col| format!("\"{}\" = ?", col.name()))
|
|
|
|
- .collect::<Vec<_>>()
|
|
|
|
- .join(" AND ")
|
|
|
|
- );
|
|
|
|
- self.db
|
|
|
|
- .conn
|
|
|
|
- .prepare(&query)
|
|
|
|
- .expect(format!("Failed to prepare SQL query: {}", query).as_str())
|
|
|
|
- },
|
|
|
|
- &mut |stmt| {
|
|
|
|
- for index in 0..val.len() {
|
|
|
|
- val[index].bind_to(stmt, index + 1).ok()?;
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- self.expect_one_result(stmt, &mut |stmt| {
|
|
|
|
- let id: i64 = stmt.read(0).ok()?;
|
|
|
|
- Some(WithID::wrap(T::build_from(stmt).ok()?, id))
|
|
|
|
- })
|
|
|
|
- },
|
|
|
|
- )
|
|
|
|
- }
|
|
|
|
|
|
+ &mut |mut stmt: &mut sqlite::Statement<'_>| {
|
|
|
|
+ crate::model::store::serialize_into(&mut stmt, m)?;
|
|
|
|
|
|
- /// Delete entities by searching with a single property
|
|
|
|
- pub fn delete_by<C: EntityColumn, V: Modelable>(&self, c: C, val: V) -> Option<()> {
|
|
|
|
- let table_name = <C::Entity>::table_name();
|
|
|
|
- let column_name = c.name();
|
|
|
|
-
|
|
|
|
- self.cached_query_column(
|
|
|
|
- "delete_by",
|
|
|
|
- std::any::TypeId::of::<C::Entity>(),
|
|
|
|
- &[&c],
|
|
|
|
- &|| {
|
|
|
|
- let query = format!("DELETE FROM \"{}\" WHERE {} = ?", table_name, column_name);
|
|
|
|
- self.db
|
|
|
|
- .conn
|
|
|
|
- .prepare(&query)
|
|
|
|
- .expect(format!("Failed to prepare SQL query: {}", query).as_str())
|
|
|
|
- },
|
|
|
|
- &mut |stmt| {
|
|
|
|
- val.bind_to(stmt, 1).ok()?;
|
|
|
|
|
|
+ let rowid = self.expect_one_result(&mut stmt, &mut |stmt| {
|
|
|
|
+ stmt.read::<i64>(0).map_err(|x| crate::Error::DBError(x))
|
|
|
|
+ })?;
|
|
|
|
|
|
- self.expect_no_result(stmt)
|
|
|
|
|
|
+ Ok(<T as Entity>::ID::from_raw_id(rowid.unwrap()))
|
|
},
|
|
},
|
|
)
|
|
)
|
|
}
|
|
}
|
|
|
|
+}
|
|
|
|
|
|
- /// Delete entities by searching with a single property
|
|
|
|
- pub fn delete_by_id<I: EntityID<Entity = T>, T: Entity<ID = I>>(
|
|
|
|
- &self,
|
|
|
|
- id: <T as Entity>::ID,
|
|
|
|
- ) -> Option<()> {
|
|
|
|
- let table_name = <T as Entity>::table_name();
|
|
|
|
-
|
|
|
|
- self.cached_query(
|
|
|
|
- "delete_by_id",
|
|
|
|
- std::any::TypeId::of::<T>(),
|
|
|
|
- &|| {
|
|
|
|
- let query = format!("DELETE FROM \"{}\" WHERE id = ?", table_name);
|
|
|
|
- self.db
|
|
|
|
- .conn
|
|
|
|
- .prepare(&query)
|
|
|
|
- .expect(format!("Failed to prepare SQL query: {}", query).as_str())
|
|
|
|
- },
|
|
|
|
- &mut |stmt| {
|
|
|
|
- id.bind_to(stmt, 1).ok()?;
|
|
|
|
-
|
|
|
|
- self.expect_no_result(stmt)
|
|
|
|
- },
|
|
|
|
- )
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- /// Delete entities by searching with multiple properties
|
|
|
|
- pub fn delete_by_multi<T: Entity>(
|
|
|
|
- &self,
|
|
|
|
- c: &[&dyn EntityColumn<Entity = T>],
|
|
|
|
- val: &[&dyn crate::model::Modelable],
|
|
|
|
- ) -> Option<()> {
|
|
|
|
- let table_name = <T>::table_name();
|
|
|
|
-
|
|
|
|
- assert_eq!(c.len(), val.len());
|
|
|
|
-
|
|
|
|
- self.cached_query_column(
|
|
|
|
- "delete_by_multi",
|
|
|
|
- std::any::TypeId::of::<T>(),
|
|
|
|
- c,
|
|
|
|
- &|| {
|
|
|
|
- let query = format!(
|
|
|
|
- "DELETE FROM \"{}\" WHERE {}",
|
|
|
|
- table_name,
|
|
|
|
- c.iter()
|
|
|
|
- .map(|col| format!("\"{}\" = ?", col.name()))
|
|
|
|
- .collect::<Vec<_>>()
|
|
|
|
- .join(" AND ")
|
|
|
|
- );
|
|
|
|
- self.db
|
|
|
|
- .conn
|
|
|
|
- .prepare(&query)
|
|
|
|
- .expect(format!("Failed to prepare SQL query: {}", query).as_str())
|
|
|
|
- },
|
|
|
|
- &mut |stmt| {
|
|
|
|
- for index in 0..val.len() {
|
|
|
|
- val[index].bind_to(stmt, index + 1).ok()?;
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- self.expect_no_result(stmt)
|
|
|
|
- },
|
|
|
|
- )
|
|
|
|
|
|
+impl<'l> QueryInterface<'l> {
|
|
|
|
+ pub fn get<'a, 'b, T: Entity>(&'a self) -> build::Select<'b, 'l, T>
|
|
|
|
+ where
|
|
|
|
+ 'a: 'b,
|
|
|
|
+ {
|
|
|
|
+ build::Select::new(self)
|
|
}
|
|
}
|
|
|
|
|
|
- /// Search for an entity by ID
|
|
|
|
- pub fn get_one_by_id<I: EntityID<Entity = T>, T: Entity>(&self, id: I) -> Option<WithID<T>> {
|
|
|
|
- let table_name = <T as Entity>::table_name();
|
|
|
|
-
|
|
|
|
- self.cached_query(
|
|
|
|
- "get_one_by_id",
|
|
|
|
- std::any::TypeId::of::<T>(),
|
|
|
|
- &|| {
|
|
|
|
- self.db
|
|
|
|
- .conn
|
|
|
|
- .prepare(&format!("SELECT * FROM \"{}\" WHERE id = ?", table_name))
|
|
|
|
- .expect("")
|
|
|
|
- },
|
|
|
|
- &mut |stmt| {
|
|
|
|
- id.bind_to(stmt, 1).ok()?;
|
|
|
|
-
|
|
|
|
- self.expect_one_result(stmt, &mut |stmt| {
|
|
|
|
- let id: i64 = stmt.read(0).ok()?;
|
|
|
|
- Some(WithID::wrap(T::build_from(stmt).ok()?, id))
|
|
|
|
- })
|
|
|
|
- },
|
|
|
|
- )
|
|
|
|
|
|
+ pub fn delete<'a, 'b, T: Entity>(&'a self) -> build::Delete<'b, 'l, T>
|
|
|
|
+ where
|
|
|
|
+ 'a: 'b,
|
|
|
|
+ {
|
|
|
|
+ build::Delete::new(self)
|
|
}
|
|
}
|
|
|
|
+}
|
|
|
|
|
|
- /// Search for all entities matching a property
|
|
|
|
- pub fn get_all_by<C: EntityColumn, V: Modelable>(
|
|
|
|
- &self,
|
|
|
|
- c: C,
|
|
|
|
- val: V,
|
|
|
|
- ) -> Option<Vec<WithID<C::Entity>>> {
|
|
|
|
- let table_name = <C::Entity>::table_name();
|
|
|
|
- let column_name = c.name();
|
|
|
|
-
|
|
|
|
- self.cached_query_column(
|
|
|
|
- "get_all_by",
|
|
|
|
- std::any::TypeId::of::<C::Entity>(),
|
|
|
|
- &[&c],
|
|
|
|
- &|| {
|
|
|
|
- self.db
|
|
|
|
- .conn
|
|
|
|
- .prepare(&format!(
|
|
|
|
- "SELECT * FROM \"{}\" WHERE {} = ?",
|
|
|
|
- table_name, column_name
|
|
|
|
- ))
|
|
|
|
- .expect("")
|
|
|
|
- },
|
|
|
|
- &mut |stmt| {
|
|
|
|
- val.bind_to(stmt, 1).ok()?;
|
|
|
|
-
|
|
|
|
- let mut res = Vec::new();
|
|
|
|
- loop {
|
|
|
|
- let state = stmt.next().ok()?;
|
|
|
|
- if state == sqlite::State::Done {
|
|
|
|
- break;
|
|
|
|
- }
|
|
|
|
|
|
+#[cfg(test)]
|
|
|
|
+mod test_build {
|
|
|
|
+ use microrm_macros::Entity;
|
|
|
|
+ use serde::{Deserialize, Serialize};
|
|
|
|
|
|
- let id: i64 = stmt.read(0).ok()?;
|
|
|
|
- res.push(WithID::wrap(C::Entity::build_from(stmt).ok()?, id));
|
|
|
|
- }
|
|
|
|
|
|
+ use crate::QueryInterface;
|
|
|
|
|
|
- Some(res)
|
|
|
|
- },
|
|
|
|
- )
|
|
|
|
|
|
+ #[derive(Entity, Serialize, Deserialize)]
|
|
|
|
+ #[microrm_internal]
|
|
|
|
+ pub struct KVStore {
|
|
|
|
+ key: String,
|
|
|
|
+ value: String,
|
|
}
|
|
}
|
|
|
|
|
|
- /// Add an entity to its table
|
|
|
|
- pub fn add<T: Entity + serde::Serialize>(&self, m: &T) -> Option<<T as Entity>::ID> {
|
|
|
|
- self.cached_query(
|
|
|
|
- "add",
|
|
|
|
- std::any::TypeId::of::<T>(),
|
|
|
|
- &|| {
|
|
|
|
- let placeholders = (0..(<T as Entity>::column_count() - 1))
|
|
|
|
- .map(|_| "?".to_string())
|
|
|
|
- .collect::<Vec<_>>()
|
|
|
|
- .join(",");
|
|
|
|
-
|
|
|
|
- self.db
|
|
|
|
- .conn
|
|
|
|
- .prepare(&format!(
|
|
|
|
- "INSERT INTO \"{}\" VALUES (NULL, {}) RETURNING \"id\"",
|
|
|
|
- <T as Entity>::table_name(),
|
|
|
|
- placeholders
|
|
|
|
- ))
|
|
|
|
- .expect("")
|
|
|
|
- },
|
|
|
|
- &mut |stmt| {
|
|
|
|
- crate::model::store::serialize_into(stmt, m).ok()?;
|
|
|
|
-
|
|
|
|
- let rowid = self.expect_one_result(stmt, &mut |stmt| stmt.read::<i64>(0).ok())?;
|
|
|
|
|
|
+ #[test]
|
|
|
|
+ fn simple_get() {
|
|
|
|
+ use super::*;
|
|
|
|
+ let db = crate::DB::new_in_memory(crate::Schema::new().entity::<KVStore>()).unwrap();
|
|
|
|
+ let qi = db.query_interface();
|
|
|
|
|
|
- Some(<T as Entity>::ID::from_raw_id(rowid))
|
|
|
|
- },
|
|
|
|
- )
|
|
|
|
|
|
+ assert!(qi.get().by(KVStore::Key, "abc").result().is_ok());
|
|
}
|
|
}
|
|
}
|
|
}
|