1use std::{collections::HashMap, rc::Rc};
2
3use gen_core::{HashId, calculate_hash, traits::Capnp};
4use itertools::Itertools;
5use rusqlite::{self, Row, params, types::Value};
6use serde::{Deserialize, Serialize};
7use thiserror::Error;
8
9use crate::{
10 db::GraphConnection, edge::Edge, gen_models_capnp::path_edge as PathEdgeCapnp, traits::*,
11};
12
13#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
14pub struct PathEdge {
15 pub id: HashId,
16 pub path_id: HashId,
17 pub edge_id: HashId,
18 pub index_in_path: i64,
19}
20
21#[derive(Debug, Error, PartialEq)]
22pub enum PathEdgeError {
23 #[error("Database error: {0}")]
24 DatabaseError(#[from] rusqlite::Error),
25 #[error("Duplicate entry with uuid: {0}")]
26 Duplicate(String),
27}
28
29impl<'a> Capnp<'a> for PathEdge {
30 type Builder = PathEdgeCapnp::Builder<'a>;
31 type Reader = PathEdgeCapnp::Reader<'a>;
32
33 fn write_capnp(&self, builder: &mut Self::Builder) {
34 builder.set_id(&self.id.0).unwrap();
35 builder.set_path_id(&self.path_id.0).unwrap();
36 builder.set_index_in_path(self.index_in_path);
37 builder.set_edge_id(&self.edge_id.0).unwrap();
38 }
39
40 fn read_capnp(reader: Self::Reader) -> Self {
41 let id = reader
42 .get_id()
43 .unwrap()
44 .as_slice()
45 .unwrap()
46 .try_into()
47 .unwrap();
48 let path_id = reader
49 .get_path_id()
50 .unwrap()
51 .as_slice()
52 .unwrap()
53 .try_into()
54 .unwrap();
55 let index_in_path = reader.get_index_in_path();
56 let edge_id = reader
57 .get_edge_id()
58 .unwrap()
59 .as_slice()
60 .unwrap()
61 .try_into()
62 .unwrap();
63
64 PathEdge {
65 id,
66 path_id,
67 index_in_path,
68 edge_id,
69 }
70 }
71}
72
73impl Query for PathEdge {
74 type Model = PathEdge;
75
76 const TABLE_NAME: &'static str = "path_edges";
77
78 fn process_row(row: &Row) -> Self::Model {
79 PathEdge {
80 id: row.get(0).unwrap(),
81 path_id: row.get(1).unwrap(),
82 edge_id: row.get(2).unwrap(),
83 index_in_path: row.get(3).unwrap(),
84 }
85 }
86}
87
88impl PathEdge {
89 pub fn create(
90 conn: &GraphConnection,
91 path_id: &HashId,
92 index_in_path: i64,
93 edge_id: HashId,
94 ) -> Result<PathEdge, PathEdgeError> {
95 let query =
96 "INSERT INTO path_edges (id, path_id, edge_id, index_in_path) VALUES (?1, ?2, ?3, ?4);";
97 let mut stmt = match conn.prepare(query) {
98 Ok(stmt) => stmt,
99 Err(e) => return Err(PathEdgeError::DatabaseError(e)),
100 };
101 let hash = HashId(calculate_hash(&format!(
102 "{path_id}:{edge_id}:{index_in_path}"
103 )));
104 match stmt.execute(params![hash, path_id, edge_id, index_in_path]) {
105 Ok(_) => Ok(PathEdge {
106 id: hash,
107 path_id: *path_id,
108 index_in_path,
109 edge_id,
110 }),
111 Err(rusqlite::Error::SqliteFailure(err, _details))
112 if err.code == rusqlite::ErrorCode::ConstraintViolation =>
113 {
114 Ok(PathEdge {
115 id: hash,
116 path_id: *path_id,
117 index_in_path,
118 edge_id,
119 })
120 }
121 Err(e) => Err(PathEdgeError::DatabaseError(e)),
122 }
123 }
124
125 pub fn bulk_create(
126 conn: &GraphConnection,
127 path_id: &HashId,
128 edge_ids: &[HashId],
129 ) -> Result<(), PathEdgeError> {
130 let batch_size = max_rows_per_batch(conn, 4);
131
132 for (index1, chunk) in edge_ids.chunks(batch_size).enumerate() {
133 let mut rows_to_insert = vec![];
134 let mut params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
135 for (index2, edge_id) in chunk.iter().enumerate() {
136 rows_to_insert.push("(?, ?, ?, ?)".to_string());
137 let index_in = index1 * 100000 + index2;
138 let hash = HashId(calculate_hash(&format!("{path_id}:{edge_id}:{index_in}")));
139 params.push(Box::new(hash));
140 params.push(Box::new(path_id));
141 params.push(Box::new(edge_id));
142 params.push(Box::new(index_in));
143 }
144
145 let sql = format!(
146 "INSERT OR IGNORE INTO path_edges (id, path_id, edge_id, index_in_path) VALUES {};",
147 rows_to_insert.join(", ")
148 );
149
150 let mut stmt = match conn.prepare(&sql) {
151 Ok(stmt) => stmt,
152 Err(e) => return Err(PathEdgeError::DatabaseError(e)),
153 };
154 match stmt.execute(rusqlite::params_from_iter(params)) {
155 Ok(_) => (),
156 Err(e) => return Err(PathEdgeError::DatabaseError(e)),
157 }
158 }
159
160 Ok(())
161 }
162
163 pub fn delete(conn: &GraphConnection, path_id: &HashId) {
164 let statement = "DELETE from path_edges WHERE path_id = ?1;";
165 conn.execute(statement, params![path_id]).unwrap();
166 }
167
168 pub fn edges_for_path(conn: &GraphConnection, path_id: &HashId) -> Vec<Edge> {
169 let path_edges = PathEdge::query(
170 conn,
171 "select * from path_edges where path_id = ?1 order by index_in_path ASC",
172 params![path_id],
173 );
174 let edge_ids = path_edges
175 .into_iter()
176 .map(|path_edge| path_edge.edge_id)
177 .collect::<Vec<HashId>>();
178 let edges = Edge::query_by_ids(conn, &edge_ids);
179 let edges_by_id = edges
180 .into_iter()
181 .map(|edge| (edge.id, edge))
182 .collect::<HashMap<HashId, Edge>>();
183 edge_ids
184 .into_iter()
185 .map(|edge_id| edges_by_id[&edge_id].clone())
186 .collect::<Vec<Edge>>()
187 }
188
189 pub fn edges_for_paths(
190 conn: &GraphConnection,
191 path_ids: Vec<HashId>,
192 ) -> HashMap<HashId, Vec<Edge>> {
193 let query_path_ids = path_ids
194 .iter()
195 .map(|path_id| Value::from(*path_id))
196 .collect::<Vec<Value>>();
197 let path_edges = PathEdge::query(
198 conn,
199 "select * from path_edges where path_id in rarray(?1) ORDER BY path_id, index_in_path",
200 params![Rc::new(query_path_ids)],
201 );
202 let edge_ids = path_edges
203 .iter()
204 .map(|path_edge| path_edge.edge_id)
205 .collect::<Vec<_>>();
206 let edges = Edge::query_by_ids(conn, &edge_ids);
207 let edges_by_id = edges
208 .into_iter()
209 .map(|edge| (edge.id, edge))
210 .collect::<HashMap<_, Edge>>();
211 let path_edges_by_path_id = path_edges
212 .iter()
213 .map(|path_edge| (path_edge.path_id, path_edge.edge_id))
214 .into_group_map();
215 path_edges_by_path_id
216 .into_iter()
217 .map(|(path_id, edge_ids)| {
218 (
219 path_id,
220 edge_ids
221 .into_iter()
222 .map(|edge_id| edges_by_id[&edge_id].clone())
223 .collect::<Vec<Edge>>(),
224 )
225 })
226 .collect::<HashMap<HashId, Vec<Edge>>>()
227 }
228}
229
230#[cfg(test)]
231mod tests {
232 use capnp::message::TypedBuilder;
233
234 use super::*;
235 use crate::gen_models_capnp::path_edge;
236
237 #[test]
238 fn test_path_edge_capnp_serialization() {
239 let path_edge = PathEdge {
240 id: HashId::pad_str(100),
241 path_id: HashId::pad_str(200),
242 index_in_path: 5,
243 edge_id: HashId::pad_str(300),
244 };
245
246 let mut message = TypedBuilder::<path_edge::Owned>::new_default();
247 let mut root = message.init_root();
248 path_edge.write_capnp(&mut root);
249
250 let deserialized = PathEdge::read_capnp(root.into_reader());
251 assert_eq!(path_edge, deserialized);
252 }
253}