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 pub fn create(conn: &GraphConnection, name: &str) -> Result<Collection, CollectionError> {
60 let mut stmt = match conn.prepare("INSERT INTO collections (name) VALUES (?1) RETURNING *;")
61 {
62 Ok(stmt) => stmt,
63 Err(e) => return Err(CollectionError::DatabaseError(e)),
64 };
65
66 match stmt.query_row((name,), |_row| {
67 Ok(Collection {
68 name: name.to_string(),
69 })
70 }) {
71 Ok(res) => Ok(res),
72 Err(rusqlite::Error::SqliteFailure(e, _))
73 if e.code == rusqlite::ErrorCode::ConstraintViolation =>
74 {
75 Err(CollectionError::Duplicate(Collection {
76 name: name.to_string(),
77 }))
78 }
79 Err(e) => Err(CollectionError::DatabaseError(e)),
80 }
81 }
82
83 pub fn get_or_create(
84 conn: &GraphConnection,
85 name: &str,
86 ) -> Result<Collection, CollectionError> {
87 match Collection::create(conn, name) {
88 Ok(collection) => Ok(collection),
89 Err(CollectionError::Duplicate(_)) => {
90 let collections =
91 Self::query(conn, "SELECT * FROM collections WHERE name = ?1", [name]);
92 if let Some(collection) = collections.into_iter().next() {
93 Ok(collection)
94 } else {
95 Err(CollectionError::DatabaseError(
96 rusqlite::Error::QueryReturnedNoRows,
97 ))
98 }
99 }
100 Err(e) => Err(e),
101 }
102 }
103
104 pub fn bulk_create(conn: &GraphConnection, names: &Vec<String>) -> Vec<Collection> {
105 let placeholders = names.iter().map(|_| "(?)").collect::<Vec<_>>().join(", ");
106 let q = format!("INSERT INTO collections (name) VALUES {placeholders} RETURNING *",);
107 let mut stmt = conn.prepare(&q).unwrap();
108 let rows = stmt
109 .query_map(params_from_iter(names), |row| {
110 Ok(Collection { name: row.get(0)? })
111 })
112 .unwrap();
113 rows.map(|row| row.unwrap()).collect()
114 }
115
116 pub fn get_block_groups(conn: &GraphConnection, collection_name: &str) -> Vec<BlockGroup> {
117 let mut stmt = conn
119 .prepare("SELECT * FROM block_groups WHERE collection_name = ?1 order by created_on;")
120 .unwrap();
121 let block_group_iter = stmt
122 .query_map([collection_name], |row| Ok(BlockGroup::process_row(row)))
123 .unwrap();
124 block_group_iter.map(|bg| bg.unwrap()).collect()
125 }
126
127 pub fn delete_by_name(conn: &GraphConnection, name: &str) {
128 let mut stmt = conn
129 .prepare("delete from collections where name = ?1")
130 .unwrap();
131 stmt.execute([name]).unwrap();
132 }
133}
134
135#[cfg(test)]
136mod tests {
137 use capnp::message::TypedBuilder;
138
139 use super::*;
140 use crate::test_helpers::get_connection;
141
142 #[test]
143 pub fn test_serialization() {
144 let c = Collection {
145 name: "test".to_string(),
146 };
147 let mut message = TypedBuilder::<collection::Owned>::new_default();
148 let mut root = message.init_root();
149 c.write_capnp(&mut root);
150
151 let d = Collection::read_capnp(root.into_reader());
152 assert_eq!(c, d);
153 }
154
155 #[test]
156 pub fn test_delete_by_name() {
157 let conn = &get_connection(None).unwrap();
158 let collection1 = Collection::create(conn, "test1").unwrap();
159 let collection2 = Collection::create(conn, "test2").unwrap();
160
161 Collection::delete_by_name(conn, &collection1.name);
162
163 assert!(!Collection::exists(conn, &collection1.name));
165 assert!(Collection::exists(conn, &collection2.name));
166 }
167}