Skip to main content

gen_models/
path_edge.rs

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    #[cfg_attr(
90        all(debug_assertions, feature = "profiling"),
91        tracing::instrument(skip(conn, path_id, index_in_path, edge_id))
92    )]
93    pub fn create(
94        conn: &GraphConnection,
95        path_id: &HashId,
96        index_in_path: i64,
97        edge_id: HashId,
98    ) -> Result<PathEdge, PathEdgeError> {
99        let query =
100            "INSERT INTO path_edges (id, path_id, edge_id, index_in_path) VALUES (?1, ?2, ?3, ?4);";
101        let mut stmt = match conn.prepare(query) {
102            Ok(stmt) => stmt,
103            Err(e) => return Err(PathEdgeError::DatabaseError(e)),
104        };
105        let hash = HashId(calculate_hash(&format!(
106            "{path_id}:{edge_id}:{index_in_path}"
107        )));
108        match stmt.execute(params![hash, path_id, edge_id, index_in_path]) {
109            Ok(_) => Ok(PathEdge {
110                id: hash,
111                path_id: *path_id,
112                index_in_path,
113                edge_id,
114            }),
115            Err(rusqlite::Error::SqliteFailure(err, _details))
116                if err.code == rusqlite::ErrorCode::ConstraintViolation =>
117            {
118                Ok(PathEdge {
119                    id: hash,
120                    path_id: *path_id,
121                    index_in_path,
122                    edge_id,
123                })
124            }
125            Err(e) => Err(PathEdgeError::DatabaseError(e)),
126        }
127    }
128
129    #[cfg_attr(
130        all(debug_assertions, feature = "profiling"),
131        tracing::instrument(skip(conn, path_id, edge_ids))
132    )]
133    pub fn bulk_create(
134        conn: &GraphConnection,
135        path_id: &HashId,
136        edge_ids: &[HashId],
137    ) -> Result<(), PathEdgeError> {
138        let batch_size = max_rows_per_batch(conn, 4);
139
140        for (index1, chunk) in edge_ids.chunks(batch_size).enumerate() {
141            let mut rows_to_insert = vec![];
142            let mut params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
143            for (index2, edge_id) in chunk.iter().enumerate() {
144                rows_to_insert.push("(?, ?, ?, ?)".to_string());
145                let index_in = index1 * 100000 + index2;
146                let hash = HashId(calculate_hash(&format!("{path_id}:{edge_id}:{index_in}")));
147                params.push(Box::new(hash));
148                params.push(Box::new(path_id));
149                params.push(Box::new(edge_id));
150                params.push(Box::new(index_in));
151            }
152
153            let sql = format!(
154                "INSERT OR IGNORE INTO path_edges (id, path_id, edge_id, index_in_path) VALUES {};",
155                rows_to_insert.join(", ")
156            );
157
158            let mut stmt = match conn.prepare(&sql) {
159                Ok(stmt) => stmt,
160                Err(e) => return Err(PathEdgeError::DatabaseError(e)),
161            };
162            match stmt.execute(rusqlite::params_from_iter(params)) {
163                Ok(_) => (),
164                Err(e) => return Err(PathEdgeError::DatabaseError(e)),
165            }
166        }
167
168        Ok(())
169    }
170
171    pub fn delete(conn: &GraphConnection, path_id: &HashId) {
172        let statement = "DELETE from path_edges WHERE path_id = ?1;";
173        conn.execute(statement, params![path_id]).unwrap();
174    }
175
176    pub fn edges_for_path(conn: &GraphConnection, path_id: &HashId) -> Vec<Edge> {
177        let path_edges = PathEdge::query(
178            conn,
179            "select * from path_edges where path_id = ?1 order by index_in_path ASC",
180            params![path_id],
181        );
182        let edge_ids = path_edges
183            .into_iter()
184            .map(|path_edge| path_edge.edge_id)
185            .collect::<Vec<HashId>>();
186        let edges = Edge::query_by_ids(conn, &edge_ids);
187        let edges_by_id = edges
188            .into_iter()
189            .map(|edge| (edge.id, edge))
190            .collect::<HashMap<HashId, Edge>>();
191        edge_ids
192            .into_iter()
193            .map(|edge_id| edges_by_id[&edge_id].clone())
194            .collect::<Vec<Edge>>()
195    }
196
197    pub fn edges_for_paths(
198        conn: &GraphConnection,
199        path_ids: Vec<HashId>,
200    ) -> HashMap<HashId, Vec<Edge>> {
201        let query_path_ids = path_ids
202            .iter()
203            .map(|path_id| Value::from(*path_id))
204            .collect::<Vec<Value>>();
205        let path_edges = PathEdge::query(
206            conn,
207            "select * from path_edges where path_id in rarray(?1) ORDER BY path_id, index_in_path",
208            params![Rc::new(query_path_ids)],
209        );
210        let edge_ids = path_edges
211            .iter()
212            .map(|path_edge| path_edge.edge_id)
213            .collect::<Vec<_>>();
214        let edges = Edge::query_by_ids(conn, &edge_ids);
215        let edges_by_id = edges
216            .into_iter()
217            .map(|edge| (edge.id, edge))
218            .collect::<HashMap<_, Edge>>();
219        let path_edges_by_path_id = path_edges
220            .iter()
221            .map(|path_edge| (path_edge.path_id, path_edge.edge_id))
222            .into_group_map();
223        path_edges_by_path_id
224            .into_iter()
225            .map(|(path_id, edge_ids)| {
226                (
227                    path_id,
228                    edge_ids
229                        .into_iter()
230                        .map(|edge_id| edges_by_id[&edge_id].clone())
231                        .collect::<Vec<Edge>>(),
232                )
233            })
234            .collect::<HashMap<HashId, Vec<Edge>>>()
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use capnp::message::TypedBuilder;
241
242    use super::*;
243    use crate::gen_models_capnp::path_edge;
244
245    #[test]
246    fn test_path_edge_capnp_serialization() {
247        let path_edge = PathEdge {
248            id: HashId::pad_str(100),
249            path_id: HashId::pad_str(200),
250            index_in_path: 5,
251            edge_id: HashId::pad_str(300),
252        };
253
254        let mut message = TypedBuilder::<path_edge::Owned>::new_default();
255        let mut root = message.init_root();
256        path_edge.write_capnp(&mut root);
257
258        let deserialized = PathEdge::read_capnp(root.into_reader());
259        assert_eq!(path_edge, deserialized);
260    }
261}