Skip to main content

gen_models/
sample_lineage.rs

1use gen_core::traits::Capnp;
2use rusqlite::{Result as SQLResult, Row, params, types::Value as SQLValue};
3use serde::{Deserialize, Serialize};
4
5use crate::{
6    Direction, ModelSelect,
7    db::GraphConnection,
8    gen_models_capnp::sample_lineage,
9    lineage::SqlLineage,
10    select::{ModelSelectRow, SqlFilter},
11};
12
13#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, ModelSelect)]
14#[model_select(
15    table = "sample_lineage",
16    default_sort(parent_sample_name = "asc", child_sample_name = "asc")
17)]
18pub struct SampleLineage {
19    #[model_select(primary_key)]
20    pub parent_sample_name: String,
21    #[model_select(primary_key)]
22    pub child_sample_name: String,
23}
24
25impl SampleLineageSelect<'_> {
26    pub fn name_contains(self, name: impl Into<String>) -> Self {
27        let name = name.into();
28        let parent_column = self.column("parent_sample_name");
29        let child_column = self.column("child_sample_name");
30        self.push_filter(SqlFilter::new(
31            format!(
32                "(instr(lower({parent_column}), lower(?)) > 0 OR \
33                 instr(lower({child_column}), lower(?)) > 0)"
34            ),
35            vec![SQLValue::from(name.clone()), SQLValue::from(name)],
36        ))
37    }
38}
39
40impl<'a> Capnp<'a> for SampleLineage {
41    type Builder = sample_lineage::Builder<'a>;
42    type Reader = sample_lineage::Reader<'a>;
43
44    fn write_capnp(&self, builder: &mut Self::Builder) {
45        builder.set_parent_sample_name(&self.parent_sample_name);
46        builder.set_child_sample_name(&self.child_sample_name);
47    }
48
49    fn read_capnp(reader: Self::Reader) -> Self {
50        let parent_sample_name = reader
51            .get_parent_sample_name()
52            .unwrap()
53            .to_string()
54            .unwrap();
55        let child_sample_name = reader.get_child_sample_name().unwrap().to_string().unwrap();
56
57        SampleLineage {
58            parent_sample_name,
59            child_sample_name,
60        }
61    }
62}
63
64impl SqlLineage for SampleLineage {
65    type Id = String;
66
67    const CHILD_COLUMN: &'static str = "child_sample_name";
68    const CHILD_ID_COLUMN: &'static str = "name";
69    const CHILD_TABLE_NAME: &'static str = "samples";
70    const PARENT_COLUMN: &'static str = "parent_sample_name";
71    const PARENT_ID_COLUMN: &'static str = "name";
72    const PARENT_TABLE_NAME: &'static str = "samples";
73    const TABLE_NAME: &'static str = "sample_lineage";
74
75    fn parent_id(&self) -> &Self::Id {
76        &self.parent_sample_name
77    }
78
79    fn child_id(&self) -> &Self::Id {
80        &self.child_sample_name
81    }
82
83    fn process_row(row: &Row) -> rusqlite::Result<Self> {
84        <Self as ModelSelectRow>::process_row(row)
85    }
86}
87
88impl SampleLineage {
89    pub fn get_parents(
90        conn: &GraphConnection,
91        child_sample_name: &str,
92        history_ref: Option<&str>,
93    ) -> Vec<String> {
94        let select = SampleLineage::select(conn)
95            .child_sample_name(child_sample_name)
96            .order_by(SampleLineageSelect::ParentSampleName, Direction::Asc)
97            .with_ref(history_ref);
98        select
99            .load()
100            .expect("should load parent sample lineage")
101            .into_iter()
102            .map(|lineage| lineage.parent_sample_name)
103            .collect()
104    }
105
106    pub fn get_children(
107        conn: &GraphConnection,
108        parent_sample_name: &str,
109        history_ref: Option<&str>,
110    ) -> Vec<String> {
111        let select = SampleLineage::select(conn)
112            .parent_sample_name(parent_sample_name)
113            .order_by(SampleLineageSelect::ChildSampleName, Direction::Asc)
114            .with_ref(history_ref);
115        select
116            .load()
117            .expect("should load child sample lineage")
118            .into_iter()
119            .map(|lineage| lineage.child_sample_name)
120            .collect()
121    }
122
123    pub fn create(
124        conn: &GraphConnection,
125        parent_sample_name: &str,
126        child_sample_name: &str,
127    ) -> SQLResult<Self> {
128        let query = "INSERT INTO sample_lineage (parent_sample_name, child_sample_name)
129            VALUES (?1, ?2)
130            ON CONFLICT(parent_sample_name, child_sample_name) DO NOTHING;";
131        let mut stmt = conn.prepare(query).unwrap();
132        stmt.execute(params![parent_sample_name, child_sample_name])?;
133
134        Ok(SampleLineage {
135            parent_sample_name: parent_sample_name.to_string(),
136            child_sample_name: child_sample_name.to_string(),
137        })
138    }
139
140    pub fn delete(
141        conn: &GraphConnection,
142        parent_sample_name: &str,
143        child_sample_name: &str,
144    ) -> SQLResult<()> {
145        let query =
146            "DELETE FROM sample_lineage WHERE parent_sample_name = ?1 AND child_sample_name = ?2;";
147        let mut stmt = conn.prepare(query).unwrap();
148        stmt.execute(params![parent_sample_name, child_sample_name])?;
149        Ok(())
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use capnp::message::TypedBuilder;
156
157    use super::*;
158    use crate::{
159        history::dolt::{checkout, commit_all, create_branch},
160        lineage::SqlLineage,
161        sample::{NewSample, Sample},
162        test_helpers::get_connection,
163    };
164
165    #[test]
166    fn test_capnp_serialization() {
167        let lineage = SampleLineage {
168            parent_sample_name: "parent".to_string(),
169            child_sample_name: "child".to_string(),
170        };
171
172        let mut message = TypedBuilder::<sample_lineage::Owned>::new_default();
173        let mut root = message.init_root();
174        lineage.write_capnp(&mut root);
175
176        let deserialized = SampleLineage::read_capnp(root.into_reader());
177        assert_eq!(lineage, deserialized);
178    }
179
180    #[test]
181    fn test_lineage_queries() {
182        let conn = get_connection(None).unwrap();
183
184        for sample in ["root", "left", "right", "leaf", "sibling"] {
185            Sample::get_or_create(
186                &conn,
187                NewSample {
188                    name: sample,
189                    ..Default::default()
190                },
191            )
192            .unwrap();
193        }
194
195        SampleLineage::create(&conn, "root", "left").unwrap();
196        SampleLineage::create(&conn, "root", "right").unwrap();
197        SampleLineage::create(&conn, "left", "leaf").unwrap();
198        SampleLineage::create(&conn, "right", "leaf").unwrap();
199        SampleLineage::create(&conn, "right", "sibling").unwrap();
200
201        let ancestors = SampleLineage::get_ancestors(&conn, &"leaf".to_string(), None, None);
202        assert_eq!(ancestors, vec!["left", "right", "root"]);
203        assert_eq!(
204            SampleLineage::get_ancestors(&conn, &"leaf".to_string(), Some(1), None),
205            vec!["left", "right"]
206        );
207        assert_eq!(
208            SampleLineage::get_ancestors(&conn, &"leaf".to_string(), Some(0), None),
209            Vec::<String>::new()
210        );
211
212        assert_eq!(
213            SampleLineage::get_parents(&conn, "leaf", None),
214            vec!["left".to_string(), "right".to_string()]
215        );
216        assert_eq!(
217            SampleLineage::get_children(&conn, "right", None),
218            vec!["leaf".to_string(), "sibling".to_string()]
219        );
220
221        let descendants = SampleLineage::get_descendants(&conn, &"root".to_string(), None, None);
222        assert_eq!(descendants, vec!["left", "right", "leaf", "sibling"]);
223        assert_eq!(
224            SampleLineage::get_descendants(&conn, &"root".to_string(), Some(1), None),
225            vec!["left", "right"]
226        );
227        assert_eq!(
228            SampleLineage::get_descendants(&conn, &"root".to_string(), Some(0), None),
229            Vec::<String>::new()
230        );
231
232        let mut graph = SampleLineage::get_graph(&conn, None);
233        graph.sort_by(|left, right| {
234            left.parent_sample_name
235                .cmp(&right.parent_sample_name)
236                .then(left.child_sample_name.cmp(&right.child_sample_name))
237        });
238        assert_eq!(
239            graph,
240            vec![
241                SampleLineage {
242                    parent_sample_name: "left".to_string(),
243                    child_sample_name: "leaf".to_string(),
244                },
245                SampleLineage {
246                    parent_sample_name: "right".to_string(),
247                    child_sample_name: "leaf".to_string(),
248                },
249                SampleLineage {
250                    parent_sample_name: "right".to_string(),
251                    child_sample_name: "sibling".to_string(),
252                },
253                SampleLineage {
254                    parent_sample_name: "root".to_string(),
255                    child_sample_name: "left".to_string(),
256                },
257                SampleLineage {
258                    parent_sample_name: "root".to_string(),
259                    child_sample_name: "right".to_string(),
260                },
261            ]
262        );
263
264        let path = SampleLineage::get_path_between(
265            &conn,
266            &"leaf".to_string(),
267            &"sibling".to_string(),
268            None,
269        );
270        assert_eq!(path, vec!["leaf", "right", "sibling"]);
271
272        let edges = SampleLineage::get_path_edges_between(
273            &conn,
274            &"leaf".to_string(),
275            &"sibling".to_string(),
276            None,
277        );
278        assert_eq!(
279            edges,
280            vec![
281                SampleLineage {
282                    parent_sample_name: "right".to_string(),
283                    child_sample_name: "leaf".to_string(),
284                },
285                SampleLineage {
286                    parent_sample_name: "right".to_string(),
287                    child_sample_name: "sibling".to_string(),
288                },
289            ]
290        );
291    }
292
293    #[test]
294    fn test_lineage_depth_limit() {
295        let conn = get_connection(None).unwrap();
296
297        for sample in ["root", "left", "right", "leaf", "sibling"] {
298            Sample::get_or_create(
299                &conn,
300                NewSample {
301                    name: sample,
302                    ..Default::default()
303                },
304            )
305            .unwrap();
306        }
307
308        SampleLineage::create(&conn, "root", "left").unwrap();
309        SampleLineage::create(&conn, "root", "right").unwrap();
310        SampleLineage::create(&conn, "left", "leaf").unwrap();
311        SampleLineage::create(&conn, "right", "leaf").unwrap();
312        SampleLineage::create(&conn, "right", "sibling").unwrap();
313
314        assert_eq!(
315            SampleLineage::get_ancestors(&conn, &"leaf".to_string(), Some(1), None),
316            vec!["left", "right"]
317        );
318        assert_eq!(
319            SampleLineage::get_ancestors(&conn, &"leaf".to_string(), Some(2), None),
320            vec!["left", "right", "root"]
321        );
322        assert_eq!(
323            SampleLineage::get_descendants(&conn, &"root".to_string(), Some(1), None),
324            vec!["left", "right"]
325        );
326        assert_eq!(
327            SampleLineage::get_descendants(&conn, &"root".to_string(), Some(2), None),
328            vec!["left", "right", "leaf", "sibling"]
329        );
330    }
331
332    #[test]
333    fn test_get_ancestors_respects_history_ref() {
334        let conn = get_connection(None).unwrap();
335        for sample in ["grand", "parent", "child"] {
336            Sample::get_or_create(
337                &conn,
338                NewSample {
339                    name: sample,
340                    ..Default::default()
341                },
342            )
343            .unwrap();
344        }
345        SampleLineage::create(&conn, "parent", "child").unwrap();
346        let base = commit_all(&conn, "parent lineage").unwrap();
347        SampleLineage::create(&conn, "grand", "parent").unwrap();
348
349        assert_eq!(
350            SampleLineage::get_ancestors(&conn, &"child".to_string(), None, None),
351            vec!["parent", "grand"]
352        );
353        assert_eq!(
354            SampleLineage::get_ancestors(
355                &conn,
356                &"child".to_string(),
357                None,
358                Some(&base.to_string()),
359            ),
360            vec!["parent"]
361        );
362        let historical_ancestors = SampleLineage::get_ancestors_page(
363            &conn,
364            &"child".to_string(),
365            None,
366            10,
367            0,
368            Some(&base.to_string()),
369        );
370        assert_eq!(historical_ancestors.ids, vec!["parent".to_string()]);
371        assert!(!historical_ancestors.has_more);
372        let current_ancestors =
373            SampleLineage::get_ancestors_page(&conn, &"child".to_string(), None, 10, 0, None);
374        assert_eq!(
375            current_ancestors.ids,
376            vec!["parent".to_string(), "grand".to_string()]
377        );
378        assert!(!current_ancestors.has_more);
379        assert_eq!(
380            SampleLineage::get_parents(&conn, "parent", None),
381            vec!["grand"]
382        );
383        assert!(SampleLineage::get_parents(&conn, "parent", Some(&base.to_string())).is_empty());
384    }
385
386    #[test]
387    fn test_lineage_queries_respect_history_and_branches() {
388        // The base snapshot is root -> child -> leaf.
389        // The alternate branch deletes child -> leaf and leaf, then adds root -> later.
390        // The queries compare current state with commit and branch refs before and after checkout.
391        let conn = get_connection(None).unwrap();
392        for name in ["root", "child", "leaf"] {
393            Sample::get_or_create(
394                &conn,
395                NewSample {
396                    name,
397                    ..Default::default()
398                },
399            )
400            .expect("should create sample");
401        }
402        SampleLineage::create(&conn, "root", "child").expect("should create lineage");
403        SampleLineage::create(&conn, "child", "leaf").expect("should create lineage");
404        let base = commit_all(&conn, "base lineage")
405            .expect("should commit lineage")
406            .to_string();
407        create_branch(&conn, "lineage-base").expect("should create branch");
408        create_branch(&conn, "lineage-alternate").expect("should create branch");
409        checkout(&conn, "lineage-alternate").expect("should checkout branch");
410        SampleLineage::delete(&conn, "child", "leaf").expect("should delete lineage");
411        Sample::delete_by_name(&conn, "leaf");
412        Sample::get_or_create(
413            &conn,
414            NewSample {
415                name: "later",
416                ..Default::default()
417            },
418        )
419        .expect("should create later sample");
420        SampleLineage::create(&conn, "root", "later").expect("should create later lineage");
421        commit_all(&conn, "alternate lineage").expect("should commit alternate lineage");
422
423        let root = "root".to_string();
424        assert_eq!(
425            SampleLineage::get_descendants(&conn, &root, None, None),
426            vec!["child", "later"]
427        );
428        assert_eq!(
429            SampleLineage::get_descendants(&conn, &root, None, Some(&base)),
430            vec!["child", "leaf"]
431        );
432        let historical_roots = SampleLineage::get_roots_page(&conn, 10, 0, Some(&base));
433        assert_eq!(historical_roots.ids, vec!["root"]);
434        assert!(!historical_roots.has_more);
435        let historical_children =
436            SampleLineage::get_children_page(&conn, &root, 10, 0, Some(&base));
437        assert_eq!(historical_children.ids, vec!["child"]);
438        assert!(!historical_children.has_more);
439        let historical_descendants =
440            SampleLineage::get_descendants_page(&conn, &root, None, 1, 0, Some(&base));
441        assert_eq!(historical_descendants.ids, vec!["child".to_string()]);
442        assert!(historical_descendants.has_more);
443        let historical_descendants =
444            SampleLineage::get_descendants_page(&conn, &root, None, 1, 1, Some(&base));
445        assert_eq!(historical_descendants.ids, vec!["leaf".to_string()]);
446        assert!(!historical_descendants.has_more);
447        assert_eq!(
448            SampleLineage::get_descendants(&conn, &root, None, Some("lineage-base")),
449            vec!["child", "leaf"]
450        );
451        assert_eq!(
452            SampleLineage::get_descendants(&conn, &root, Some(1), Some(&base)),
453            vec!["child"]
454        );
455        assert!(SampleLineage::get_descendants(&conn, &root, Some(0), Some(&base)).is_empty());
456
457        let sort_graph = |graph: &mut Vec<SampleLineage>| {
458            graph.sort_by(|left, right| {
459                left.parent_sample_name
460                    .cmp(&right.parent_sample_name)
461                    .then(left.child_sample_name.cmp(&right.child_sample_name))
462            });
463        };
464        let mut current_graph = SampleLineage::get_graph(&conn, None);
465        sort_graph(&mut current_graph);
466        assert_eq!(
467            current_graph,
468            vec![
469                SampleLineage {
470                    parent_sample_name: "root".to_string(),
471                    child_sample_name: "child".to_string(),
472                },
473                SampleLineage {
474                    parent_sample_name: "root".to_string(),
475                    child_sample_name: "later".to_string(),
476                },
477            ]
478        );
479        let mut base_graph = SampleLineage::get_graph(&conn, Some(&base));
480        sort_graph(&mut base_graph);
481        assert_eq!(
482            base_graph,
483            vec![
484                SampleLineage {
485                    parent_sample_name: "child".to_string(),
486                    child_sample_name: "leaf".to_string(),
487                },
488                SampleLineage {
489                    parent_sample_name: "root".to_string(),
490                    child_sample_name: "child".to_string(),
491                },
492            ]
493        );
494        assert_eq!(
495            SampleLineage::get_path_between(&conn, &root, &"leaf".to_string(), None),
496            Vec::<String>::new()
497        );
498        assert_eq!(
499            SampleLineage::get_path_between(&conn, &root, &"leaf".to_string(), Some(&base)),
500            vec!["root", "child", "leaf"]
501        );
502        assert_eq!(
503            SampleLineage::get_path_edges_between(&conn, &root, &"leaf".to_string(), Some(&base)),
504            vec![
505                SampleLineage {
506                    parent_sample_name: "root".to_string(),
507                    child_sample_name: "child".to_string(),
508                },
509                SampleLineage {
510                    parent_sample_name: "child".to_string(),
511                    child_sample_name: "leaf".to_string(),
512                },
513            ]
514        );
515        checkout(&conn, "lineage-base").expect("should checkout base branch");
516        assert_eq!(
517            SampleLineage::get_descendants(&conn, &root, None, Some("lineage-alternate")),
518            vec!["child", "later"]
519        );
520        let mut alternate_graph = SampleLineage::get_graph(&conn, Some("lineage-alternate"));
521        sort_graph(&mut alternate_graph);
522        assert_eq!(alternate_graph, current_graph);
523        assert_eq!(
524            SampleLineage::get_path_between(
525                &conn,
526                &root,
527                &"later".to_string(),
528                Some("lineage-alternate"),
529            ),
530            vec!["root", "later"]
531        );
532        assert_eq!(
533            SampleLineage::get_path_edges_between(
534                &conn,
535                &root,
536                &"later".to_string(),
537                Some("lineage-alternate"),
538            ),
539            vec![SampleLineage {
540                parent_sample_name: "root".to_string(),
541                child_sample_name: "later".to_string(),
542            }]
543        );
544    }
545
546    #[test]
547    fn test_get_descendants_fetches_five_levels_at_history_ref() {
548        // The committed fixture is the chain root -> one -> two -> three -> four -> five -> six.
549        // The historical reads below check the five-edge cutoff and unlimited traversal.
550        let conn = get_connection(None).unwrap();
551        let names = ["root", "one", "two", "three", "four", "five", "six"];
552        for name in names {
553            Sample::get_or_create(
554                &conn,
555                NewSample {
556                    name,
557                    ..Default::default()
558                },
559            )
560            .expect("should create sample");
561        }
562        for pair in names.windows(2) {
563            SampleLineage::create(&conn, pair[0], pair[1]).expect("should create lineage");
564        }
565        let history = commit_all(&conn, "deep lineage")
566            .expect("should commit lineage")
567            .to_string();
568        let root = "root".to_string();
569        assert_eq!(
570            SampleLineage::get_descendants(&conn, &root, Some(5), Some(&history)),
571            vec!["one", "two", "three", "four", "five"]
572        );
573        assert_eq!(
574            SampleLineage::get_descendants(&conn, &root, None, Some(&history)),
575            vec!["one", "two", "three", "four", "five", "six"]
576        );
577    }
578
579    #[test]
580    fn test_self_references_are_rejected() {
581        let conn = get_connection(None).unwrap();
582        Sample::get_or_create(
583            &conn,
584            NewSample {
585                name: "sample",
586                ..Default::default()
587            },
588        )
589        .unwrap();
590
591        let err = SampleLineage::create(&conn, "sample", "sample").unwrap_err();
592        assert!(matches!(
593            err,
594            rusqlite::Error::SqliteFailure(code, _)
595                if code.code == rusqlite::ErrorCode::ConstraintViolation
596        ));
597    }
598
599    #[test]
600    fn test_search_name_returns_partial_matches() {
601        let conn = get_connection(None).unwrap();
602
603        for sample in [
604            "alpha",
605            "BarFooBaz",
606            "child",
607            "foo",
608            "plain-parent",
609            "plain-child",
610            "QuxFood",
611            "zzz",
612        ] {
613            Sample::get_or_create(
614                &conn,
615                NewSample {
616                    name: sample,
617                    ..Default::default()
618                },
619            )
620            .unwrap();
621        }
622
623        SampleLineage::create(&conn, "alpha", "BarFooBaz").unwrap();
624        SampleLineage::create(&conn, "foo", "child").unwrap();
625        SampleLineage::create(&conn, "plain-parent", "plain-child").unwrap();
626        SampleLineage::create(&conn, "zzz", "QuxFood").unwrap();
627
628        let matches = SampleLineage::select(&conn)
629            .name_contains("FoO")
630            .order_by(SampleLineageSelect::ParentSampleName, Direction::Asc)
631            .order_by(SampleLineageSelect::ChildSampleName, Direction::Asc)
632            .load()
633            .expect("should load matching sample lineage");
634
635        assert_eq!(
636            matches,
637            vec![
638                SampleLineage {
639                    parent_sample_name: "alpha".to_string(),
640                    child_sample_name: "BarFooBaz".to_string(),
641                },
642                SampleLineage {
643                    parent_sample_name: "foo".to_string(),
644                    child_sample_name: "child".to_string(),
645                },
646                SampleLineage {
647                    parent_sample_name: "zzz".to_string(),
648                    child_sample_name: "QuxFood".to_string(),
649                },
650            ]
651        );
652
653        let limited_matches = SampleLineage::select(&conn)
654            .name_contains("FoO")
655            .order_by(SampleLineageSelect::ChildSampleName, Direction::Desc)
656            .order_by(SampleLineageSelect::ParentSampleName, Direction::Desc)
657            .limit(2)
658            .load()
659            .expect("should load limited sample lineage");
660
661        assert_eq!(
662            limited_matches,
663            vec![
664                SampleLineage {
665                    parent_sample_name: "foo".to_string(),
666                    child_sample_name: "child".to_string(),
667                },
668                SampleLineage {
669                    parent_sample_name: "zzz".to_string(),
670                    child_sample_name: "QuxFood".to_string(),
671                },
672            ]
673        );
674    }
675
676    #[test]
677    fn test_search_supports_sort_and_pagination() {
678        let conn = get_connection(None).unwrap();
679
680        for sample in ["alpha", "beta", "child-a", "child-b", "foo", "zzz"] {
681            Sample::get_or_create(
682                &conn,
683                NewSample {
684                    name: sample,
685                    ..Default::default()
686                },
687            )
688            .unwrap();
689        }
690
691        SampleLineage::create(&conn, "alpha", "child-a").unwrap();
692        SampleLineage::create(&conn, "foo", "child-b").unwrap();
693        SampleLineage::create(&conn, "zzz", "beta").unwrap();
694
695        let matches = SampleLineage::select(&conn)
696            .name_contains("a")
697            .order_by(SampleLineageSelect::ChildSampleName, Direction::Desc)
698            .order_by(SampleLineageSelect::ParentSampleName, Direction::Desc)
699            .limit(2)
700            .offset(1)
701            .load()
702            .expect("should load paginated sample lineage");
703
704        assert_eq!(
705            matches,
706            vec![SampleLineage {
707                parent_sample_name: "zzz".to_string(),
708                child_sample_name: "beta".to_string(),
709            }]
710        );
711    }
712}