mithril_signer/database/query/protocol_initializer/
get_protocol_initializer.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use sqlite::Value;

use mithril_common::entities::Epoch;
use mithril_persistence::sqlite::{Query, SourceAlias, SqLiteEntity, WhereCondition};

use crate::database::record::ProtocolInitializerRecord;

/// Simple queries to retrieve [ProtocolInitializer] from the sqlite database.
pub struct GetProtocolInitializerQuery {
    condition: WhereCondition,
    limit: Option<usize>,
}

impl GetProtocolInitializerQuery {
    /// Get protocol initializer that match the epoch.
    pub fn for_epoch(epoch: Epoch) -> Self {
        let epoch_i64: i64 = epoch.try_into().unwrap();
        let condition = WhereCondition::new(
            "protocol_initializer.epoch = ?",
            vec![Value::Integer(epoch_i64)],
        );

        Self {
            condition,
            limit: None,
        }
    }

    pub fn last_n(limit: usize) -> Self {
        let condition = WhereCondition::default();
        Self {
            condition,
            limit: Some(limit),
        }
    }
}

impl Query for GetProtocolInitializerQuery {
    type Entity = ProtocolInitializerRecord;

    fn filters(&self) -> WhereCondition {
        self.condition.clone()
    }

    fn get_definition(&self, condition: &str) -> String {
        let aliases = SourceAlias::new(&[("{:protocol_initializer:}", "protocol_initializer")]);
        let projection = Self::Entity::get_projection().expand(aliases);
        let limit = self
            .limit
            .map_or("".to_string(), |limit| format!(" limit {}", limit));
        format!("select {projection} from protocol_initializer where {condition} order by rowid desc{limit}")
    }
}