Skip to main content

gen_models/
collection.rs

1use gen_core::traits::Capnp;
2use rusqlite::{Row, params_from_iter};
3use serde::{Deserialize, Serialize};
4use thiserror::Error;
5
6use crate::{
7    block_group::BlockGroup, db::GraphConnection, gen_models_capnp::collection, traits::*,
8};
9
10#[derive(Debug, Error, PartialEq)]
11pub enum CollectionError {
12    #[error("Database error: {0}")]
13    DatabaseError(#[from] rusqlite::Error),
14    #[error("Collection already exists")]
15    Duplicate(Collection),
16}
17
18#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
19pub struct Collection {
20    pub name: String,
21}
22
23impl<'a> Capnp<'a> for Collection {
24    type Builder = collection::Builder<'a>;
25    type Reader = collection::Reader<'a>;
26
27    fn write_capnp(&self, builder: &mut Self::Builder) {
28        builder.set_name(self.name.clone());
29    }
30
31    fn read_capnp(reader: Self::Reader) -> Self {
32        let name = reader.get_name().unwrap().to_string().unwrap();
33
34        Collection { name }
35    }
36}
37
38impl Query for Collection {
39    type Model = Collection;
40
41    const PRIMARY_KEY: &'static str = "name";
42    const TABLE_NAME: &'static str = "collections";
43
44    fn process_row(row: &Row) -> Self::Model {
45        Collection {
46            name: row.get(0).unwrap(),
47        }
48    }
49}
50
51impl Collection {
52    pub fn exists(conn: &GraphConnection, name: &str) -> bool {
53        let mut stmt = conn
54            .prepare("select name from collections where name = ?1")
55            .unwrap();
56        stmt.exists([name]).unwrap()
57    }
58
59    #[cfg_attr(
60        all(debug_assertions, feature = "profiling"),
61        tracing::instrument(skip(conn, name))
62    )]
63    pub fn create(conn: &GraphConnection, name: &str) -> Result<Collection, CollectionError> {
64        let mut stmt = match conn.prepare("INSERT INTO collections (name) VALUES (?1) RETURNING *;")
65        {
66            Ok(stmt) => stmt,
67            Err(e) => return Err(CollectionError::DatabaseError(e)),
68        };
69
70        match stmt.query_row((name,), |_row| {
71            Ok(Collection {
72                name: name.to_string(),
73            })
74        }) {
75            Ok(res) => Ok(res),
76            Err(rusqlite::Error::SqliteFailure(e, _))
77                if e.code == rusqlite::ErrorCode::ConstraintViolation =>
78            {
79                Err(CollectionError::Duplicate(Collection {
80                    name: name.to_string(),
81                }))
82            }
83            Err(e) => Err(CollectionError::DatabaseError(e)),
84        }
85    }
86
87    pub fn get_or_create(
88        conn: &GraphConnection,
89        name: &str,
90    ) -> Result<Collection, CollectionError> {
91        match Collection::create(conn, name) {
92            Ok(collection) => Ok(collection),
93            Err(CollectionError::Duplicate(_)) => {
94                let collections =
95                    Self::query(conn, "SELECT * FROM collections WHERE name = ?1", [name]);
96                if let Some(collection) = collections.into_iter().next() {
97                    Ok(collection)
98                } else {
99                    Err(CollectionError::DatabaseError(
100                        rusqlite::Error::QueryReturnedNoRows,
101                    ))
102                }
103            }
104            Err(e) => Err(e),
105        }
106    }
107
108    pub fn bulk_create(conn: &GraphConnection, names: &Vec<String>) -> Vec<Collection> {
109        let placeholders = names.iter().map(|_| "(?)").collect::<Vec<_>>().join(", ");
110        let q = format!("INSERT INTO collections (name) VALUES {placeholders} RETURNING *",);
111        let mut stmt = conn.prepare(&q).unwrap();
112        let rows = stmt
113            .query_map(params_from_iter(names), |row| {
114                Ok(Collection { name: row.get(0)? })
115            })
116            .unwrap();
117        rows.map(|row| row.unwrap()).collect()
118    }
119
120    pub fn get_block_groups(conn: &GraphConnection, collection_name: &str) -> Vec<BlockGroup> {
121        // Load all block groups that have the given collection_name
122        let mut stmt = conn
123            .prepare("SELECT * FROM block_groups WHERE collection_name = ?1 order by created_on;")
124            .unwrap();
125        let block_group_iter = stmt
126            .query_map([collection_name], |row| Ok(BlockGroup::process_row(row)))
127            .unwrap();
128        block_group_iter.map(|bg| bg.unwrap()).collect()
129    }
130
131    pub fn delete_by_name(conn: &GraphConnection, name: &str) {
132        let mut stmt = conn
133            .prepare("delete from collections where name = ?1")
134            .unwrap();
135        stmt.execute([name]).unwrap();
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use capnp::message::TypedBuilder;
142
143    use super::*;
144    use crate::test_helpers::get_connection;
145
146    #[test]
147    pub fn test_serialization() {
148        let c = Collection {
149            name: "test".to_string(),
150        };
151        let mut message = TypedBuilder::<collection::Owned>::new_default();
152        let mut root = message.init_root();
153        c.write_capnp(&mut root);
154
155        let d = Collection::read_capnp(root.into_reader());
156        assert_eq!(c, d);
157    }
158
159    #[test]
160    pub fn test_delete_by_name() {
161        let conn = &get_connection(None).unwrap();
162        let collection1 = Collection::create(conn, "test1").unwrap();
163        let collection2 = Collection::create(conn, "test2").unwrap();
164
165        Collection::delete_by_name(conn, &collection1.name);
166
167        // Verify only the correct one was deleted
168        assert!(!Collection::exists(conn, &collection1.name));
169        assert!(Collection::exists(conn, &collection2.name));
170    }
171}