1use std::str::FromStr;
2
3use gen_core::HashId;
4use rusqlite::{
5 Connection, params,
6 types::{FromSql, ToSql},
7};
8
9use crate::traits::Query;
10
11pub trait LineageId: Clone + Eq + FromSql + ToSql {
15 fn decode_hex_token(token: &str) -> Self;
16}
17
18fn decode_hex_bytes(token: &str) -> Vec<u8> {
19 assert_eq!(token.len() % 2, 0, "hex tokens must have an even length");
20
21 token
22 .as_bytes()
23 .chunks_exact(2)
24 .map(|pair| {
25 let pair = std::str::from_utf8(pair).expect("hex token must be valid ascii");
26 u8::from_str_radix(pair, 16).expect("hex token must be valid")
27 })
28 .collect()
29}
30
31impl LineageId for String {
32 fn decode_hex_token(token: &str) -> Self {
33 String::from_utf8(decode_hex_bytes(token)).expect("lineage token should decode to utf-8")
34 }
35}
36
37impl LineageId for HashId {
38 fn decode_hex_token(token: &str) -> Self {
39 let bytes = decode_hex_bytes(token);
40 HashId::try_from(bytes.as_slice()).expect("lineage token should decode to a hash id")
41 }
42}
43
44macro_rules! impl_numeric_lineage_id {
45 ($($ty:ty),* $(,)?) => {
46 $(
47 impl LineageId for $ty {
48 fn decode_hex_token(token: &str) -> Self {
49 let value =
50 String::from_utf8(decode_hex_bytes(token)).expect("lineage token should decode to utf-8");
51 <$ty>::from_str(&value).expect("lineage token should decode to a number")
52 }
53 }
54 )*
55 };
56}
57
58impl_numeric_lineage_id!(i32, i64, u32, u64, usize);
59
60pub trait SqlLineage: Query<Model = Self> + Sized {
61 type Id: LineageId;
62
63 const PARENT_TABLE_NAME: &'static str;
64 const PARENT_ID_COLUMN: &'static str;
65 const CHILD_TABLE_NAME: &'static str;
66 const CHILD_ID_COLUMN: &'static str;
67 const PARENT_COLUMN: &'static str;
68 const CHILD_COLUMN: &'static str;
69
70 fn parent_id(&self) -> &Self::Id;
71 fn child_id(&self) -> &Self::Id;
72
73 fn get_ancestors(
74 conn: &Connection,
75 child_id: &Self::Id,
76 max_depth: Option<usize>,
77 ) -> Vec<Self::Id> {
78 let max_depth = max_depth.map(|depth| depth as i64);
79 let query = format!(
80 "WITH RECURSIVE ancestors(id, depth, visited) AS (
81 SELECT
82 lineage.{parent_column},
83 1,
84 printf('|%s|', hex(lineage.{parent_column}))
85 FROM {table_name} lineage
86 WHERE lineage.{child_column} = ?1
87 UNION ALL
88 SELECT
89 lineage.{parent_column},
90 ancestors.depth + 1,
91 ancestors.visited || hex(lineage.{parent_column}) || '|'
92 FROM {table_name} lineage
93 JOIN ancestors ON lineage.{child_column} = ancestors.id
94 WHERE instr(
95 ancestors.visited,
96 printf('|%s|', hex(lineage.{parent_column}))
97 ) = 0
98 AND (?2 IS NULL OR ancestors.depth < ?2)
99 ),
100 ranked_ancestors(id, depth) AS (
101 SELECT id, MIN(depth)
102 FROM ancestors
103 GROUP BY id
104 )
105 SELECT parent.{parent_id_column}
106 FROM {parent_table_name} parent
107 JOIN ranked_ancestors ancestors ON parent.{parent_id_column} = ancestors.id
108 WHERE ?2 IS NULL OR ancestors.depth <= ?2
109 ORDER BY ancestors.depth, parent.{parent_id_column};",
110 table_name = Self::TABLE_NAME,
111 parent_column = Self::PARENT_COLUMN,
112 child_column = Self::CHILD_COLUMN,
113 parent_table_name = Self::PARENT_TABLE_NAME,
114 parent_id_column = Self::PARENT_ID_COLUMN,
115 );
116
117 let mut stmt = conn.prepare(&query).unwrap();
118 stmt.query_map(params![child_id, max_depth], |row| row.get(0))
119 .unwrap()
120 .map(|value| value.unwrap())
121 .collect()
122 }
123
124 fn get_descendants(
125 conn: &Connection,
126 parent_id: &Self::Id,
127 max_depth: Option<usize>,
128 ) -> Vec<Self::Id> {
129 let max_depth = max_depth.map(|depth| depth as i64);
130 let query = format!(
131 "WITH RECURSIVE descendants(id, depth, visited) AS (
132 SELECT
133 lineage.{child_column},
134 1,
135 printf('|%s|', hex(lineage.{child_column}))
136 FROM {table_name} lineage
137 WHERE lineage.{parent_column} = ?1
138 UNION ALL
139 SELECT
140 lineage.{child_column},
141 descendants.depth + 1,
142 descendants.visited || hex(lineage.{child_column}) || '|'
143 FROM {table_name} lineage
144 JOIN descendants ON lineage.{parent_column} = descendants.id
145 WHERE instr(
146 descendants.visited,
147 printf('|%s|', hex(lineage.{child_column}))
148 ) = 0
149 AND (?2 IS NULL OR descendants.depth < ?2)
150 ),
151 ranked_descendants(id, depth) AS (
152 SELECT id, MIN(depth)
153 FROM descendants
154 GROUP BY id
155 )
156 SELECT child.{child_id_column}
157 FROM {child_table_name} child
158 JOIN ranked_descendants descendants ON child.{child_id_column} = descendants.id
159 WHERE ?2 IS NULL OR descendants.depth <= ?2
160 ORDER BY descendants.depth, child.{child_id_column};",
161 table_name = Self::TABLE_NAME,
162 parent_column = Self::PARENT_COLUMN,
163 child_column = Self::CHILD_COLUMN,
164 child_table_name = Self::CHILD_TABLE_NAME,
165 child_id_column = Self::CHILD_ID_COLUMN,
166 );
167
168 let mut stmt = conn.prepare(&query).unwrap();
169 stmt.query_map(params![parent_id, max_depth], |row| row.get(0))
170 .unwrap()
171 .map(|value| value.unwrap())
172 .collect()
173 }
174
175 fn get_graph(conn: &Connection) -> Vec<Self> {
176 let query = format!(
177 "WITH RECURSIVE lineage_graph({parent_column}, {child_column}) AS (
178 SELECT {parent_column}, {child_column}
179 FROM {table_name}
180 UNION
181 SELECT lineage.{parent_column}, lineage.{child_column}
182 FROM {table_name} lineage
183 JOIN lineage_graph graph ON lineage.{parent_column} = graph.{child_column}
184 )
185 SELECT {parent_column}, {child_column}
186 FROM lineage_graph;",
187 table_name = Self::TABLE_NAME,
188 parent_column = Self::PARENT_COLUMN,
189 child_column = Self::CHILD_COLUMN,
190 );
191
192 Self::query(conn, &query, [])
193 }
194
195 fn get_path_between(
196 conn: &Connection,
197 source_id: &Self::Id,
198 target_id: &Self::Id,
199 ) -> Vec<Self::Id> {
200 if source_id == target_id {
201 return vec![source_id.clone()];
202 }
203
204 let query = format!(
205 "WITH RECURSIVE traversal(current_id, visited, node_path, depth) AS (
206 SELECT
207 ?1,
208 printf('|%s|', hex(?1)),
209 printf('%s', hex(?1)),
210 0
211 UNION ALL
212 SELECT
213 CASE
214 WHEN lineage.{parent_column} = traversal.current_id THEN lineage.{child_column}
215 ELSE lineage.{parent_column}
216 END,
217 traversal.visited || hex(
218 CASE
219 WHEN lineage.{parent_column} = traversal.current_id THEN lineage.{child_column}
220 ELSE lineage.{parent_column}
221 END
222 ) || '|',
223 traversal.node_path || ',' || hex(
224 CASE
225 WHEN lineage.{parent_column} = traversal.current_id THEN lineage.{child_column}
226 ELSE lineage.{parent_column}
227 END
228 ),
229 traversal.depth + 1
230 FROM traversal
231 JOIN {table_name} lineage
232 ON lineage.{parent_column} = traversal.current_id
233 OR lineage.{child_column} = traversal.current_id
234 WHERE instr(
235 traversal.visited,
236 printf(
237 '|%s|',
238 hex(
239 CASE
240 WHEN lineage.{parent_column} = traversal.current_id THEN lineage.{child_column}
241 ELSE lineage.{parent_column}
242 END
243 )
244 )
245 ) = 0
246 )
247 SELECT node_path
248 FROM traversal
249 WHERE current_id = ?2
250 ORDER BY depth
251 LIMIT 1;",
252 table_name = Self::TABLE_NAME,
253 parent_column = Self::PARENT_COLUMN,
254 child_column = Self::CHILD_COLUMN,
255 );
256
257 let mut stmt = conn.prepare(&query).unwrap();
258 let encoded_path = stmt
259 .query_row(params![source_id, target_id], |row| row.get::<_, String>(0))
260 .ok();
261
262 encoded_path
263 .map(|path| {
264 path.split(',')
265 .filter(|token| !token.is_empty())
266 .map(Self::Id::decode_hex_token)
267 .collect()
268 })
269 .unwrap_or_default()
270 }
271
272 fn get_path_edges_between(
273 conn: &Connection,
274 source_id: &Self::Id,
275 target_id: &Self::Id,
276 ) -> Vec<Self> {
277 let path = Self::get_path_between(conn, source_id, target_id);
278 let mut edges = Vec::new();
279 for pair in path.windows(2) {
280 let query = format!(
281 "SELECT {parent_column}, {child_column}
282 FROM {table_name}
283 WHERE ({parent_column} = ?1 AND {child_column} = ?2)
284 OR ({parent_column} = ?2 AND {child_column} = ?1)
285 LIMIT 1;",
286 table_name = Self::TABLE_NAME,
287 parent_column = Self::PARENT_COLUMN,
288 child_column = Self::CHILD_COLUMN,
289 );
290
291 if let Ok(edge) = Self::get(conn, &query, params![&pair[0], &pair[1]]) {
292 edges.push(edge);
293 }
294 }
295 edges
296 }
297}
298
299#[cfg(test)]
300mod tests {
301 use rusqlite::{Connection, Row, params};
302
303 use super::*;
304
305 #[derive(Clone, Debug, Eq, PartialEq)]
306 struct NumericLineage {
307 parent_id: i64,
308 child_id: i64,
309 }
310
311 impl Query for NumericLineage {
312 type Model = NumericLineage;
313
314 const PRIMARY_KEY: &'static str = "parent_id";
315 const TABLE_NAME: &'static str = "numeric_lineage";
316
317 fn process_row(row: &Row) -> Self::Model {
318 NumericLineage {
319 parent_id: row.get(0).unwrap(),
320 child_id: row.get(1).unwrap(),
321 }
322 }
323 }
324
325 impl SqlLineage for NumericLineage {
326 type Id = i64;
327
328 const CHILD_COLUMN: &'static str = "child_id";
329 const CHILD_ID_COLUMN: &'static str = "id";
330 const CHILD_TABLE_NAME: &'static str = "numeric_nodes";
331 const PARENT_COLUMN: &'static str = "parent_id";
332 const PARENT_ID_COLUMN: &'static str = "id";
333 const PARENT_TABLE_NAME: &'static str = "numeric_nodes";
334
335 fn parent_id(&self) -> &Self::Id {
336 &self.parent_id
337 }
338
339 fn child_id(&self) -> &Self::Id {
340 &self.child_id
341 }
342 }
343
344 #[derive(Clone, Debug, Eq, PartialEq)]
345 struct HashLineage {
346 parent_id: HashId,
347 child_id: HashId,
348 }
349
350 impl Query for HashLineage {
351 type Model = HashLineage;
352
353 const PRIMARY_KEY: &'static str = "parent_id";
354 const TABLE_NAME: &'static str = "hash_lineage";
355
356 fn process_row(row: &Row) -> Self::Model {
357 HashLineage {
358 parent_id: row.get(0).unwrap(),
359 child_id: row.get(1).unwrap(),
360 }
361 }
362 }
363
364 impl SqlLineage for HashLineage {
365 type Id = HashId;
366
367 const CHILD_COLUMN: &'static str = "child_id";
368 const CHILD_ID_COLUMN: &'static str = "id";
369 const CHILD_TABLE_NAME: &'static str = "hash_nodes";
370 const PARENT_COLUMN: &'static str = "parent_id";
371 const PARENT_ID_COLUMN: &'static str = "id";
372 const PARENT_TABLE_NAME: &'static str = "hash_nodes";
373
374 fn parent_id(&self) -> &Self::Id {
375 &self.parent_id
376 }
377
378 fn child_id(&self) -> &Self::Id {
379 &self.child_id
380 }
381 }
382
383 fn setup_numeric_lineage_connection() -> Connection {
384 let conn = Connection::open_in_memory().unwrap();
385 conn.execute_batch(
386 "
387 CREATE TABLE numeric_nodes (id INTEGER PRIMARY KEY);
388 CREATE TABLE numeric_lineage (
389 parent_id INTEGER NOT NULL,
390 child_id INTEGER NOT NULL
391 );
392 ",
393 )
394 .unwrap();
395
396 for id in [1_i64, 2, 3, 4, 5, 6] {
397 conn.execute("INSERT INTO numeric_nodes (id) VALUES (?1);", params![id])
398 .unwrap();
399 }
400
401 for (parent_id, child_id) in [(1_i64, 2_i64), (2, 3), (3, 4), (2, 5)] {
402 conn.execute(
403 "INSERT INTO numeric_lineage (parent_id, child_id) VALUES (?1, ?2);",
404 params![parent_id, child_id],
405 )
406 .unwrap();
407 }
408
409 conn
410 }
411
412 fn setup_hash_lineage_connection() -> (Connection, HashId, HashId, HashId, HashId) {
413 let conn = Connection::open_in_memory().unwrap();
414 conn.execute_batch(
415 "
416 CREATE TABLE hash_nodes (id BLOB PRIMARY KEY);
417 CREATE TABLE hash_lineage (
418 parent_id BLOB NOT NULL,
419 child_id BLOB NOT NULL
420 );
421 ",
422 )
423 .unwrap();
424
425 let root = HashId::convert_str("lineage-root");
426 let middle = HashId::convert_str("lineage-middle");
427 let leaf = HashId::convert_str("lineage-leaf");
428 let other = HashId::convert_str("lineage-other");
429
430 for id in [root, middle, leaf, other] {
431 conn.execute("INSERT INTO hash_nodes (id) VALUES (?1);", params![id])
432 .unwrap();
433 }
434
435 for (parent_id, child_id) in [(root, middle), (middle, leaf)] {
436 conn.execute(
437 "INSERT INTO hash_lineage (parent_id, child_id) VALUES (?1, ?2);",
438 params![parent_id, child_id],
439 )
440 .unwrap();
441 }
442
443 (conn, root, middle, leaf, other)
444 }
445
446 #[test]
447 fn test_sql_lineage_queries_with_numeric_ids() {
448 let conn = setup_numeric_lineage_connection();
449
450 assert_eq!(
451 NumericLineage::get_ancestors(&conn, &4, None),
452 vec![3, 2, 1]
453 );
454 assert_eq!(
455 NumericLineage::get_ancestors(&conn, &4, Some(2)),
456 vec![3, 2]
457 );
458 assert_eq!(
459 NumericLineage::get_descendants(&conn, &1, None),
460 vec![2, 3, 5, 4]
461 );
462 assert_eq!(
463 NumericLineage::get_descendants(&conn, &1, Some(2)),
464 vec![2, 3, 5]
465 );
466 assert_eq!(
467 NumericLineage::get_path_between(&conn, &1, &4),
468 vec![1, 2, 3, 4]
469 );
470 assert_eq!(
471 NumericLineage::get_path_edges_between(&conn, &1, &4),
472 vec![
473 NumericLineage {
474 parent_id: 1,
475 child_id: 2,
476 },
477 NumericLineage {
478 parent_id: 2,
479 child_id: 3,
480 },
481 NumericLineage {
482 parent_id: 3,
483 child_id: 4,
484 },
485 ]
486 );
487
488 let mut graph = NumericLineage::get_graph(&conn);
489 graph.sort_by(|left, right| {
490 left.parent_id
491 .cmp(&right.parent_id)
492 .then(left.child_id.cmp(&right.child_id))
493 });
494 assert_eq!(
495 graph,
496 vec![
497 NumericLineage {
498 parent_id: 1,
499 child_id: 2,
500 },
501 NumericLineage {
502 parent_id: 2,
503 child_id: 3,
504 },
505 NumericLineage {
506 parent_id: 2,
507 child_id: 5,
508 },
509 NumericLineage {
510 parent_id: 3,
511 child_id: 4,
512 },
513 ]
514 );
515 }
516
517 #[test]
518 fn test_sql_lineage_path_between_handles_same_and_disconnected_numeric_ids() {
519 let conn = setup_numeric_lineage_connection();
520
521 assert_eq!(NumericLineage::get_path_between(&conn, &3, &3), vec![3]);
522 assert_eq!(
523 NumericLineage::get_path_between(&conn, &1, &6),
524 Vec::<i64>::new()
525 );
526 assert_eq!(
527 NumericLineage::get_path_edges_between(&conn, &1, &6),
528 Vec::<NumericLineage>::new()
529 );
530 }
531
532 #[test]
533 fn test_sql_lineage_hash_id_paths_decode_hex_tokens() {
534 let (conn, root, middle, leaf, other) = setup_hash_lineage_connection();
535
536 assert_eq!(
537 HashLineage::get_path_between(&conn, &root, &leaf),
538 vec![root, middle, leaf]
539 );
540 assert_eq!(
541 HashLineage::get_path_edges_between(&conn, &root, &leaf),
542 vec![
543 HashLineage {
544 parent_id: root,
545 child_id: middle,
546 },
547 HashLineage {
548 parent_id: middle,
549 child_id: leaf,
550 },
551 ]
552 );
553 assert_eq!(
554 HashLineage::get_path_between(&conn, &root, &other),
555 Vec::<HashId>::new()
556 );
557 }
558}