mithril_signer/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 #[cfg(test)]
23 pub(crate) fn all() -> Self {
24 Self {
25 condition: WhereCondition::default(),
26 }
27 }
28}
29
30impl Query for GetStakePoolQuery {
31 type Entity = StakePool;
32
33 fn filters(&self) -> WhereCondition {
34 self.condition.clone()
35 }
36
37 fn get_definition(&self, condition: &str) -> String {
38 let aliases = SourceAlias::new(&[("{:stake_pool:}", "sp")]);
39 let projection = Self::Entity::get_projection().expand(aliases);
40
41 format!("select {projection} from stake_pool as sp where {condition} order by epoch asc, stake desc, stake_pool_id asc")
42 }
43}
44
45#[cfg(test)]
46mod tests {
47 use super::*;
48 use crate::database::{query::InsertOrReplaceStakePoolQuery, test_helper::main_db_connection};
49 use mithril_persistence::sqlite::ConnectionExtensions;
50
51 #[test]
52 fn test_query_sorts_the_return_stake_pool_by_epoch_stack_and_stake_pool_id() {
53 let connection = main_db_connection().unwrap();
54 connection
55 .apply(InsertOrReplaceStakePoolQuery::many(vec![
56 ("pool-A".to_string(), Epoch(1), 1500),
57 ("pool-D".to_string(), Epoch(2), 1250),
58 ("pool-B".to_string(), Epoch(1), 1000),
59 ("pool-E".to_string(), Epoch(1), 1600),
60 ("pool-C".to_string(), Epoch(1), 1600),
61 ]))
62 .unwrap();
63
64 let stake_pool_in_database: Vec<StakePool> =
65 connection.fetch_collect(GetStakePoolQuery::all()).unwrap();
66
67 assert_eq!(
68 vec![
69 ("pool-C".to_string(), Epoch(1), 1600),
70 ("pool-E".to_string(), Epoch(1), 1600),
71 ("pool-A".to_string(), Epoch(1), 1500),
72 ("pool-B".to_string(), Epoch(1), 1000),
73 ("pool-D".to_string(), Epoch(2), 1250),
74 ],
75 stake_pool_in_database
76 .into_iter()
77 .map(|s| (s.stake_pool_id, s.epoch, s.stake))
78 .collect::<Vec<_>>()
79 );
80 }
81}