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 #[cfg_attr(
65 all(debug_assertions, feature = "profiling"),
66 tracing::instrument(skip(conn, db_uuid, name, path))
67 )]
68 pub fn create(
69 conn: &OperationsConnection,
70 db_uuid: &str,
71 name: &str,
72 path: &str,
73 ) -> Result<GenDatabase, GenDatabaseError> {
74 let query = "INSERT INTO gen_databases (db_uuid, name, path) VALUES (?1, ?2, ?3);";
75 let mut stmt = match conn.prepare(query) {
76 Ok(s) => s,
77 Err(e) => return Err(GenDatabaseError::DatabaseError(e)),
78 };
79 match stmt.execute(params![db_uuid, name, path]) {
80 Ok(_) => Ok(GenDatabase {
81 db_uuid: db_uuid.to_string(),
82 name: name.to_string(),
83 path: path.to_string(),
84 }),
85 Err(rusqlite::Error::SqliteFailure(e, _))
86 if e.code == rusqlite::ErrorCode::ConstraintViolation =>
87 {
88 Err(GenDatabaseError::Duplicate(db_uuid.to_string()))
89 }
90 Err(e) => Err(GenDatabaseError::DatabaseError(e)),
91 }
92 }
93
94 pub fn delete_by_uuid(conn: &OperationsConnection, db_uuid: &str) -> SQLResult<GenDatabase> {
95 GenDatabase::get(
96 conn,
97 "DELETE FROM gen_databases WHERE db_uuid = ?1",
98 params![db_uuid],
99 )
100 }
101
102 #[cfg_attr(
103 all(debug_assertions, feature = "profiling"),
104 tracing::instrument(skip(conn, db_uuid))
105 )]
106 pub fn get_by_uuid(conn: &OperationsConnection, db_uuid: &str) -> SQLResult<GenDatabase> {
107 GenDatabase::get(
108 conn,
109 "SELECT * FROM gen_databases WHERE db_uuid = ?1",
110 params![db_uuid],
111 )
112 }
113
114 #[cfg_attr(
115 all(debug_assertions, feature = "profiling"),
116 tracing::instrument(skip(conn, path))
117 )]
118 pub fn get_by_path(conn: &OperationsConnection, path: &str) -> SQLResult<GenDatabase> {
119 GenDatabase::get(
120 conn,
121 "SELECT * FROM gen_databases WHERE path = ?1",
122 params![path],
123 )
124 }
125
126 #[cfg_attr(
127 all(debug_assertions, feature = "profiling"),
128 tracing::instrument(skip(conn, db_uuid, name, path))
129 )]
130 pub fn get_or_create(
131 conn: &OperationsConnection,
132 db_uuid: &str,
133 name: &str,
134 path: &str,
135 ) -> Result<GenDatabase, GenDatabaseError> {
136 match GenDatabase::create(conn, db_uuid, name, path) {
137 Ok(new) => Ok(new),
138 Err(GenDatabaseError::Duplicate(_)) => {
139 match GenDatabase::get(
140 conn,
141 "select * from gen_databases where db_uuid = ?1 AND name = ?2 AND path = ?3",
142 params![db_uuid, name, path],
143 ) {
144 Ok(result) => Ok(result),
145 Err(e) => Err(GenDatabaseError::DatabaseError(e)),
146 }
147 }
148 Err(e) => Err(e),
149 }
150 }
151
152 pub fn query_by_operations(
153 conn: &OperationsConnection,
154 operations: &[HashId],
155 ) -> Result<HashMap<HashId, Vec<GenDatabase>>, GenDatabaseError> {
156 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)";
157 let mut stmt = conn.prepare(query).unwrap();
158 let rows = stmt
159 .query_map(
160 params![Rc::new(
161 operations
162 .iter()
163 .map(|h| Value::from(*h))
164 .collect::<Vec<Value>>()
165 )],
166 |row| Ok((GenDatabase::process_row(row), row.get::<_, HashId>(3)?)),
167 )
168 .unwrap();
169 rows.into_iter()
170 .try_fold(HashMap::new(), |mut acc: HashMap<_, Vec<_>>, row| {
171 let (item, hash) = row?;
172 acc.entry(hash).or_default().push(item);
173 Ok(acc)
174 })
175 }
176}
177
178#[cfg(test)]
179mod tests {
180 use capnp::message::TypedBuilder;
181
182 use super::*;
183 use crate::test_helpers::get_operation_connection;
184
185 #[test]
186 fn test_gen_database_capnp_serialization() {
187 let gen_database = GenDatabase {
188 db_uuid: "test-uuid-123".to_string(),
189 name: "test_database".to_string(),
190 path: "/path/to/test.db".to_string(),
191 };
192
193 let mut message = TypedBuilder::<gen_database::Owned>::new_default();
194 let mut root = message.init_root();
195 gen_database.write_capnp(&mut root);
196
197 let deserialized = GenDatabase::read_capnp(root.into_reader());
198 assert_eq!(gen_database, deserialized);
199 }
200
201 #[test]
202 fn test_create_gen_database() {
203 let conn = get_operation_connection(None).unwrap();
204
205 let db = GenDatabase::create(&conn, "test-uuid-123", "test_db", "path/to/db.db").unwrap();
206
207 assert_eq!(db.db_uuid, "test-uuid-123");
208 assert_eq!(db.name, "test_db");
209 assert_eq!(db.path, "path/to/db.db");
210 }
211
212 #[test]
213 fn test_get_by_uuid() {
214 let conn = get_operation_connection(None).unwrap();
215
216 let created_db =
217 GenDatabase::create(&conn, "test-uuid-456", "test_db2", "path/to/db2.db").unwrap();
218
219 let retrieved_db = GenDatabase::get_by_uuid(&conn, &created_db.db_uuid).unwrap();
220
221 assert_eq!(retrieved_db, created_db);
222 }
223
224 #[test]
225 fn test_get_by_path() {
226 let conn = get_operation_connection(None).unwrap();
227
228 let created_db =
229 GenDatabase::create(&conn, "test-uuid-789", "test_db3", "path/to/db3.db").unwrap();
230
231 let retrieved_db = GenDatabase::get_by_path(&conn, "path/to/db3.db").unwrap();
232
233 assert_eq!(retrieved_db, created_db);
234 }
235
236 #[test]
237 fn test_get_or_create_existing() {
238 let conn = get_operation_connection(None).unwrap();
239
240 let created_db = GenDatabase::create(
241 &conn,
242 "test-uuid-existing",
243 "existing_db",
244 "path/to/existing.db",
245 )
246 .unwrap();
247
248 let retrieved_db = GenDatabase::get_or_create(
250 &conn,
251 "test-uuid-existing",
252 "existing_db",
253 "path/to/existing.db",
254 )
255 .unwrap();
256
257 assert_eq!(retrieved_db, created_db); }
259
260 #[test]
261 fn test_get_or_create_conflict() {
262 let conn = get_operation_connection(None).unwrap();
263
264 let _ = GenDatabase::create(
266 &conn,
267 "test-uuid-existing",
268 "existing_db",
269 "path/to/existing.db",
270 )
271 .unwrap();
272
273 let retrieved_db = GenDatabase::get_or_create(
275 &conn,
276 "test-uuid-existing",
277 "something_else",
278 "path/to/something_else.db",
279 );
280 assert!(retrieved_db.is_err())
281 }
282
283 #[test]
284 fn test_get_or_create_new() {
285 let conn = get_operation_connection(None).unwrap();
286
287 let new_db =
289 GenDatabase::get_or_create(&conn, "test-uuid-new", "new_db", "path/to/new.db").unwrap();
290
291 assert_eq!(new_db.db_uuid, "test-uuid-new");
292 assert_eq!(new_db.name, "new_db");
293 assert_eq!(new_db.path, "path/to/new.db");
294 }
295
296 #[test]
297 fn test_get_by_uuid_not_found() {
298 let conn = get_operation_connection(None).unwrap();
299
300 let result = GenDatabase::get_by_uuid(&conn, "non-existing-uuid");
301
302 assert!(result.is_err());
303 }
304
305 #[test]
306 fn test_get_by_path_not_found() {
307 let conn = get_operation_connection(None).unwrap();
308
309 let result = GenDatabase::get_by_path(&conn, "non/existing/path.db");
310
311 assert!(result.is_err());
312 }
313}