mithril_signer/database/query/protocol_initializer/
insert_protocol_initializer.rs

1use sqlite::Value;
2
3use mithril_common::StdResult;
4use mithril_persistence::sqlite::{Query, SourceAlias, SqLiteEntity, WhereCondition};
5
6use crate::database::record::ProtocolInitializerRecord;
7
8/// Query to insert or replace [ProtocolInitializerRecord] in the sqlite database
9pub struct InsertOrReplaceProtocolInitializerQuery {
10    condition: WhereCondition,
11}
12
13impl InsertOrReplaceProtocolInitializerQuery {
14    pub fn one(record: ProtocolInitializerRecord) -> StdResult<Self> {
15        let value = serde_json::to_string(&record.protocol_initializer).unwrap();
16        let condition = WhereCondition::new(
17            "(epoch, protocol, created_at) values (?*, ?*, ?*)",
18            vec![
19                Value::Integer(record.epoch.try_into()?),
20                Value::String(value),
21                Value::String(record.created_at.to_rfc3339()),
22            ],
23        );
24
25        Ok(Self { condition })
26    }
27}
28
29impl Query for InsertOrReplaceProtocolInitializerQuery {
30    type Entity = ProtocolInitializerRecord;
31
32    fn filters(&self) -> WhereCondition {
33        self.condition.clone()
34    }
35
36    fn get_definition(&self, condition: &str) -> String {
37        // it is important to alias the fields with the same name as the table
38        // since the table cannot be aliased in a RETURNING statement in SQLite.
39        let projection = Self::Entity::get_projection().expand(SourceAlias::new(&[(
40            "{:protocol_initializer:}",
41            "protocol_initializer",
42        )]));
43
44        format!("insert or replace into protocol_initializer {condition} returning {projection}")
45    }
46}