1use std::{collections::HashMap, rc::Rc};
2
3use gen_core::{HashId, traits::Capnp};
4use rusqlite::{Result as SQLResult, Row, params, types::Value};
5use serde::{Deserialize, Serialize};
6use thiserror::Error;
7
8use crate::{db::OperationsConnection, gen_models_capnp::gen_database, traits::*};
9
10#[derive(Debug, Error)]
11pub enum GenDatabaseError {
12 #[error("Database error: {0}")]
13 DatabaseError(#[from] rusqlite::Error),
14 #[error("Duplicate entry with uuid: {0}")]
15 Duplicate(String),
16}
17
18#[derive(Clone, Debug, Eq, Hash, Serialize, Deserialize, PartialEq)]
19pub struct GenDatabase {
20 pub db_uuid: String,
21 pub name: String,
22 pub path: String,
23}
24
25impl<'a> Capnp<'a> for GenDatabase {
26 type Builder = gen_database::Builder<'a>;
27 type Reader = gen_database::Reader<'a>;
28
29 fn write_capnp(&self, builder: &mut Self::Builder) {
30 builder.set_db_uuid(&self.db_uuid);
31 builder.set_name(&self.name);
32 builder.set_path(&self.path);
33 }
34
35 fn read_capnp(reader: Self::Reader) -> Self {
36 let db_uuid = reader.get_db_uuid().unwrap().to_string().unwrap();
37 let name = reader.get_name().unwrap().to_string().unwrap();
38 let path = reader.get_path().unwrap().to_string().unwrap();
39
40 GenDatabase {
41 db_uuid,
42 name,
43 path,
44 }
45 }
46}
47
48impl Query for GenDatabase {
49 type Model = GenDatabase;
50
51 const PRIMARY_KEY: &'static str = "db_uuid";
52 const TABLE_NAME: &'static str = "gen_databases";
53
54 fn process_row(row: &Row) -> Self::Model {
55 GenDatabase {
56 db_uuid: row.get(0).unwrap(),
57 name: row.get(1).unwrap(),
58 path: row.get(2).unwrap(),
59 }
60 }
61}
62
63impl GenDatabase {
64 pub fn create(
65 conn: &OperationsConnection,
66 db_uuid: &str,
67 name: &str,
68 path: &str,
69 ) -> Result<GenDatabase, GenDatabaseError> {
70 let query = "INSERT INTO gen_databases (db_uuid, name, path) VALUES (?1, ?2, ?3);";
71 let mut stmt = match conn.prepare(query) {
72 Ok(s) => s,
73 Err(e) => return Err(GenDatabaseError::DatabaseError(e)),
74 };
75 match stmt.execute(params![db_uuid, name, path]) {
76 Ok(_) => Ok(GenDatabase {
77 db_uuid: db_uuid.to_string(),
78 name: name.to_string(),
79 path: path.to_string(),
80 }),
81 Err(rusqlite::Error::SqliteFailure(e, _))
82 if e.code == rusqlite::ErrorCode::ConstraintViolation =>
83 {
84 Err(GenDatabaseError::Duplicate(db_uuid.to_string()))
85 }
86 Err(e) => Err(GenDatabaseError::DatabaseError(e)),
87 }
88 }
89
90 pub fn delete_by_uuid(conn: &OperationsConnection, db_uuid: &str) -> SQLResult<GenDatabase> {
91 GenDatabase::get(
92 conn,
93 "DELETE FROM gen_databases WHERE db_uuid = ?1",
94 params![db_uuid],
95 )
96 }
97
98 pub fn get_by_uuid(conn: &OperationsConnection, db_uuid: &str) -> SQLResult<GenDatabase> {
99 GenDatabase::get(
100 conn,
101 "SELECT * FROM gen_databases WHERE db_uuid = ?1",
102 params![db_uuid],
103 )
104 }
105
106 pub fn get_by_path(conn: &OperationsConnection, path: &str) -> SQLResult<GenDatabase> {
107 GenDatabase::get(
108 conn,
109 "SELECT * FROM gen_databases WHERE path = ?1",
110 params![path],
111 )
112 }
113
114 pub fn get_or_create(
115 conn: &OperationsConnection,
116 db_uuid: &str,
117 name: &str,
118 path: &str,
119 ) -> Result<GenDatabase, GenDatabaseError> {
120 match GenDatabase::create(conn, db_uuid, name, path) {
121 Ok(new) => Ok(new),
122 Err(GenDatabaseError::Duplicate(_)) => {
123 match GenDatabase::get(
124 conn,
125 "select * from gen_databases where db_uuid = ?1 AND name = ?2 AND path = ?3",
126 params![db_uuid, name, path],
127 ) {
128 Ok(result) => Ok(result),
129 Err(e) => Err(GenDatabaseError::DatabaseError(e)),
130 }
131 }
132 Err(e) => Err(e),
133 }
134 }
135
136 pub fn query_by_operations(
137 conn: &OperationsConnection,
138 operations: &[HashId],
139 ) -> Result<HashMap<HashId, Vec<GenDatabase>>, GenDatabaseError> {
140 let query = "select gd.*, od.operation_hash from gen_databases gd left join operation_databases od on (gd.db_uuid = od.database_uuid) where od.operation_hash in rarray(?1)";
141 let mut stmt = conn.prepare(query).unwrap();
142 let rows = stmt
143 .query_map(
144 params![Rc::new(
145 operations
146 .iter()
147 .map(|h| Value::from(*h))
148 .collect::<Vec<Value>>()
149 )],
150 |row| Ok((GenDatabase::process_row(row), row.get::<_, HashId>(3)?)),
151 )
152 .unwrap();
153 rows.into_iter()
154 .try_fold(HashMap::new(), |mut acc: HashMap<_, Vec<_>>, row| {
155 let (item, hash) = row?;
156 acc.entry(hash).or_default().push(item);
157 Ok(acc)
158 })
159 }
160}
161
162#[cfg(test)]
163mod tests {
164 use capnp::message::TypedBuilder;
165
166 use super::*;
167 use crate::test_helpers::get_operation_connection;
168
169 #[test]
170 fn test_gen_database_capnp_serialization() {
171 let gen_database = GenDatabase {
172 db_uuid: "test-uuid-123".to_string(),
173 name: "test_database".to_string(),
174 path: "/path/to/test.db".to_string(),
175 };
176
177 let mut message = TypedBuilder::<gen_database::Owned>::new_default();
178 let mut root = message.init_root();
179 gen_database.write_capnp(&mut root);
180
181 let deserialized = GenDatabase::read_capnp(root.into_reader());
182 assert_eq!(gen_database, deserialized);
183 }
184
185 #[test]
186 fn test_create_gen_database() {
187 let conn = get_operation_connection(None).unwrap();
188
189 let db = GenDatabase::create(&conn, "test-uuid-123", "test_db", "path/to/db.db").unwrap();
190
191 assert_eq!(db.db_uuid, "test-uuid-123");
192 assert_eq!(db.name, "test_db");
193 assert_eq!(db.path, "path/to/db.db");
194 }
195
196 #[test]
197 fn test_get_by_uuid() {
198 let conn = get_operation_connection(None).unwrap();
199
200 let created_db =
201 GenDatabase::create(&conn, "test-uuid-456", "test_db2", "path/to/db2.db").unwrap();
202
203 let retrieved_db = GenDatabase::get_by_uuid(&conn, &created_db.db_uuid).unwrap();
204
205 assert_eq!(retrieved_db, created_db);
206 }
207
208 #[test]
209 fn test_get_by_path() {
210 let conn = get_operation_connection(None).unwrap();
211
212 let created_db =
213 GenDatabase::create(&conn, "test-uuid-789", "test_db3", "path/to/db3.db").unwrap();
214
215 let retrieved_db = GenDatabase::get_by_path(&conn, "path/to/db3.db").unwrap();
216
217 assert_eq!(retrieved_db, created_db);
218 }
219
220 #[test]
221 fn test_get_or_create_existing() {
222 let conn = get_operation_connection(None).unwrap();
223
224 let created_db = GenDatabase::create(
225 &conn,
226 "test-uuid-existing",
227 "existing_db",
228 "path/to/existing.db",
229 )
230 .unwrap();
231
232 let retrieved_db = GenDatabase::get_or_create(
234 &conn,
235 "test-uuid-existing",
236 "existing_db",
237 "path/to/existing.db",
238 )
239 .unwrap();
240
241 assert_eq!(retrieved_db, created_db); }
243
244 #[test]
245 fn test_get_or_create_conflict() {
246 let conn = get_operation_connection(None).unwrap();
247
248 let _ = GenDatabase::create(
250 &conn,
251 "test-uuid-existing",
252 "existing_db",
253 "path/to/existing.db",
254 )
255 .unwrap();
256
257 let retrieved_db = GenDatabase::get_or_create(
259 &conn,
260 "test-uuid-existing",
261 "something_else",
262 "path/to/something_else.db",
263 );
264 assert!(retrieved_db.is_err())
265 }
266
267 #[test]
268 fn test_get_or_create_new() {
269 let conn = get_operation_connection(None).unwrap();
270
271 let new_db =
273 GenDatabase::get_or_create(&conn, "test-uuid-new", "new_db", "path/to/new.db").unwrap();
274
275 assert_eq!(new_db.db_uuid, "test-uuid-new");
276 assert_eq!(new_db.name, "new_db");
277 assert_eq!(new_db.path, "path/to/new.db");
278 }
279
280 #[test]
281 fn test_get_by_uuid_not_found() {
282 let conn = get_operation_connection(None).unwrap();
283
284 let result = GenDatabase::get_by_uuid(&conn, "non-existing-uuid");
285
286 assert!(result.is_err());
287 }
288
289 #[test]
290 fn test_get_by_path_not_found() {
291 let conn = get_operation_connection(None).unwrap();
292
293 let result = GenDatabase::get_by_path(&conn, "non/existing/path.db");
294
295 assert!(result.is_err());
296 }
297}