mithril_aggregator/database/query/stake_pool/
get_stake_pool.rs1use sqlite::Value;
2
3use mithril_common::entities::Epoch;
4use mithril_common::StdResult;
5use mithril_persistence::sqlite::{Query, SourceAlias, SqLiteEntity, WhereCondition};
6
7use crate::database::record::StakePool;
8
9pub struct GetStakePoolQuery {
11 condition: WhereCondition,
12}
13
14impl GetStakePoolQuery {
15 pub fn by_epoch(epoch: Epoch) -> StdResult<Self> {
17 let condition = WhereCondition::new("epoch = ?*", vec![Value::Integer(epoch.try_into()?)]);
18
19 Ok(Self { condition })
20 }
21}
22
23impl Query for GetStakePoolQuery {
24 type Entity = StakePool;
25
26 fn filters(&self) -> WhereCondition {
27 self.condition.clone()
28 }
29
30 fn get_definition(&self, condition: &str) -> String {
31 let aliases = SourceAlias::new(&[("{:stake_pool:}", "sp")]);
32 let projection = Self::Entity::get_projection().expand(aliases);
33
34 format!("select {projection} from stake_pool as sp where {condition} order by epoch asc, stake desc, stake_pool_id asc")
35 }
36}
37
38#[cfg(test)]
39mod tests {
40 use crate::database::test_helper::{insert_stake_pool, main_db_connection};
41 use mithril_persistence::sqlite::ConnectionExtensions;
42
43 use super::*;
44
45 #[test]
46 fn test_get_stake_pools() {
47 let connection = main_db_connection().unwrap();
48 insert_stake_pool(&connection, &[1, 2, 3]).unwrap();
49
50 let mut cursor = connection
51 .fetch(GetStakePoolQuery::by_epoch(Epoch(1)).unwrap())
52 .unwrap();
53
54 let stake_pool = cursor.next().expect("Should have a stake pool 'pool3'.");
55 assert_eq!(
56 ("pool3".to_string(), Epoch(1), 1200),
57 (stake_pool.stake_pool_id, stake_pool.epoch, stake_pool.stake)
58 );
59 assert_eq!(2, cursor.count());
60
61 let mut cursor = connection
62 .fetch(GetStakePoolQuery::by_epoch(Epoch(3)).unwrap())
63 .unwrap();
64
65 let stake_pool = cursor.next().expect("Should have a stake pool 'pool2'.");
66 assert_eq!(
67 ("pool2".to_string(), Epoch(3), 1190),
68 (stake_pool.stake_pool_id, stake_pool.epoch, stake_pool.stake)
69 );
70 assert_eq!(2, cursor.count());
71
72 let cursor = connection
73 .fetch(GetStakePoolQuery::by_epoch(Epoch(5)).unwrap())
74 .unwrap();
75 assert_eq!(0, cursor.count());
76 }
77}