mithril_aggregator/database/query/signer_registration/
get_signer_registration.rs

1use sqlite::Value;
2
3use mithril_common::{entities::Epoch, StdResult};
4use mithril_persistence::sqlite::{Query, SourceAlias, SqLiteEntity, WhereCondition};
5
6use crate::database::record::SignerRegistrationRecord;
7
8/// Simple queries to retrieve [SignerRegistrationRecord] from the sqlite database.
9pub struct GetSignerRegistrationRecordQuery {
10    condition: WhereCondition,
11}
12
13impl GetSignerRegistrationRecordQuery {
14    #[cfg(test)]
15    pub fn all() -> Self {
16        Self {
17            condition: WhereCondition::default(),
18        }
19    }
20
21    /// Query to get SignerRegistrationRecords for given signer id and epoch.
22    pub fn by_signer_id_and_epoch(signer_id: String, epoch: Epoch) -> StdResult<Self> {
23        let epoch: i64 = epoch.try_into()?;
24        let condition =
25            WhereCondition::new("signer_id = ?*", vec![Value::String(signer_id)]).and_where(
26                WhereCondition::new("epoch_setting_id = ?*", vec![Value::Integer(epoch)]),
27            );
28
29        Ok(Self { condition })
30    }
31
32    /// Query to get SignerRegistrationRecords for a given Epoch.
33    pub fn by_epoch(epoch: Epoch) -> StdResult<Self> {
34        let epoch: i64 = epoch.try_into()?;
35        let condition = WhereCondition::new("epoch_setting_id = ?*", vec![Value::Integer(epoch)]);
36
37        Ok(Self { condition })
38    }
39}
40
41impl Query for GetSignerRegistrationRecordQuery {
42    type Entity = SignerRegistrationRecord;
43
44    fn filters(&self) -> WhereCondition {
45        self.condition.clone()
46    }
47
48    fn get_definition(&self, condition: &str) -> String {
49        let aliases = SourceAlias::new(&[("{:signer_registration:}", "sr")]);
50        let projection = Self::Entity::get_projection().expand(aliases);
51        format!("select {projection} from signer_registration as sr where {condition} order by ROWID desc")
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use chrono::{DateTime, Utc};
58
59    use mithril_common::entities::SignerWithStake;
60    use mithril_common::test_utils::MithrilFixtureBuilder;
61    use mithril_persistence::sqlite::ConnectionExtensions;
62
63    use crate::database::test_helper::{insert_signer_registrations, main_db_connection};
64
65    use super::*;
66
67    fn reset_created_at(
68        signer_registration_records: Vec<SignerRegistrationRecord>,
69    ) -> Vec<SignerRegistrationRecord> {
70        signer_registration_records
71            .into_iter()
72            .map(|mut sr| {
73                sr.created_at = DateTime::<Utc>::default();
74                sr
75            })
76            .collect::<Vec<_>>()
77    }
78
79    #[test]
80    fn test_get_signer_registration_records() {
81        let fixture = MithrilFixtureBuilder::default().with_signers(5).build();
82        let signer_with_stakes = fixture.signers_with_stake();
83        let signer_with_stakes_by_epoch: Vec<(Epoch, Vec<SignerWithStake>)> = (0..=3)
84            .map(|e| (Epoch(e), signer_with_stakes.clone()))
85            .collect();
86
87        let connection = main_db_connection().unwrap();
88        insert_signer_registrations(&connection, signer_with_stakes_by_epoch.clone()).unwrap();
89
90        let signer_registration_records: Vec<SignerRegistrationRecord> = connection
91            .fetch_collect(GetSignerRegistrationRecordQuery::by_epoch(Epoch(1)).unwrap())
92            .unwrap();
93        let expected_signer_registration_records: Vec<SignerRegistrationRecord> =
94            signer_with_stakes_by_epoch[1]
95                .1
96                .iter()
97                .map(|sr| SignerRegistrationRecord::from_signer_with_stake(sr.clone(), Epoch(1)))
98                .rev()
99                .collect();
100        assert_eq!(
101            reset_created_at(expected_signer_registration_records),
102            reset_created_at(signer_registration_records)
103        );
104
105        let signer_registration_records: Vec<SignerRegistrationRecord> = connection
106            .fetch_collect(GetSignerRegistrationRecordQuery::by_epoch(Epoch(3)).unwrap())
107            .unwrap();
108        let expected_signer_registration_records: Vec<SignerRegistrationRecord> =
109            signer_with_stakes_by_epoch[3]
110                .1
111                .iter()
112                .map(|sr| SignerRegistrationRecord::from_signer_with_stake(sr.clone(), Epoch(3)))
113                .rev()
114                .collect();
115        assert_eq!(
116            reset_created_at(expected_signer_registration_records),
117            reset_created_at(signer_registration_records)
118        );
119
120        let cursor = connection
121            .fetch(GetSignerRegistrationRecordQuery::by_epoch(Epoch(5)).unwrap())
122            .unwrap();
123        assert_eq!(0, cursor.count());
124
125        let signer_registration_records: Vec<SignerRegistrationRecord> = connection
126            .fetch_collect(GetSignerRegistrationRecordQuery::all())
127            .unwrap();
128        let expected_signer_registration_records: Vec<SignerRegistrationRecord> =
129            signer_with_stakes_by_epoch
130                .iter()
131                .fold(
132                    Vec::<SignerRegistrationRecord>::new(),
133                    |mut acc, (epoch, signer_with_stakes)| {
134                        acc.extend(
135                            signer_with_stakes
136                                .iter()
137                                .map(|sr| {
138                                    SignerRegistrationRecord::from_signer_with_stake(
139                                        sr.clone(),
140                                        *epoch,
141                                    )
142                                })
143                                .collect::<Vec<SignerRegistrationRecord>>(),
144                        );
145                        acc
146                    },
147                )
148                .into_iter()
149                .rev()
150                .collect();
151        assert_eq!(
152            reset_created_at(expected_signer_registration_records),
153            reset_created_at(signer_registration_records)
154        );
155    }
156}