1use std::{collections::HashSet, rc::Rc};
2
3use gen_core::traits::Capnp;
4use gen_graph::GenGraph;
5use rusqlite::{Result as SQLResult, Row, params, types::Value as SQLValue};
6use serde::{Deserialize, Serialize};
7use thiserror::Error;
8
9use crate::{
10 block_group::BlockGroup,
11 db::GraphConnection,
12 errors::{BlockGroupError, QueryError},
13 gen_models_capnp::sample,
14 sample_lineage::SampleLineage,
15 traits::Query,
16};
17
18#[derive(Debug, Deserialize, Serialize, PartialEq)]
19pub struct Sample {
20 pub name: String,
21 pub is_reference: bool,
22}
23
24#[derive(Clone, Debug, Default)]
25pub struct NewSample<'a> {
26 pub name: &'a str,
27 pub is_reference: bool,
28}
29
30#[derive(Debug, Error, PartialEq)]
31pub enum SampleError {
32 #[error("Query Error: {0}")]
33 QueryError(#[from] QueryError),
34 #[error("SQLite Error: {0}")]
35 SqliteError(#[from] rusqlite::Error),
36 #[error("Sample already exists")]
37 Duplicate(Sample),
38 #[error("Sample not found: {0}")]
39 NotFound(String),
40 #[error("Sample is not a reference sample: {0}")]
41 NotReference(String),
42 #[error("Block group creation error: {0}")]
43 BlockGroup(#[from] BlockGroupError),
44}
45
46impl<'a> Capnp<'a> for Sample {
47 type Builder = sample::Builder<'a>;
48 type Reader = sample::Reader<'a>;
49
50 fn write_capnp(&self, builder: &mut Self::Builder) {
51 builder.set_name(&self.name);
52 builder.set_is_reference(self.is_reference);
53 }
54
55 fn read_capnp(reader: Self::Reader) -> Self {
56 let name = reader.get_name().unwrap().to_string().unwrap();
57 let is_reference = reader.get_is_reference();
58 Sample { name, is_reference }
59 }
60}
61
62impl Query for Sample {
63 type Model = Sample;
64
65 const PRIMARY_KEY: &'static str = "name";
66 const TABLE_NAME: &'static str = "samples";
67
68 fn process_row(row: &Row) -> Self::Model {
69 Sample {
70 name: row.get(0).unwrap(),
71 is_reference: row.get(1).unwrap(),
72 }
73 }
74}
75
76impl Sample {
77 pub const DEFAULT_NAME: &str = "reference";
78
79 pub fn get_parent_names(conn: &GraphConnection, sample_name: &str) -> Vec<String> {
80 SampleLineage::get_parents(conn, sample_name)
81 }
82
83 #[cfg_attr(
84 all(debug_assertions, feature = "profiling"),
85 tracing::instrument(skip(conn, new_sample))
86 )]
87 pub fn create(
88 conn: &GraphConnection,
89 new_sample: NewSample<'_>,
90 ) -> Result<Sample, SampleError> {
91 let mut stmt =
92 match conn.prepare("INSERT INTO samples (name, is_reference) VALUES (?1, ?2);") {
93 Ok(stmt) => stmt,
94 Err(err) => return Err(SampleError::SqliteError(err)),
95 };
96
97 match stmt.execute(params![new_sample.name, new_sample.is_reference]) {
98 Ok(_) => Ok(Sample {
99 name: new_sample.name.to_string(),
100 is_reference: new_sample.is_reference,
101 }),
102 Err(rusqlite::Error::SqliteFailure(e, _))
103 if e.code == rusqlite::ErrorCode::ConstraintViolation =>
104 {
105 Err(SampleError::Duplicate(Sample {
106 name: new_sample.name.to_string(),
107 is_reference: new_sample.is_reference,
108 }))
109 }
110 Err(err) => Err(SampleError::SqliteError(err)),
111 }
112 }
113
114 #[cfg_attr(
115 all(debug_assertions, feature = "profiling"),
116 tracing::instrument(skip(conn, new_sample))
117 )]
118 pub fn get_or_create(
119 conn: &GraphConnection,
120 new_sample: NewSample<'_>,
121 ) -> Result<Sample, SampleError> {
122 match Sample::create(conn, new_sample.clone()) {
123 Ok(sample) => Ok(sample),
124 Err(SampleError::Duplicate(sample)) => Ok(sample),
125 Err(e) => Err(e),
126 }
127 }
128
129 pub fn set_reference(
130 conn: &GraphConnection,
131 name: &str,
132 is_reference: bool,
133 ) -> Result<(), SampleError> {
134 conn.execute(
135 "UPDATE samples SET is_reference = ?2 WHERE name = ?1",
136 params![name, is_reference],
137 )?;
138 Ok(())
139 }
140
141 pub fn get_reference_samples(conn: &GraphConnection) -> Vec<Sample> {
142 Sample::query(
143 conn,
144 "select * from samples where is_reference = 1 order by name;",
145 params![],
146 )
147 }
148
149 pub fn get_sample_reference_block_groups(
150 conn: &GraphConnection,
151 collection_name: &str,
152 sample_name: &str,
153 ) -> Result<Vec<BlockGroup>, SampleError> {
154 let sample = Sample::get_by_name(conn, sample_name)
155 .map_err(|_| SampleError::NotFound(sample_name.to_string()))?;
156
157 if !sample.is_reference {
158 return Err(SampleError::NotReference(sample_name.to_string()));
159 }
160
161 Ok(Sample::get_block_groups(conn, collection_name, sample_name))
162 }
163
164 pub fn delete_by_name(conn: &GraphConnection, name: &str) {
165 let mut stmt = conn.prepare("delete from samples where name = ?1").unwrap();
166 stmt.execute([name]).unwrap();
167 }
168
169 pub fn get_graph(
170 conn: &GraphConnection,
171 collection: &str,
172 name: &str,
173 ) -> Result<GenGraph, SampleError> {
174 let block_groups = Sample::get_block_groups(conn, collection, name);
175 let mut sample_graph = GenGraph::new();
176 for bg in block_groups {
177 let bg_graph = BlockGroup::get_graph(conn, &bg.id)?;
178 for node in bg_graph.nodes() {
180 sample_graph.add_node(node);
181 }
182 for (source, dest, edges) in bg_graph.all_edges() {
183 if let Some(existing_edges) = sample_graph.edge_weight_mut(source, dest) {
184 existing_edges.extend(edges.clone());
185 } else {
186 sample_graph.add_edge(source, dest, edges.clone());
187 }
188 }
189 }
190 Ok(sample_graph)
191 }
192
193 pub fn get_all_sequences(
194 conn: &GraphConnection,
195 collection_name: &str,
196 sample_name: &str,
197 prune: bool,
198 ) -> Result<HashSet<String>, SampleError> {
199 let mut sequences = HashSet::new();
200 for block_group in Sample::get_block_groups(conn, collection_name, sample_name) {
201 sequences.extend(BlockGroup::get_all_sequences(conn, &block_group.id, prune)?);
202 }
203 Ok(sequences)
204 }
205
206 pub fn get_or_create_child(
207 conn: &GraphConnection,
208 collection_name: &str,
209 sample_name: &str,
210 parent_samples: Vec<String>,
211 ) -> Result<Sample, SampleError> {
212 match Sample::create(
213 conn,
214 NewSample {
215 name: sample_name,
216 is_reference: false,
217 },
218 ) {
219 Ok(new_sample) => {
220 if !parent_samples.is_empty() {
221 let parent_block_groups = BlockGroup::query(
222 conn,
223 "select * from block_groups
224 where collection_name = ?1 AND sample_name IN rarray(?2)
225 ORDER BY name, sample_name, created_on, id",
226 params![
227 collection_name,
228 Rc::new(
229 parent_samples
230 .iter()
231 .cloned()
232 .map(SQLValue::from)
233 .collect::<Vec<_>>()
234 ),
235 ],
236 );
237 let group_names = parent_block_groups
238 .into_iter()
239 .map(|parent_block_group| parent_block_group.name)
240 .collect::<HashSet<_>>();
241
242 for group_name in group_names {
243 BlockGroup::get_or_create_sample_block_groups(
244 conn,
245 collection_name,
246 &new_sample.name,
247 &group_name,
248 parent_samples.clone(),
249 )
250 .map_err(SampleError::from)?;
251 }
252
253 for parent_sample in parent_samples {
254 SampleLineage::create(conn, &parent_sample, &new_sample.name)
255 .map_err(SampleError::from)?;
256 }
257 }
258
259 Ok(new_sample)
260 }
261 Err(SampleError::Duplicate(sample)) => Ok(sample),
262 Err(e) => Err(e),
263 }
264 }
265
266 pub fn get_block_groups(
267 conn: &GraphConnection,
268 collection_name: &str,
269 sample_name: &str,
270 ) -> Vec<BlockGroup> {
271 BlockGroup::query(
272 conn,
273 "select * from block_groups where collection_name = ?1 AND sample_name = ?2;",
274 params![collection_name, sample_name],
275 )
276 }
277
278 pub fn get_all_names(conn: &GraphConnection) -> Vec<String> {
279 let samples = Sample::query(conn, "select * from samples;", rusqlite::params!());
280 samples.iter().map(|s| s.name.clone()).collect()
281 }
282
283 pub fn get_by_name(conn: &GraphConnection, name: &str) -> SQLResult<Sample> {
284 Sample::get(
285 conn,
286 "select * from samples where name = ?1;",
287 rusqlite::params!(name),
288 )
289 }
290
291 pub fn search_name(conn: &GraphConnection, name: &str) -> Vec<Sample> {
292 Sample::query(
293 conn,
294 "select * from samples
295 where instr(lower(name), lower(?1)) > 0
296 order by name;",
297 rusqlite::params!(name),
298 )
299 }
300}
301
302#[cfg(test)]
303mod tests {
304 use capnp::message::TypedBuilder;
305
306 use super::*;
307 use crate::{
308 collection::Collection,
309 errors::SampleError,
310 test_helpers::{create_bg, get_connection},
311 };
312
313 #[test]
314 fn test_capnp_serialization() {
315 let sample = Sample {
316 name: "test_sample".to_string(),
317 is_reference: true,
318 };
319
320 let mut message = TypedBuilder::<sample::Owned>::new_default();
321 let mut root = message.init_root();
322 sample.write_capnp(&mut root);
323
324 let deserialized = Sample::read_capnp(root.into_reader());
325 assert_eq!(sample, deserialized);
326 }
327
328 #[test]
329 fn test_delete_by_name() {
330 let conn = &get_connection(None).unwrap();
331
332 let _ = Sample::create(
333 conn,
334 NewSample {
335 name: "sample1",
336 is_reference: false,
337 },
338 )
339 .unwrap();
340 let _ = Sample::create(
341 conn,
342 NewSample {
343 name: "sample2",
344 is_reference: false,
345 },
346 )
347 .unwrap();
348
349 assert!(Sample::get_by_name(conn, "sample1").is_ok());
350 assert!(Sample::get_by_name(conn, "sample2").is_ok());
351
352 Sample::delete_by_name(conn, "sample1");
353
354 assert!(Sample::get_by_name(conn, "sample1").is_err());
355 assert!(Sample::get_by_name(conn, "sample2").is_ok());
356 }
357
358 #[test]
359 fn test_search_name_returns_partial_matches() {
360 let conn = &get_connection(None).unwrap();
361
362 for sample in ["alpha", "BarFooBaz", "foo", "QuxFood", "zzz"] {
363 Sample::create(
364 conn,
365 NewSample {
366 name: sample,
367 is_reference: false,
368 },
369 )
370 .unwrap();
371 }
372
373 let matches = Sample::search_name(conn, "FoO")
374 .into_iter()
375 .map(|sample| sample.name)
376 .collect::<Vec<_>>();
377
378 assert_eq!(matches, vec!["BarFooBaz", "QuxFood", "foo"]);
379 }
380
381 #[test]
382 fn test_get_or_create_child_does_not_add_lineage_for_existing_sample() {
383 let conn = &get_connection(None).unwrap();
384 Sample::get_or_create(
385 conn,
386 NewSample {
387 name: "parent",
388 ..Default::default()
389 },
390 )
391 .unwrap();
392 Sample::get_or_create(
393 conn,
394 NewSample {
395 name: "child",
396 ..Default::default()
397 },
398 )
399 .unwrap();
400
401 Sample::get_or_create_child(conn, "test", "child", vec!["parent".to_string()]).unwrap();
402
403 assert!(SampleLineage::get_parents(conn, "child").is_empty());
404 }
405
406 #[test]
407 fn test_get_or_create_child_returns_sample_error_for_invalid_lineage() {
408 let conn = &get_connection(None).unwrap();
409
410 let err = Sample::get_or_create_child(conn, "test", "child", vec!["child".to_string()])
411 .unwrap_err();
412
413 assert!(matches!(
414 err,
415 SampleError::SqliteError(rusqlite::Error::SqliteFailure(code, _))
416 if code.code == rusqlite::ErrorCode::ConstraintViolation
417 ));
418 }
419
420 #[test]
421 fn test_get_or_create_child_multiple_parents() {
422 let conn = &get_connection(None).unwrap();
423 Collection::create(conn, "test").unwrap();
424
425 create_bg(conn, "test", "parent_a", "chr1");
426 create_bg(conn, "test", "parent_a", "chr2");
427 create_bg(conn, "test", "parent_b", "chr2");
428 create_bg(conn, "test", "parent_c", "chr3");
429
430 let child = Sample::get_or_create_child(
431 conn,
432 "test",
433 "child",
434 vec![
435 "parent_a".to_string(),
436 "parent_b".to_string(),
437 "parent_c".to_string(),
438 ],
439 )
440 .unwrap();
441
442 let mut block_group_names = Sample::get_block_groups(conn, "test", &child.name)
443 .into_iter()
444 .map(|block_group| block_group.name)
445 .collect::<Vec<_>>();
446 block_group_names.sort();
447 assert_eq!(block_group_names, vec!["chr1", "chr2", "chr2", "chr3"]);
448 assert_eq!(
449 SampleLineage::get_parents(conn, &child.name),
450 vec![
451 "parent_a".to_string(),
452 "parent_b".to_string(),
453 "parent_c".to_string(),
454 ]
455 );
456 }
457
458 #[test]
459 fn test_get_reference_samples_returns_only_reference_samples() {
460 let conn = &get_connection(None).unwrap();
461 Sample::create(
462 conn,
463 NewSample {
464 name: "reference-a",
465 is_reference: true,
466 },
467 )
468 .unwrap();
469 Sample::create(
470 conn,
471 NewSample {
472 name: "sample-b",
473 is_reference: false,
474 },
475 )
476 .unwrap();
477 Sample::create(
478 conn,
479 NewSample {
480 name: "reference-c",
481 is_reference: true,
482 },
483 )
484 .unwrap();
485
486 let reference_names = Sample::get_reference_samples(conn)
487 .into_iter()
488 .map(|sample| sample.name)
489 .collect::<Vec<_>>();
490
491 assert_eq!(reference_names, vec!["reference-a", "reference-c"]);
492 }
493
494 #[test]
495 fn test_get_sample_reference_block_groups_returns_reference_block_groups() {
496 let conn = &get_connection(None).unwrap();
497 Collection::create(conn, "test").unwrap();
498
499 Sample::create(
500 conn,
501 NewSample {
502 name: "reference-root",
503 is_reference: true,
504 },
505 )
506 .unwrap();
507 create_bg(conn, "test", "reference-root", "chr1");
508 create_bg(conn, "test", "reference-root", "chr2");
509
510 let reference_block_group_names =
511 Sample::get_sample_reference_block_groups(conn, "test", "reference-root")
512 .unwrap()
513 .into_iter()
514 .map(|block_group| block_group.name)
515 .collect::<Vec<_>>();
516
517 assert_eq!(reference_block_group_names, vec!["chr1", "chr2"]);
518 }
519
520 #[test]
521 fn test_get_sample_reference_block_groups_errors_for_non_reference_sample() {
522 let conn = &get_connection(None).unwrap();
523 Collection::create(conn, "test").unwrap();
524 Sample::create(
525 conn,
526 NewSample {
527 name: "child",
528 is_reference: false,
529 },
530 )
531 .unwrap();
532
533 let err = Sample::get_sample_reference_block_groups(conn, "test", "child").unwrap_err();
534
535 assert_eq!(err, SampleError::NotReference("child".to_string()));
536 }
537
538 #[test]
539 fn test_get_sample_reference_block_groups_errors_for_missing_sample() {
540 let conn = &get_connection(None).unwrap();
541 Collection::create(conn, "test").unwrap();
542
543 let err = Sample::get_sample_reference_block_groups(conn, "test", "missing").unwrap_err();
544
545 assert_eq!(err, SampleError::NotFound("missing".to_string()));
546 }
547}