Skip to main content

gen_models/
lineage.rs

1use std::str::FromStr;
2
3use gen_core::HashId;
4use rusqlite::{
5    Connection, Row,
6    types::{FromSql, ToSql},
7};
8
9use crate::select::sql_table_name_with_history_ref;
10
11// This looks a bit redundant with the HashId sql parsing, but is not because the id column can be any type. The macro below
12// and these traits provide a generic way to go from hex in sql -> rust type. The traversal code encodes everything as hex
13// so ints/strings/blobs/etc. can all be treated identically in traversal.
14pub trait LineageId: Clone + Eq + FromSql + ToSql {
15    fn decode_hex_token(token: &str) -> Self;
16}
17
18/// A stable page of lineage IDs.
19#[derive(Clone, Debug, Eq, PartialEq)]
20pub struct LineagePage<Id> {
21    /// IDs returned in the requested order.
22    pub ids: Vec<Id>,
23    /// Whether another page can be requested with the next offset.
24    pub has_more: bool,
25}
26
27fn decode_hex_bytes(token: &str) -> Vec<u8> {
28    assert_eq!(token.len() % 2, 0, "hex tokens must have an even length");
29
30    token
31        .as_bytes()
32        .as_chunks::<2>()
33        .0
34        .iter()
35        .map(|pair| {
36            let pair = std::str::from_utf8(pair).expect("hex token must be valid ascii");
37            u8::from_str_radix(pair, 16).expect("hex token must be valid")
38        })
39        .collect()
40}
41
42impl LineageId for String {
43    fn decode_hex_token(token: &str) -> Self {
44        String::from_utf8(decode_hex_bytes(token)).expect("lineage token should decode to utf-8")
45    }
46}
47
48impl LineageId for HashId {
49    fn decode_hex_token(token: &str) -> Self {
50        let bytes = decode_hex_bytes(token);
51        HashId::try_from(bytes.as_slice()).expect("lineage token should decode to a hash id")
52    }
53}
54
55macro_rules! impl_numeric_lineage_id {
56    ($($ty:ty),* $(,)?) => {
57        $(
58            impl LineageId for $ty {
59                fn decode_hex_token(token: &str) -> Self {
60                    let value =
61                        String::from_utf8(decode_hex_bytes(token)).expect("lineage token should decode to utf-8");
62                    <$ty>::from_str(&value).expect("lineage token should decode to a number")
63                }
64            }
65        )*
66    };
67}
68
69impl_numeric_lineage_id!(i32, i64, u32, u64, usize);
70
71pub trait SqlLineage: Sized {
72    type Id: LineageId;
73
74    const TABLE_NAME: &'static str;
75    const PARENT_TABLE_NAME: &'static str;
76    const PARENT_ID_COLUMN: &'static str;
77    const CHILD_TABLE_NAME: &'static str;
78    const CHILD_ID_COLUMN: &'static str;
79    const PARENT_COLUMN: &'static str;
80    const CHILD_COLUMN: &'static str;
81
82    fn parent_id(&self) -> &Self::Id;
83    fn child_id(&self) -> &Self::Id;
84    fn process_row(row: &Row) -> rusqlite::Result<Self>;
85
86    /// Return root entities that have no incoming lineage edge.
87    fn get_roots_page(
88        conn: &Connection,
89        limit: usize,
90        offset: u32,
91        history_ref: Option<&str>,
92    ) -> LineagePage<Self::Id> {
93        let lineage_table_name =
94            sql_table_name_with_history_ref(Self::TABLE_NAME, Some(Self::TABLE_NAME), history_ref);
95        let parent_table_name = sql_table_name_with_history_ref(
96            Self::PARENT_TABLE_NAME,
97            Some(Self::PARENT_TABLE_NAME),
98            history_ref,
99        );
100        // This query essentially finds all potential parents and declares that as a root. It does so by
101        // identifying all potential parents, and then removing if that potential parent has a parent.
102        // It's done this way instead of doing a lookup of parent_id is null because a join table would
103        // not contain any entries -- such as:
104        // Table 1 having {1,2,3}
105        // A join table having {parent_id: 1, child_id: 3}
106        // Looking at parent_id is null would:
107        //   return no parents if no lineage existed
108        //   fail to identify id 2 as a root
109        let query = format!(
110            "SELECT parent.{parent_id_column}
111             FROM {parent_table_name} parent
112             WHERE NOT EXISTS (
113                 SELECT 1
114                 FROM {lineage_table_name} lineage
115                 WHERE lineage.{child_column} = parent.{parent_id_column}
116             )
117             ORDER BY parent.{parent_id_column}
118             LIMIT :limit OFFSET :offset;",
119            parent_id_column = Self::PARENT_ID_COLUMN,
120            parent_table_name = parent_table_name,
121            lineage_table_name = lineage_table_name,
122            child_column = Self::CHILD_COLUMN,
123        );
124        let limit = limit.max(1);
125        let fetch_limit = i64::try_from(limit.saturating_add(1)).unwrap_or(i64::MAX);
126        let offset = i64::from(offset);
127        let history_ref_param = history_ref.map(str::to_owned);
128        let mut query_params: Vec<(&str, &dyn ToSql)> =
129            vec![(":limit", &fetch_limit), (":offset", &offset)];
130        if let Some(history_ref) = history_ref_param.as_ref() {
131            query_params.push((":history_ref", history_ref));
132        }
133        let mut ids = conn
134            .prepare(&query)
135            .unwrap()
136            .query_map(&query_params[..], |row| row.get(0))
137            .unwrap()
138            .map(|value| value.unwrap())
139            .collect::<Vec<Self::Id>>();
140        let has_more = ids.len() > limit;
141        if has_more {
142            ids.truncate(limit);
143        }
144        LineagePage { ids, has_more }
145    }
146
147    /// Return direct children in a stable, offset-paginated order.
148    fn get_children_page(
149        conn: &Connection,
150        parent_id: &Self::Id,
151        limit: usize,
152        offset: u32,
153        history_ref: Option<&str>,
154    ) -> LineagePage<Self::Id> {
155        let lineage_table_name =
156            sql_table_name_with_history_ref(Self::TABLE_NAME, Some(Self::TABLE_NAME), history_ref);
157        let child_table_name = sql_table_name_with_history_ref(
158            Self::CHILD_TABLE_NAME,
159            Some(Self::CHILD_TABLE_NAME),
160            history_ref,
161        );
162        let query = format!(
163            "SELECT child.{child_id_column}
164             FROM {child_table_name} child
165             WHERE EXISTS (
166                 SELECT 1
167                 FROM {lineage_table_name} lineage
168                 WHERE lineage.{parent_column} = :parent_id
169                   AND lineage.{child_column} != :parent_id
170                   AND lineage.{child_column} = child.{child_id_column}
171             )
172             ORDER BY child.{child_id_column}
173             LIMIT :limit OFFSET :offset;",
174            child_id_column = Self::CHILD_ID_COLUMN,
175            child_table_name = child_table_name,
176            lineage_table_name = lineage_table_name,
177            parent_column = Self::PARENT_COLUMN,
178            child_column = Self::CHILD_COLUMN,
179        );
180        let limit = limit.max(1);
181        let fetch_limit = i64::try_from(limit.saturating_add(1)).unwrap_or(i64::MAX);
182        let offset = i64::from(offset);
183        let history_ref_param = history_ref.map(str::to_owned);
184        let mut query_params: Vec<(&str, &dyn ToSql)> = vec![
185            (":parent_id", parent_id),
186            (":limit", &fetch_limit),
187            (":offset", &offset),
188        ];
189        if let Some(history_ref) = history_ref_param.as_ref() {
190            query_params.push((":history_ref", history_ref));
191        }
192        let mut ids = conn
193            .prepare(&query)
194            .unwrap()
195            .query_map(&query_params[..], |row| row.get(0))
196            .unwrap()
197            .map(|value| value.unwrap())
198            .collect::<Vec<Self::Id>>();
199        let has_more = ids.len() > limit;
200        if has_more {
201            ids.truncate(limit);
202        }
203        LineagePage { ids, has_more }
204    }
205
206    /// Return descendants ordered by minimum depth and ID with a global page bound.
207    ///
208    /// The page limits rows returned to the caller. The recursive traversal still visits the
209    /// bounded-depth subgraph so convergent paths can be deduplicated before the offset is
210    /// applied; callers that need very wide levels should use `get_children_page`.
211    fn get_descendants_page(
212        conn: &Connection,
213        parent_id: &Self::Id,
214        max_depth: Option<usize>,
215        limit: usize,
216        offset: u32,
217        history_ref: Option<&str>,
218    ) -> LineagePage<Self::Id> {
219        let max_depth = max_depth.map(|depth| depth as i64);
220        let lineage_table_name =
221            sql_table_name_with_history_ref(Self::TABLE_NAME, Some(Self::TABLE_NAME), history_ref);
222        let child_table_name = sql_table_name_with_history_ref(
223            Self::CHILD_TABLE_NAME,
224            Some(Self::CHILD_TABLE_NAME),
225            history_ref,
226        );
227        let query = format!(
228            "WITH RECURSIVE descendants(id, depth, visited) AS (
229                 SELECT lineage.{child_column}, 1,
230                        printf('|%s|%s|', hex(:parent_id), hex(lineage.{child_column}))
231                 FROM {lineage_table_name} lineage
232                 WHERE lineage.{parent_column} = :parent_id
233                   AND lineage.{child_column} != :parent_id
234                 UNION ALL
235                 SELECT lineage.{child_column}, descendants.depth + 1,
236                        descendants.visited || hex(lineage.{child_column}) || '|'
237                 FROM {lineage_table_name} lineage
238                 JOIN descendants ON lineage.{parent_column} = descendants.id
239                 WHERE instr(descendants.visited, printf('|%s|', hex(lineage.{child_column}))) = 0
240                   AND (:max_depth IS NULL OR descendants.depth < :max_depth)
241             ), ranked_descendants(id, depth) AS (
242                 SELECT id, MIN(depth)
243                 FROM descendants
244                 GROUP BY id
245             )
246             SELECT child.{child_id_column}
247             FROM {child_table_name} child
248             JOIN ranked_descendants ON child.{child_id_column} = ranked_descendants.id
249             WHERE (:max_depth IS NULL OR ranked_descendants.depth <= :max_depth)
250             ORDER BY ranked_descendants.depth, child.{child_id_column}
251             LIMIT :limit OFFSET :offset;",
252            lineage_table_name = lineage_table_name,
253            parent_column = Self::PARENT_COLUMN,
254            child_column = Self::CHILD_COLUMN,
255            child_table_name = child_table_name,
256            child_id_column = Self::CHILD_ID_COLUMN,
257        );
258        let limit = limit.max(1);
259        let fetch_limit = i64::try_from(limit.saturating_add(1)).unwrap_or(i64::MAX);
260        let offset = i64::from(offset);
261        let history_ref_param = history_ref.map(str::to_owned);
262        let mut query_params: Vec<(&str, &dyn ToSql)> = vec![
263            (":parent_id", parent_id),
264            (":max_depth", &max_depth),
265            (":limit", &fetch_limit),
266            (":offset", &offset),
267        ];
268        if let Some(history_ref) = history_ref_param.as_ref() {
269            query_params.push((":history_ref", history_ref));
270        }
271        let mut ids = conn
272            .prepare(&query)
273            .unwrap()
274            .query_map(&query_params[..], |row| row.get(0))
275            .unwrap()
276            .map(|value| value.unwrap())
277            .collect::<Vec<Self::Id>>();
278        let has_more = ids.len() > limit;
279        if has_more {
280            ids.truncate(limit);
281        }
282        LineagePage { ids, has_more }
283    }
284
285    /// Return ancestors ordered by minimum depth and ID with a global page bound.
286    ///
287    /// The page limits rows returned to the caller. The recursive traversal still visits the
288    /// bounded-depth subgraph so convergent paths can be deduplicated before the offset is
289    /// applied.
290    fn get_ancestors_page(
291        conn: &Connection,
292        child_id: &Self::Id,
293        max_depth: Option<usize>,
294        limit: usize,
295        offset: u32,
296        history_ref: Option<&str>,
297    ) -> LineagePage<Self::Id> {
298        let max_depth = max_depth.map(|depth| depth as i64);
299        let lineage_table_name =
300            sql_table_name_with_history_ref(Self::TABLE_NAME, Some(Self::TABLE_NAME), history_ref);
301        let parent_table_name = sql_table_name_with_history_ref(
302            Self::PARENT_TABLE_NAME,
303            Some(Self::PARENT_TABLE_NAME),
304            history_ref,
305        );
306        let query = format!(
307            "WITH RECURSIVE ancestors(id, depth, visited) AS (
308                 SELECT lineage.{parent_column}, 1,
309                        printf('|%s|%s|', hex(:child_id), hex(lineage.{parent_column}))
310                 FROM {lineage_table_name} lineage
311                 WHERE lineage.{child_column} = :child_id
312                   AND lineage.{parent_column} != :child_id
313                 UNION ALL
314                 SELECT lineage.{parent_column}, ancestors.depth + 1,
315                        ancestors.visited || hex(lineage.{parent_column}) || '|'
316                 FROM {lineage_table_name} lineage
317                 JOIN ancestors ON lineage.{child_column} = ancestors.id
318                 WHERE instr(ancestors.visited, printf('|%s|', hex(lineage.{parent_column}))) = 0
319                   AND (:max_depth IS NULL OR ancestors.depth < :max_depth)
320             ), ranked_ancestors(id, depth) AS (
321                 SELECT id, MIN(depth)
322                 FROM ancestors
323                 GROUP BY id
324             )
325             SELECT parent.{parent_id_column}
326             FROM {parent_table_name} parent
327             JOIN ranked_ancestors ON parent.{parent_id_column} = ranked_ancestors.id
328             WHERE (:max_depth IS NULL OR ranked_ancestors.depth <= :max_depth)
329             ORDER BY ranked_ancestors.depth, parent.{parent_id_column}
330             LIMIT :limit OFFSET :offset;",
331            lineage_table_name = lineage_table_name,
332            parent_column = Self::PARENT_COLUMN,
333            child_column = Self::CHILD_COLUMN,
334            parent_table_name = parent_table_name,
335            parent_id_column = Self::PARENT_ID_COLUMN,
336        );
337        let limit = limit.max(1);
338        let fetch_limit = i64::try_from(limit.saturating_add(1)).unwrap_or(i64::MAX);
339        let offset = i64::from(offset);
340        let history_ref_param = history_ref.map(str::to_owned);
341        let mut query_params: Vec<(&str, &dyn ToSql)> = vec![
342            (":child_id", child_id),
343            (":max_depth", &max_depth),
344            (":limit", &fetch_limit),
345            (":offset", &offset),
346        ];
347        if let Some(history_ref) = history_ref_param.as_ref() {
348            query_params.push((":history_ref", history_ref));
349        }
350        let mut ids = conn
351            .prepare(&query)
352            .unwrap()
353            .query_map(&query_params[..], |row| row.get(0))
354            .unwrap()
355            .map(|value| value.unwrap())
356            .collect::<Vec<Self::Id>>();
357        let has_more = ids.len() > limit;
358        if has_more {
359            ids.truncate(limit);
360        }
361        LineagePage { ids, has_more }
362    }
363
364    fn get_ancestors(
365        conn: &Connection,
366        child_id: &Self::Id,
367        max_depth: Option<usize>,
368        history_ref: Option<&str>,
369    ) -> Vec<Self::Id> {
370        let max_depth = max_depth.map(|depth| depth as i64);
371        let lineage_table_name =
372            sql_table_name_with_history_ref(Self::TABLE_NAME, Some(Self::TABLE_NAME), history_ref);
373        let parent_table_name = history_ref.map_or_else(
374            || Self::PARENT_TABLE_NAME.to_string(),
375            |_| format!("dolt_at_{}(:history_ref)", Self::PARENT_TABLE_NAME),
376        );
377        let query = format!(
378            "WITH RECURSIVE ancestors(id, depth, visited) AS (
379                SELECT
380                    lineage.{parent_column},
381                    1,
382                    printf('|%s|', hex(lineage.{parent_column}))
383                FROM {table_name} lineage
384                WHERE lineage.{child_column} = :child_id
385                UNION ALL
386                SELECT
387                    lineage.{parent_column},
388                    ancestors.depth + 1,
389                    ancestors.visited || hex(lineage.{parent_column}) || '|'
390                FROM {table_name} lineage
391                JOIN ancestors ON lineage.{child_column} = ancestors.id
392                WHERE instr(
393                    ancestors.visited,
394                    printf('|%s|', hex(lineage.{parent_column}))
395                ) = 0
396                AND (:max_depth IS NULL OR ancestors.depth < :max_depth)
397            ),
398            ranked_ancestors(id, depth) AS (
399                SELECT id, MIN(depth)
400                FROM ancestors
401                GROUP BY id
402            )
403            SELECT parent.{parent_id_column}
404            FROM {parent_table_name} parent
405            JOIN ranked_ancestors ancestors ON parent.{parent_id_column} = ancestors.id
406            WHERE :max_depth IS NULL OR ancestors.depth <= :max_depth
407            ORDER BY ancestors.depth, parent.{parent_id_column};",
408            table_name = lineage_table_name,
409            parent_column = Self::PARENT_COLUMN,
410            child_column = Self::CHILD_COLUMN,
411            parent_table_name = parent_table_name,
412            parent_id_column = Self::PARENT_ID_COLUMN,
413        );
414
415        let mut stmt = conn.prepare(&query).unwrap();
416        let mut query_params: Vec<(&str, &dyn ToSql)> =
417            vec![(":child_id", child_id), (":max_depth", &max_depth)];
418        if let Some(history_ref) = history_ref.as_ref() {
419            query_params.push((":history_ref", history_ref));
420        }
421        stmt.query_map(&query_params[..], |row| row.get(0))
422            .unwrap()
423            .map(|value| value.unwrap())
424            .collect()
425    }
426
427    /// Return unique descendants ordered by minimum depth, then child ID.
428    /// Both lineage edges and child entities are read at `history_ref` when supplied.
429    fn get_descendants(
430        conn: &Connection,
431        parent_id: &Self::Id,
432        max_depth: Option<usize>,
433        history_ref: Option<&str>,
434    ) -> Vec<Self::Id> {
435        let max_depth = max_depth.map(|depth| depth as i64);
436        let lineage_table_name =
437            sql_table_name_with_history_ref(Self::TABLE_NAME, Some(Self::TABLE_NAME), history_ref);
438        let child_table_name = sql_table_name_with_history_ref(
439            Self::CHILD_TABLE_NAME,
440            Some(Self::CHILD_TABLE_NAME),
441            history_ref,
442        );
443        let query = format!(
444            "WITH RECURSIVE descendants(id, depth, visited) AS (
445                SELECT
446                    lineage.{child_column},
447                    1,
448                    printf('|%s|%s|', hex(:parent_id), hex(lineage.{child_column}))
449                FROM {table_name} lineage
450                WHERE lineage.{parent_column} = :parent_id
451                  AND lineage.{child_column} != :parent_id
452                UNION ALL
453                SELECT
454                    lineage.{child_column},
455                    descendants.depth + 1,
456                    descendants.visited || hex(lineage.{child_column}) || '|'
457                FROM {table_name} lineage
458                JOIN descendants ON lineage.{parent_column} = descendants.id
459                WHERE instr(
460                    descendants.visited,
461                    printf('|%s|', hex(lineage.{child_column}))
462                ) = 0
463                AND (:max_depth IS NULL OR descendants.depth < :max_depth)
464            ),
465            ranked_descendants(id, depth) AS (
466                SELECT id, MIN(depth)
467                FROM descendants
468                GROUP BY id
469            )
470            SELECT child.{child_id_column}
471            FROM {child_table_name} child
472            JOIN ranked_descendants descendants ON child.{child_id_column} = descendants.id
473            WHERE :max_depth IS NULL OR descendants.depth <= :max_depth
474            ORDER BY descendants.depth, child.{child_id_column};",
475            table_name = lineage_table_name,
476            parent_column = Self::PARENT_COLUMN,
477            child_column = Self::CHILD_COLUMN,
478            child_table_name = child_table_name,
479            child_id_column = Self::CHILD_ID_COLUMN,
480        );
481
482        let mut stmt = conn.prepare(&query).unwrap();
483        let mut query_params: Vec<(&str, &dyn ToSql)> =
484            vec![(":parent_id", parent_id), (":max_depth", &max_depth)];
485        if let Some(history_ref) = history_ref.as_ref() {
486            query_params.push((":history_ref", history_ref));
487        }
488        stmt.query_map(&query_params[..], |row| row.get(0))
489            .unwrap()
490            .map(|value| value.unwrap())
491            .collect()
492    }
493
494    fn get_graph(conn: &Connection, history_ref: Option<&str>) -> Vec<Self> {
495        let lineage_table_name =
496            sql_table_name_with_history_ref(Self::TABLE_NAME, Some(Self::TABLE_NAME), history_ref);
497        let query = format!(
498            "WITH RECURSIVE lineage_graph({parent_column}, {child_column}) AS (
499                SELECT {parent_column}, {child_column}
500                FROM {table_name}
501                UNION
502                SELECT lineage.{parent_column}, lineage.{child_column}
503                FROM {table_name} lineage
504                JOIN lineage_graph graph ON lineage.{parent_column} = graph.{child_column}
505            )
506            SELECT {parent_column}, {child_column}
507            FROM lineage_graph;",
508            table_name = lineage_table_name,
509            parent_column = Self::PARENT_COLUMN,
510            child_column = Self::CHILD_COLUMN,
511        );
512
513        let mut statement = conn.prepare(&query).unwrap();
514        let mut query_params: Vec<(&str, &dyn ToSql)> = Vec::new();
515        if let Some(history_ref) = history_ref.as_ref() {
516            query_params.push((":history_ref", history_ref));
517        }
518        statement
519            .query_map(&query_params[..], Self::process_row)
520            .unwrap()
521            .map(Result::unwrap)
522            .collect()
523    }
524
525    fn get_path_between(
526        conn: &Connection,
527        source_id: &Self::Id,
528        target_id: &Self::Id,
529        history_ref: Option<&str>,
530    ) -> Vec<Self::Id> {
531        if source_id == target_id {
532            return vec![source_id.clone()];
533        }
534
535        let lineage_table_name =
536            sql_table_name_with_history_ref(Self::TABLE_NAME, Some(Self::TABLE_NAME), history_ref);
537        let query = format!(
538            "WITH RECURSIVE traversal(current_id, visited, node_path, depth) AS (
539                SELECT
540                    :source_id,
541                    printf('|%s|', hex(:source_id)),
542                    printf('%s', hex(:source_id)),
543                    0
544                UNION ALL
545                SELECT
546                    CASE
547                        WHEN lineage.{parent_column} = traversal.current_id THEN lineage.{child_column}
548                        ELSE lineage.{parent_column}
549                    END,
550                    traversal.visited || hex(
551                        CASE
552                            WHEN lineage.{parent_column} = traversal.current_id THEN lineage.{child_column}
553                            ELSE lineage.{parent_column}
554                        END
555                    ) || '|',
556                    traversal.node_path || ',' || hex(
557                        CASE
558                            WHEN lineage.{parent_column} = traversal.current_id THEN lineage.{child_column}
559                            ELSE lineage.{parent_column}
560                        END
561                    ),
562                    traversal.depth + 1
563                FROM traversal
564                JOIN {lineage_table_name} lineage
565                    ON lineage.{parent_column} = traversal.current_id
566                    OR lineage.{child_column} = traversal.current_id
567                WHERE instr(
568                    traversal.visited,
569                    printf(
570                        '|%s|',
571                        hex(
572                            CASE
573                                WHEN lineage.{parent_column} = traversal.current_id THEN lineage.{child_column}
574                                ELSE lineage.{parent_column}
575                            END
576                        )
577                    )
578                ) = 0
579            )
580            SELECT node_path
581            FROM traversal
582            WHERE current_id = :target_id
583            ORDER BY depth
584            LIMIT 1;",
585            lineage_table_name = lineage_table_name,
586            parent_column = Self::PARENT_COLUMN,
587            child_column = Self::CHILD_COLUMN,
588        );
589
590        let mut stmt = conn.prepare(&query).unwrap();
591        let mut query_params: Vec<(&str, &dyn ToSql)> =
592            vec![(":source_id", source_id), (":target_id", target_id)];
593        if let Some(history_ref) = history_ref.as_ref() {
594            query_params.push((":history_ref", history_ref));
595        }
596        let encoded_path = stmt
597            .query_row(&query_params[..], |row| row.get::<_, String>(0))
598            .ok();
599
600        encoded_path
601            .map(|path| {
602                path.split(',')
603                    .filter(|token| !token.is_empty())
604                    .map(Self::Id::decode_hex_token)
605                    .collect()
606            })
607            .unwrap_or_default()
608    }
609
610    fn get_path_edges_between(
611        conn: &Connection,
612        source_id: &Self::Id,
613        target_id: &Self::Id,
614        history_ref: Option<&str>,
615    ) -> Vec<Self> {
616        let path = Self::get_path_between(conn, source_id, target_id, history_ref);
617        let lineage_table_name =
618            sql_table_name_with_history_ref(Self::TABLE_NAME, Some(Self::TABLE_NAME), history_ref);
619        let mut edges = Vec::new();
620        for pair in path.windows(2) {
621            let query = format!(
622                "SELECT {parent_column}, {child_column}
623                FROM {lineage_table_name}
624                WHERE ({parent_column} = :source_id AND {child_column} = :target_id)
625                   OR ({parent_column} = :target_id AND {child_column} = :source_id)
626                LIMIT 1;",
627                lineage_table_name = lineage_table_name,
628                parent_column = Self::PARENT_COLUMN,
629                child_column = Self::CHILD_COLUMN,
630            );
631
632            let mut query_params: Vec<(&str, &dyn ToSql)> =
633                vec![(":source_id", &pair[0]), (":target_id", &pair[1])];
634            if let Some(history_ref) = history_ref.as_ref() {
635                query_params.push((":history_ref", history_ref));
636            }
637            let edge = conn.query_row(&query, &query_params[..], Self::process_row);
638            if let Ok(edge) = edge {
639                edges.push(edge);
640            }
641        }
642        edges
643    }
644}
645
646#[cfg(test)]
647mod tests {
648    use rusqlite::{Connection, Row, params};
649
650    use super::*;
651
652    #[derive(Clone, Debug, Eq, PartialEq)]
653    struct NumericLineage {
654        parent_id: i64,
655        child_id: i64,
656    }
657
658    impl SqlLineage for NumericLineage {
659        type Id = i64;
660
661        const CHILD_COLUMN: &'static str = "child_id";
662        const CHILD_ID_COLUMN: &'static str = "id";
663        const CHILD_TABLE_NAME: &'static str = "numeric_nodes";
664        const PARENT_COLUMN: &'static str = "parent_id";
665        const PARENT_ID_COLUMN: &'static str = "id";
666        const PARENT_TABLE_NAME: &'static str = "numeric_nodes";
667        const TABLE_NAME: &'static str = "numeric_lineage";
668
669        fn process_row(row: &Row) -> rusqlite::Result<Self> {
670            Ok(NumericLineage {
671                parent_id: row.get(0)?,
672                child_id: row.get(1)?,
673            })
674        }
675
676        fn parent_id(&self) -> &Self::Id {
677            &self.parent_id
678        }
679
680        fn child_id(&self) -> &Self::Id {
681            &self.child_id
682        }
683    }
684
685    #[derive(Clone, Debug, Eq, PartialEq)]
686    struct HashLineage {
687        parent_id: HashId,
688        child_id: HashId,
689    }
690
691    impl SqlLineage for HashLineage {
692        type Id = HashId;
693
694        const CHILD_COLUMN: &'static str = "child_id";
695        const CHILD_ID_COLUMN: &'static str = "id";
696        const CHILD_TABLE_NAME: &'static str = "hash_nodes";
697        const PARENT_COLUMN: &'static str = "parent_id";
698        const PARENT_ID_COLUMN: &'static str = "id";
699        const PARENT_TABLE_NAME: &'static str = "hash_nodes";
700        const TABLE_NAME: &'static str = "hash_lineage";
701
702        fn process_row(row: &Row) -> rusqlite::Result<Self> {
703            Ok(HashLineage {
704                parent_id: row.get(0)?,
705                child_id: row.get(1)?,
706            })
707        }
708
709        fn parent_id(&self) -> &Self::Id {
710            &self.parent_id
711        }
712
713        fn child_id(&self) -> &Self::Id {
714            &self.child_id
715        }
716    }
717
718    fn setup_numeric_lineage_connection() -> Connection {
719        let conn = Connection::open_in_memory().unwrap();
720        conn.execute_batch(
721            "
722            CREATE TABLE numeric_nodes (id INTEGER PRIMARY KEY);
723            CREATE TABLE numeric_lineage (
724                parent_id INTEGER NOT NULL,
725                child_id INTEGER NOT NULL
726            );
727            ",
728        )
729        .unwrap();
730
731        for id in [1_i64, 2, 3, 4, 5, 6] {
732            conn.execute("INSERT INTO numeric_nodes (id) VALUES (?1);", params![id])
733                .unwrap();
734        }
735
736        for (parent_id, child_id) in [(1_i64, 2_i64), (2, 3), (3, 4), (2, 5)] {
737            conn.execute(
738                "INSERT INTO numeric_lineage (parent_id, child_id) VALUES (?1, ?2);",
739                params![parent_id, child_id],
740            )
741            .unwrap();
742        }
743
744        conn
745    }
746
747    fn setup_hash_lineage_connection() -> (Connection, HashId, HashId, HashId, HashId) {
748        let conn = Connection::open_in_memory().unwrap();
749        conn.execute_batch(
750            "
751            CREATE TABLE hash_nodes (id BLOB PRIMARY KEY);
752            CREATE TABLE hash_lineage (
753                parent_id BLOB NOT NULL,
754                child_id BLOB NOT NULL
755            );
756            ",
757        )
758        .unwrap();
759
760        let root = HashId::convert_str("lineage-root");
761        let middle = HashId::convert_str("lineage-middle");
762        let leaf = HashId::convert_str("lineage-leaf");
763        let other = HashId::convert_str("lineage-other");
764
765        for id in [root, middle, leaf, other] {
766            conn.execute("INSERT INTO hash_nodes (id) VALUES (?1);", params![id])
767                .unwrap();
768        }
769
770        for (parent_id, child_id) in [(root, middle), (middle, leaf)] {
771            conn.execute(
772                "INSERT INTO hash_lineage (parent_id, child_id) VALUES (?1, ?2);",
773                params![parent_id, child_id],
774            )
775            .unwrap();
776        }
777
778        (conn, root, middle, leaf, other)
779    }
780
781    #[test]
782    fn test_descendants_deduplicate_shared_paths_and_terminate_cycles() {
783        // The fixture starts with 1 -> 2 -> 3 -> 4 and 2 -> 5. Add 5 -> 3
784        // as a shared route to 3 and 4 -> 2 as the cycle 2 -> 3 -> 4 -> 2.
785
786        let conn = setup_numeric_lineage_connection();
787        // This adds a cycle between 4->2 and a shared path
788        conn.execute_batch(
789            "INSERT INTO numeric_lineage (parent_id, child_id) VALUES (5, 3), (4, 2);",
790        )
791        .expect("should add shared descendant and cycle");
792        assert_eq!(
793            NumericLineage::get_descendants(&conn, &1, None, None),
794            vec![2, 3, 5, 4]
795        );
796        // A depth-two limit keeps direct children and grandchildren, excluding node 4 at depth three.
797        assert_eq!(
798            NumericLineage::get_descendants(&conn, &1, Some(2), None),
799            vec![2, 3, 5]
800        );
801    }
802
803    #[test]
804    fn test_sql_lineage_queries_with_numeric_ids() {
805        let conn = setup_numeric_lineage_connection();
806
807        assert_eq!(
808            NumericLineage::get_ancestors(&conn, &4, None, None),
809            vec![3, 2, 1]
810        );
811        assert_eq!(
812            NumericLineage::get_ancestors(&conn, &4, Some(2), None),
813            vec![3, 2]
814        );
815        assert_eq!(
816            NumericLineage::get_descendants(&conn, &1, None, None),
817            vec![2, 3, 5, 4]
818        );
819        assert_eq!(
820            NumericLineage::get_descendants(&conn, &1, Some(2), None),
821            vec![2, 3, 5]
822        );
823        assert_eq!(
824            NumericLineage::get_path_between(&conn, &1, &4, None),
825            vec![1, 2, 3, 4]
826        );
827        assert_eq!(
828            NumericLineage::get_path_edges_between(&conn, &1, &4, None),
829            vec![
830                NumericLineage {
831                    parent_id: 1,
832                    child_id: 2,
833                },
834                NumericLineage {
835                    parent_id: 2,
836                    child_id: 3,
837                },
838                NumericLineage {
839                    parent_id: 3,
840                    child_id: 4,
841                },
842            ]
843        );
844
845        let mut graph = NumericLineage::get_graph(&conn, None);
846        graph.sort_by(|left, right| {
847            left.parent_id
848                .cmp(&right.parent_id)
849                .then(left.child_id.cmp(&right.child_id))
850        });
851        assert_eq!(
852            graph,
853            vec![
854                NumericLineage {
855                    parent_id: 1,
856                    child_id: 2,
857                },
858                NumericLineage {
859                    parent_id: 2,
860                    child_id: 3,
861                },
862                NumericLineage {
863                    parent_id: 2,
864                    child_id: 5,
865                },
866                NumericLineage {
867                    parent_id: 3,
868                    child_id: 4,
869                },
870            ]
871        );
872    }
873
874    #[test]
875    fn test_paged_roots_children_and_descendants_are_stable() {
876        let conn = setup_numeric_lineage_connection();
877        conn.execute_batch(
878            "INSERT INTO numeric_nodes (id) VALUES (7), (8), (9), (10), (11), (12);
879             INSERT INTO numeric_lineage (parent_id, child_id) VALUES
880                 (1, 7), (1, 8), (1, 9);",
881        )
882        .expect("should add paginated lineage fixtures");
883
884        let first_roots = NumericLineage::get_roots_page(&conn, 2, 0, None);
885        assert_eq!(first_roots.ids, vec![1, 6]);
886        assert!(first_roots.has_more);
887        let second_roots = NumericLineage::get_roots_page(&conn, 2, 2, None);
888        assert_eq!(second_roots.ids, vec![10, 11]);
889        assert!(second_roots.has_more);
890        let third_roots = NumericLineage::get_roots_page(&conn, 2, 4, None);
891        assert_eq!(third_roots.ids, vec![12]);
892        assert!(!third_roots.has_more);
893
894        let first_children = NumericLineage::get_children_page(&conn, &1, 2, 0, None);
895        assert_eq!(first_children.ids, vec![2, 7]);
896        assert!(first_children.has_more);
897
898        let second_children = NumericLineage::get_children_page(&conn, &1, 2, 2, None);
899        assert_eq!(second_children.ids, vec![8, 9]);
900        assert!(!second_children.has_more);
901
902        let first_descendants =
903            NumericLineage::get_descendants_page(&conn, &1, Some(2), 2, 0, None);
904        assert_eq!(first_descendants.ids, vec![2, 7]);
905        assert!(first_descendants.has_more);
906        let second_descendants =
907            NumericLineage::get_descendants_page(&conn, &1, Some(2), 2, 2, None);
908        assert_eq!(second_descendants.ids, vec![8, 9]);
909        assert!(second_descendants.has_more);
910        let third_descendants =
911            NumericLineage::get_descendants_page(&conn, &1, Some(2), 2, 4, None);
912        assert_eq!(third_descendants.ids, vec![3, 5]);
913        assert!(!third_descendants.has_more);
914
915        conn.execute_batch(
916            "INSERT INTO numeric_lineage (parent_id, child_id) VALUES (5, 3), (4, 2), (5, 1);",
917        )
918        .expect("should add convergent and cyclic lineage fixtures");
919        let page = NumericLineage::get_descendants_page(&conn, &1, Some(5), 20, 0, None);
920        assert_eq!(page.ids, vec![2, 7, 8, 9, 3, 5, 4]);
921        assert!(!page.has_more);
922        assert!(!page.ids.contains(&1));
923        assert_eq!(
924            NumericLineage::get_descendants(&conn, &1, Some(5), None),
925            vec![2, 7, 8, 9, 3, 5, 4]
926        );
927    }
928
929    #[test]
930    fn test_paged_ancestors_are_stable_and_cycle_safe() {
931        // The fixture is 1 -> 2 -> 3 -> 4, with a convergent route 2 -> 5 -> 3
932        // and a cycle-closing edge 4 -> 2. Ancestors of 4 should be 3, 2, 5, 1:
933        //
934        //     1 -> 2 -> 3 -> 4
935        //          |    ^    |
936        //          v    |    |
937        //          5 ---+    +-> 2
938        //
939        // The anchor 4 is reachable through the cycle but must not be returned.
940        let conn = setup_numeric_lineage_connection();
941        conn.execute_batch(
942            "INSERT INTO numeric_lineage (parent_id, child_id) VALUES (5, 3), (4, 2);",
943        )
944        .expect("should add convergent and cyclic lineage fixtures");
945
946        let first_page = NumericLineage::get_ancestors_page(&conn, &4, Some(5), 2, 0, None);
947        assert_eq!(first_page.ids, vec![3, 2]);
948        assert!(first_page.has_more);
949
950        let second_page = NumericLineage::get_ancestors_page(&conn, &4, Some(5), 2, 2, None);
951        assert_eq!(second_page.ids, vec![5, 1]);
952        assert!(!second_page.has_more);
953
954        let depth_limited = NumericLineage::get_ancestors_page(&conn, &4, Some(2), 20, 0, None);
955        assert_eq!(depth_limited.ids, vec![3, 2, 5]);
956        assert!(!depth_limited.has_more);
957
958        let zero_depth = NumericLineage::get_ancestors_page(&conn, &4, Some(0), 20, 0, None);
959        assert!(zero_depth.ids.is_empty());
960        assert!(!zero_depth.has_more);
961
962        let root = NumericLineage::get_ancestors_page(&conn, &1, None, 20, 0, None);
963        assert!(root.ids.is_empty());
964        assert!(!root.has_more);
965
966        let missing = NumericLineage::get_ancestors_page(&conn, &99, None, 20, 0, None);
967        assert!(missing.ids.is_empty());
968        assert!(!missing.has_more);
969        assert!(!first_page.ids.contains(&4));
970        assert!(!second_page.ids.contains(&4));
971    }
972
973    #[test]
974    fn test_sql_lineage_path_between_handles_same_and_disconnected_numeric_ids() {
975        let conn = setup_numeric_lineage_connection();
976
977        assert_eq!(
978            NumericLineage::get_path_between(&conn, &3, &3, None),
979            vec![3]
980        );
981        assert_eq!(
982            NumericLineage::get_path_between(&conn, &1, &6, None),
983            Vec::<i64>::new()
984        );
985        assert_eq!(
986            NumericLineage::get_path_edges_between(&conn, &1, &6, None),
987            Vec::<NumericLineage>::new()
988        );
989    }
990
991    #[test]
992    fn test_sql_lineage_hash_id_paths_decode_hex_tokens() {
993        let (conn, root, middle, leaf, other) = setup_hash_lineage_connection();
994
995        assert_eq!(
996            HashLineage::get_path_between(&conn, &root, &leaf, None),
997            vec![root, middle, leaf]
998        );
999        assert_eq!(
1000            HashLineage::get_path_edges_between(&conn, &root, &leaf, None),
1001            vec![
1002                HashLineage {
1003                    parent_id: root,
1004                    child_id: middle,
1005                },
1006                HashLineage {
1007                    parent_id: middle,
1008                    child_id: leaf,
1009                },
1010            ]
1011        );
1012        assert_eq!(
1013            HashLineage::get_path_between(&conn, &root, &other, None),
1014            Vec::<HashId>::new()
1015        );
1016    }
1017}