|
| 1 | +use crate::sqlite::condition::GetAllCondition; |
1 | 2 | use anyhow::Context;
|
2 | 3 | use mithril_common::StdResult;
|
3 | 4 |
|
4 | 5 | use super::{EntityCursor, SqLiteEntity, SqliteConnection, WhereCondition};
|
5 | 6 |
|
6 |
| -/// A Provider is able to performe queries on a database and return iterator of a defined entity. |
| 7 | +/// A Provider is able to perform queries on a database and return iterator of a defined entity. |
7 | 8 | /// It aims at being easily testable and adaptable.
|
8 | 9 | pub trait Provider<'conn> {
|
9 | 10 | /// Entity type returned by the result cursor.
|
@@ -38,6 +39,22 @@ pub trait Provider<'conn> {
|
38 | 39 | fn get_definition(&self, condition: &str) -> String;
|
39 | 40 | }
|
40 | 41 |
|
| 42 | +/// An extension of the [Provider] that can return all the entities of a given type. |
| 43 | +pub trait GetAllProvider<'conn, E: SqLiteEntity> { |
| 44 | + /// Return all the entities of the given type. |
| 45 | + fn get_all(&'conn self) -> StdResult<EntityCursor<'conn, E>>; |
| 46 | +} |
| 47 | + |
| 48 | +impl<'conn, P, E> GetAllProvider<'conn, E> for P |
| 49 | +where |
| 50 | + P: Provider<'conn, Entity = E> + GetAllCondition, |
| 51 | + E: SqLiteEntity, |
| 52 | +{ |
| 53 | + fn get_all(&'conn self) -> StdResult<EntityCursor<'conn, E>> { |
| 54 | + self.find(P::get_all_condition()) |
| 55 | + } |
| 56 | +} |
| 57 | + |
41 | 58 | #[cfg(test)]
|
42 | 59 | mod tests {
|
43 | 60 | use sqlite::{Connection, Value};
|
@@ -136,6 +153,8 @@ returning {projection}
|
136 | 153 | }
|
137 | 154 | }
|
138 | 155 |
|
| 156 | + impl GetAllCondition for TestEntityProvider<'_> {} |
| 157 | + |
139 | 158 | fn init_database() -> SqliteConnection {
|
140 | 159 | let connection = Connection::open_thread_safe(":memory:").unwrap();
|
141 | 160 | connection
|
@@ -231,6 +250,7 @@ returning {projection}
|
231 | 250 | );
|
232 | 251 | assert!(cursor.next().is_none());
|
233 | 252 | }
|
| 253 | + |
234 | 254 | #[test]
|
235 | 255 | fn test_upsertion() {
|
236 | 256 | let connection = init_database();
|
@@ -258,4 +278,30 @@ returning {projection}
|
258 | 278 | );
|
259 | 279 | assert!(cursor.next().is_none());
|
260 | 280 | }
|
| 281 | + |
| 282 | + #[test] |
| 283 | + pub fn test_blanket_get_all() { |
| 284 | + let connection = init_database(); |
| 285 | + let provider = TestEntityProvider::new(&connection); |
| 286 | + let cursor = provider.get_all().unwrap(); |
| 287 | + let entities: Vec<TestEntity> = cursor.collect(); |
| 288 | + |
| 289 | + assert_eq!( |
| 290 | + vec![ |
| 291 | + TestEntity { |
| 292 | + text_data: "row 1".to_string(), |
| 293 | + real_data: 1.23, |
| 294 | + integer_data: -52, |
| 295 | + maybe_null: None |
| 296 | + }, |
| 297 | + TestEntity { |
| 298 | + text_data: "row 2".to_string(), |
| 299 | + real_data: 2.34, |
| 300 | + integer_data: 1789, |
| 301 | + maybe_null: Some(0) |
| 302 | + } |
| 303 | + ], |
| 304 | + entities |
| 305 | + ); |
| 306 | + } |
261 | 307 | }
|
0 commit comments