Skip to main content

gen_models/
collection.rs

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