Skip to main content

gen_models/
sample_lineage.rs

1use gen_core::traits::Capnp;
2use rusqlite::{Result as SQLResult, Row, params};
3use serde::{Deserialize, Serialize};
4
5use crate::{
6    db::GraphConnection, gen_models_capnp::sample_lineage, lineage::SqlLineage, traits::Query,
7};
8
9#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
10pub struct SampleLineage {
11    pub parent_sample_name: String,
12    pub child_sample_name: String,
13}
14
15impl<'a> Capnp<'a> for SampleLineage {
16    type Builder = sample_lineage::Builder<'a>;
17    type Reader = sample_lineage::Reader<'a>;
18
19    fn write_capnp(&self, builder: &mut Self::Builder) {
20        builder.set_parent_sample_name(&self.parent_sample_name);
21        builder.set_child_sample_name(&self.child_sample_name);
22    }
23
24    fn read_capnp(reader: Self::Reader) -> Self {
25        let parent_sample_name = reader
26            .get_parent_sample_name()
27            .unwrap()
28            .to_string()
29            .unwrap();
30        let child_sample_name = reader.get_child_sample_name().unwrap().to_string().unwrap();
31
32        SampleLineage {
33            parent_sample_name,
34            child_sample_name,
35        }
36    }
37}
38
39impl Query for SampleLineage {
40    type Model = SampleLineage;
41
42    const PRIMARY_KEY: &'static str = "parent_sample_name";
43    const TABLE_NAME: &'static str = "sample_lineage";
44
45    fn process_row(row: &Row) -> Self::Model {
46        SampleLineage {
47            parent_sample_name: row.get(0).unwrap(),
48            child_sample_name: row.get(1).unwrap(),
49        }
50    }
51}
52
53impl SqlLineage for SampleLineage {
54    type Id = String;
55
56    const CHILD_COLUMN: &'static str = "child_sample_name";
57    const CHILD_ID_COLUMN: &'static str = "name";
58    const CHILD_TABLE_NAME: &'static str = "samples";
59    const PARENT_COLUMN: &'static str = "parent_sample_name";
60    const PARENT_ID_COLUMN: &'static str = "name";
61    const PARENT_TABLE_NAME: &'static str = "samples";
62
63    fn parent_id(&self) -> &Self::Id {
64        &self.parent_sample_name
65    }
66
67    fn child_id(&self) -> &Self::Id {
68        &self.child_sample_name
69    }
70}
71
72impl SampleLineage {
73    pub fn get_parents(conn: &GraphConnection, child_sample_name: &str) -> Vec<String> {
74        SampleLineage::query(
75            conn,
76            "SELECT * FROM sample_lineage WHERE child_sample_name = ?1 ORDER BY parent_sample_name;",
77            params![child_sample_name],
78        )
79        .into_iter()
80        .map(|lineage| lineage.parent_sample_name)
81        .collect()
82    }
83
84    pub fn get_children(conn: &GraphConnection, parent_sample_name: &str) -> Vec<String> {
85        SampleLineage::query(
86            conn,
87            "SELECT * FROM sample_lineage WHERE parent_sample_name = ?1 ORDER BY child_sample_name;",
88            params![parent_sample_name],
89        )
90        .into_iter()
91        .map(|lineage| lineage.child_sample_name)
92        .collect()
93    }
94
95    pub fn search_name(conn: &GraphConnection, name: &str) -> Vec<Self> {
96        SampleLineage::query(
97            conn,
98            "SELECT * FROM sample_lineage
99             WHERE instr(lower(parent_sample_name), lower(?1)) > 0
100                OR instr(lower(child_sample_name), lower(?1)) > 0
101             ORDER BY parent_sample_name, child_sample_name;",
102            params![name],
103        )
104    }
105
106    pub fn create(
107        conn: &GraphConnection,
108        parent_sample_name: &str,
109        child_sample_name: &str,
110    ) -> SQLResult<Self> {
111        let query = "INSERT INTO sample_lineage (parent_sample_name, child_sample_name)
112            VALUES (?1, ?2)
113            ON CONFLICT(parent_sample_name, child_sample_name) DO NOTHING;";
114        let mut stmt = conn.prepare(query).unwrap();
115        stmt.execute(params![parent_sample_name, child_sample_name])?;
116
117        Ok(SampleLineage {
118            parent_sample_name: parent_sample_name.to_string(),
119            child_sample_name: child_sample_name.to_string(),
120        })
121    }
122
123    pub fn delete(
124        conn: &GraphConnection,
125        parent_sample_name: &str,
126        child_sample_name: &str,
127    ) -> SQLResult<()> {
128        let query =
129            "DELETE FROM sample_lineage WHERE parent_sample_name = ?1 AND child_sample_name = ?2;";
130        let mut stmt = conn.prepare(query).unwrap();
131        stmt.execute(params![parent_sample_name, child_sample_name])?;
132        Ok(())
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use capnp::message::TypedBuilder;
139
140    use super::*;
141    use crate::{
142        lineage::SqlLineage,
143        sample::{NewSample, Sample},
144        test_helpers::get_connection,
145    };
146
147    #[test]
148    fn test_capnp_serialization() {
149        let lineage = SampleLineage {
150            parent_sample_name: "parent".to_string(),
151            child_sample_name: "child".to_string(),
152        };
153
154        let mut message = TypedBuilder::<sample_lineage::Owned>::new_default();
155        let mut root = message.init_root();
156        lineage.write_capnp(&mut root);
157
158        let deserialized = SampleLineage::read_capnp(root.into_reader());
159        assert_eq!(lineage, deserialized);
160    }
161
162    #[test]
163    fn test_lineage_queries() {
164        let conn = get_connection(None).unwrap();
165
166        for sample in ["root", "left", "right", "leaf", "sibling"] {
167            Sample::get_or_create(
168                &conn,
169                NewSample {
170                    name: sample,
171                    ..Default::default()
172                },
173            )
174            .unwrap();
175        }
176
177        SampleLineage::create(&conn, "root", "left").unwrap();
178        SampleLineage::create(&conn, "root", "right").unwrap();
179        SampleLineage::create(&conn, "left", "leaf").unwrap();
180        SampleLineage::create(&conn, "right", "leaf").unwrap();
181        SampleLineage::create(&conn, "right", "sibling").unwrap();
182
183        let ancestors = SampleLineage::get_ancestors(&conn, &"leaf".to_string(), None);
184        assert_eq!(ancestors, vec!["left", "right", "root"]);
185        assert_eq!(
186            SampleLineage::get_ancestors(&conn, &"leaf".to_string(), Some(1)),
187            vec!["left", "right"]
188        );
189        assert_eq!(
190            SampleLineage::get_ancestors(&conn, &"leaf".to_string(), Some(0)),
191            Vec::<String>::new()
192        );
193
194        assert_eq!(
195            SampleLineage::get_parents(&conn, "leaf"),
196            vec!["left".to_string(), "right".to_string()]
197        );
198        assert_eq!(
199            SampleLineage::get_children(&conn, "right"),
200            vec!["leaf".to_string(), "sibling".to_string()]
201        );
202
203        let descendants = SampleLineage::get_descendants(&conn, &"root".to_string(), None);
204        assert_eq!(descendants, vec!["left", "right", "leaf", "sibling"]);
205        assert_eq!(
206            SampleLineage::get_descendants(&conn, &"root".to_string(), Some(1)),
207            vec!["left", "right"]
208        );
209        assert_eq!(
210            SampleLineage::get_descendants(&conn, &"root".to_string(), Some(0)),
211            Vec::<String>::new()
212        );
213
214        let mut graph = SampleLineage::get_graph(&conn);
215        graph.sort_by(|left, right| {
216            left.parent_sample_name
217                .cmp(&right.parent_sample_name)
218                .then(left.child_sample_name.cmp(&right.child_sample_name))
219        });
220        assert_eq!(
221            graph,
222            vec![
223                SampleLineage {
224                    parent_sample_name: "left".to_string(),
225                    child_sample_name: "leaf".to_string(),
226                },
227                SampleLineage {
228                    parent_sample_name: "right".to_string(),
229                    child_sample_name: "leaf".to_string(),
230                },
231                SampleLineage {
232                    parent_sample_name: "right".to_string(),
233                    child_sample_name: "sibling".to_string(),
234                },
235                SampleLineage {
236                    parent_sample_name: "root".to_string(),
237                    child_sample_name: "left".to_string(),
238                },
239                SampleLineage {
240                    parent_sample_name: "root".to_string(),
241                    child_sample_name: "right".to_string(),
242                },
243            ]
244        );
245
246        let path =
247            SampleLineage::get_path_between(&conn, &"leaf".to_string(), &"sibling".to_string());
248        assert_eq!(path, vec!["leaf", "right", "sibling"]);
249
250        let edges = SampleLineage::get_path_edges_between(
251            &conn,
252            &"leaf".to_string(),
253            &"sibling".to_string(),
254        );
255        assert_eq!(
256            edges,
257            vec![
258                SampleLineage {
259                    parent_sample_name: "right".to_string(),
260                    child_sample_name: "leaf".to_string(),
261                },
262                SampleLineage {
263                    parent_sample_name: "right".to_string(),
264                    child_sample_name: "sibling".to_string(),
265                },
266            ]
267        );
268    }
269
270    #[test]
271    fn test_lineage_depth_limit() {
272        let conn = get_connection(None).unwrap();
273
274        for sample in ["root", "left", "right", "leaf", "sibling"] {
275            Sample::get_or_create(
276                &conn,
277                NewSample {
278                    name: sample,
279                    ..Default::default()
280                },
281            )
282            .unwrap();
283        }
284
285        SampleLineage::create(&conn, "root", "left").unwrap();
286        SampleLineage::create(&conn, "root", "right").unwrap();
287        SampleLineage::create(&conn, "left", "leaf").unwrap();
288        SampleLineage::create(&conn, "right", "leaf").unwrap();
289        SampleLineage::create(&conn, "right", "sibling").unwrap();
290
291        assert_eq!(
292            SampleLineage::get_ancestors(&conn, &"leaf".to_string(), Some(1)),
293            vec!["left", "right"]
294        );
295        assert_eq!(
296            SampleLineage::get_ancestors(&conn, &"leaf".to_string(), Some(2)),
297            vec!["left", "right", "root"]
298        );
299        assert_eq!(
300            SampleLineage::get_descendants(&conn, &"root".to_string(), Some(1)),
301            vec!["left", "right"]
302        );
303        assert_eq!(
304            SampleLineage::get_descendants(&conn, &"root".to_string(), Some(2)),
305            vec!["left", "right", "leaf", "sibling"]
306        );
307    }
308
309    #[test]
310    fn test_self_references_are_rejected() {
311        let conn = get_connection(None).unwrap();
312        Sample::get_or_create(
313            &conn,
314            NewSample {
315                name: "sample",
316                ..Default::default()
317            },
318        )
319        .unwrap();
320
321        let err = SampleLineage::create(&conn, "sample", "sample").unwrap_err();
322        assert!(matches!(
323            err,
324            rusqlite::Error::SqliteFailure(code, _)
325                if code.code == rusqlite::ErrorCode::ConstraintViolation
326        ));
327    }
328
329    #[test]
330    fn test_search_name_returns_partial_matches() {
331        let conn = get_connection(None).unwrap();
332
333        for sample in [
334            "alpha",
335            "BarFooBaz",
336            "child",
337            "foo",
338            "plain-parent",
339            "plain-child",
340            "QuxFood",
341            "zzz",
342        ] {
343            Sample::get_or_create(
344                &conn,
345                NewSample {
346                    name: sample,
347                    ..Default::default()
348                },
349            )
350            .unwrap();
351        }
352
353        SampleLineage::create(&conn, "alpha", "BarFooBaz").unwrap();
354        SampleLineage::create(&conn, "foo", "child").unwrap();
355        SampleLineage::create(&conn, "plain-parent", "plain-child").unwrap();
356        SampleLineage::create(&conn, "zzz", "QuxFood").unwrap();
357
358        let matches = SampleLineage::search_name(&conn, "FoO");
359
360        assert_eq!(
361            matches,
362            vec![
363                SampleLineage {
364                    parent_sample_name: "alpha".to_string(),
365                    child_sample_name: "BarFooBaz".to_string(),
366                },
367                SampleLineage {
368                    parent_sample_name: "foo".to_string(),
369                    child_sample_name: "child".to_string(),
370                },
371                SampleLineage {
372                    parent_sample_name: "zzz".to_string(),
373                    child_sample_name: "QuxFood".to_string(),
374                },
375            ]
376        );
377    }
378}