mithril_aggregator/database/query/open_message/
insert_open_message.rs

1use chrono::Utc;
2use sqlite::Value;
3use uuid::Uuid;
4
5use mithril_common::entities::{Epoch, ProtocolMessage, SignedEntityType};
6use mithril_common::StdResult;
7use mithril_persistence::sqlite::{Query, SourceAlias, SqLiteEntity, WhereCondition};
8
9use crate::database::record::OpenMessageRecord;
10
11/// Query to insert [OpenMessageRecord] in the sqlite database
12pub struct InsertOpenMessageQuery {
13    condition: WhereCondition,
14}
15
16impl InsertOpenMessageQuery {
17    pub fn one(
18        epoch: Epoch,
19        signed_entity_type: &SignedEntityType,
20        protocol_message: &ProtocolMessage,
21    ) -> StdResult<Self> {
22        let expression = "(open_message_id, epoch_setting_id, beacon, signed_entity_type_id, protocol_message, expires_at, created_at) values (?*, ?*, ?*, ?*, ?*, ?*, ?*)";
23        let beacon_str = signed_entity_type.get_json_beacon()?;
24        let parameters = vec![
25            Value::String(Uuid::new_v4().to_string()),
26            Value::Integer(epoch.try_into()?),
27            Value::String(beacon_str),
28            Value::Integer(signed_entity_type.index() as i64),
29            Value::String(serde_json::to_string(protocol_message)?),
30            signed_entity_type
31                .get_open_message_timeout()
32                .map(|t| Value::String((Utc::now() + t).to_rfc3339()))
33                .unwrap_or(Value::Null),
34            Value::String(Utc::now().to_rfc3339()),
35        ];
36
37        Ok(Self {
38            condition: WhereCondition::new(expression, parameters),
39        })
40    }
41}
42
43impl Query for InsertOpenMessageQuery {
44    type Entity = OpenMessageRecord;
45
46    fn filters(&self) -> WhereCondition {
47        self.condition.clone()
48    }
49
50    fn get_definition(&self, condition: &str) -> String {
51        let aliases = SourceAlias::new(&[("{:open_message:}", "open_message")]);
52        let projection = Self::Entity::get_projection().expand(aliases);
53
54        format!("insert into open_message {condition} returning {projection}")
55    }
56}