mithril_aggregator/database/query/signed_entity/
insert_signed_entity.rs

1use sqlite::Value;
2
3use mithril_persistence::sqlite::{Query, SourceAlias, SqLiteEntity, WhereCondition};
4
5use crate::database::record::SignedEntityRecord;
6
7/// Query to insert [SignedEntityRecord] in the sqlite database
8pub struct InsertSignedEntityRecordQuery {
9    condition: WhereCondition,
10}
11
12impl InsertSignedEntityRecordQuery {
13    pub fn one(signed_entity_record: SignedEntityRecord) -> Self {
14        Self {
15            condition: WhereCondition::new(
16                "(signed_entity_id, signed_entity_type_id, certificate_id, beacon, artifact, created_at) values (?*, ?*, ?*, ?*, ?*, ?*)",
17                vec![
18                    Value::String(signed_entity_record.signed_entity_id),
19                    Value::Integer(signed_entity_record.signed_entity_type.index() as i64),
20                    Value::String(signed_entity_record.certificate_id),
21                    Value::String(
22                        signed_entity_record.signed_entity_type.get_json_beacon().unwrap(),
23                    ),
24                    Value::String(signed_entity_record.artifact),
25                    Value::String(signed_entity_record.created_at.to_rfc3339()),
26                ],
27            ),
28        }
29    }
30}
31
32impl Query for InsertSignedEntityRecordQuery {
33    type Entity = SignedEntityRecord;
34
35    fn filters(&self) -> WhereCondition {
36        self.condition.clone()
37    }
38
39    fn get_definition(&self, condition: &str) -> String {
40        // it is important to alias the fields with the same name as the table
41        // since the table cannot be aliased in a RETURNING statement in SQLite.
42        let projection = Self::Entity::get_projection()
43            .expand(SourceAlias::new(&[("{:signed_entity:}", "signed_entity")]));
44
45        format!("insert into signed_entity {condition} returning {projection}")
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use mithril_persistence::sqlite::ConnectionExtensions;
52
53    use crate::database::test_helper::main_db_connection;
54
55    use super::*;
56
57    #[test]
58    fn test_insert_signed_entity_record() {
59        let signed_entity_records = SignedEntityRecord::fake_records(5);
60
61        let connection = main_db_connection().unwrap();
62
63        for signed_entity_record in signed_entity_records {
64            let signed_entity_record_saved = connection
65                .fetch_first(InsertSignedEntityRecordQuery::one(
66                    signed_entity_record.clone(),
67                ))
68                .unwrap();
69            assert_eq!(Some(signed_entity_record), signed_entity_record_saved);
70        }
71    }
72}