Skip to main content

gen_models/
annotations.rs

1use std::{
2    collections::HashMap,
3    path::{Path, PathBuf},
4    rc::Rc,
5};
6
7use anyhow::anyhow;
8use gen_core::{
9    HashId, NodeIntervalBlock, calculate_hash,
10    config::Workspace,
11    region::{Region, RegionResolutionError, RegionResolver},
12    traits::Capnp,
13};
14use intervaltree::IntervalTree;
15use rusqlite::{Row, params, types::Value};
16use serde::{Deserialize, Serialize};
17use thiserror::Error;
18
19use crate::{
20    accession::{Accession, AccessionError, AccessionSpan, NewAccession},
21    changesets::{ChangesetModels, DatabaseChangeset, write_changeset},
22    db::{DbContext, GraphConnection, OperationsConnection},
23    errors::{FileAdditionError, OperationError},
24    file_types::FileTypes,
25    files::GenDatabase,
26    gen_models_capnp::{annotation, annotation_group, annotation_group_sample},
27    metadata,
28    operations::{FileAddition, Operation, OperationInfo, OperationSummary},
29    session_operations::{DependencyModels, end_operation, start_operation},
30    traits::Query,
31};
32
33#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
34pub struct AnnotationGroup {
35    pub name: String,
36}
37
38impl Query for AnnotationGroup {
39    type Model = AnnotationGroup;
40
41    const PRIMARY_KEY: &'static str = "name";
42    const TABLE_NAME: &'static str = "annotation_groups";
43
44    fn process_row(row: &Row) -> Self::Model {
45        AnnotationGroup {
46            name: row.get(0).unwrap(),
47        }
48    }
49}
50
51impl AnnotationGroup {
52    pub fn create(conn: &GraphConnection, name: &str) -> rusqlite::Result<AnnotationGroup> {
53        let mut stmt = conn
54            .prepare("INSERT INTO annotation_groups (name) VALUES (?1) returning (name);")
55            .unwrap();
56        stmt.query_row((name,), |row| Ok(AnnotationGroup { name: row.get(0)? }))
57    }
58
59    pub fn get_or_create(
60        conn: &GraphConnection,
61        name: &str,
62    ) -> Result<AnnotationGroup, AnnotationGroupError> {
63        match AnnotationGroup::create(conn, name) {
64            Ok(group) => Ok(group),
65            Err(rusqlite::Error::SqliteFailure(err, _details))
66                if err.code == rusqlite::ErrorCode::ConstraintViolation =>
67            {
68                AnnotationGroup::get_by_id(conn, &name.to_string())
69                    .ok_or_else(|| rusqlite::Error::QueryReturnedNoRows.into())
70            }
71            Err(err) => Err(err.into()),
72        }
73    }
74
75    pub fn query_by_sample(conn: &GraphConnection, sample_name: &str) -> Vec<AnnotationGroup> {
76        let query = "\
77            select ag.* \
78            from annotation_groups ag \
79            join annotation_group_samples s \
80                on ag.name = s.annotation_group \
81            where s.sample_name = ?1 \
82            order by ag.name;";
83        AnnotationGroup::query(conn, query, params![sample_name])
84    }
85}
86
87impl<'a> Capnp<'a> for AnnotationGroup {
88    type Builder = annotation_group::Builder<'a>;
89    type Reader = annotation_group::Reader<'a>;
90
91    fn write_capnp(&self, builder: &mut Self::Builder) {
92        builder.set_name(&self.name);
93    }
94
95    fn read_capnp(reader: Self::Reader) -> Self {
96        AnnotationGroup {
97            name: reader.get_name().unwrap().to_string().unwrap(),
98        }
99    }
100}
101
102#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
103pub struct Annotation {
104    pub id: HashId,
105    pub name: String,
106    pub group: String,
107    pub accession_id: HashId,
108    pub extra: Option<AnnotationExtra>,
109}
110
111#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
112#[serde(default)]
113pub struct AnnotationExtra {
114    pub genbank: Option<GenBankExtra>,
115    pub gff: Option<GffExtra>,
116    pub bed: Option<BedExtra>,
117}
118
119#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
120#[serde(default)]
121pub struct GenBankExtra {
122    pub kind: String,
123    pub qualifiers: Vec<GenBankQualifier>,
124    pub location_operator: Option<GenBankLocationOperator>,
125}
126
127#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
128#[serde(default)]
129pub struct GenBankQualifier {
130    pub key: String,
131    pub value: Option<String>,
132}
133
134#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
135pub enum GenBankLocationOperator {
136    Join,
137    Order,
138    Bond,
139    OneOf,
140}
141
142#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
143#[serde(default)]
144pub struct GffExtra {
145    pub source: Option<String>,
146    pub ty: String,
147    pub score: Option<String>,
148    pub phase: Option<String>,
149    pub attributes: Vec<GffAttribute>,
150}
151
152#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
153#[serde(default)]
154pub struct GffAttribute {
155    pub key: String,
156    pub values: Vec<String>,
157}
158
159#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
160#[serde(default)]
161pub struct BedExtra {
162    pub score: Option<String>,
163    pub thick_start: Option<i64>,
164    pub thick_end: Option<i64>,
165    pub item_rgb: Option<String>,
166    pub block_count: Option<u64>,
167    pub block_sizes: Option<Vec<i64>>,
168    pub block_starts: Option<Vec<i64>>,
169    pub other_fields: Vec<String>,
170}
171
172fn serialize_annotation_extra(extra: Option<&AnnotationExtra>) -> Result<String, AnnotationError> {
173    serde_json::to_string(extra.unwrap_or(&AnnotationExtra::default()))
174        .map_err(|err| AnnotationError::SerializationError(err.to_string()))
175}
176
177fn deserialize_annotation_extra(
178    value: Option<String>,
179) -> Result<Option<AnnotationExtra>, AnnotationError> {
180    value
181        .map(|value| serde_json::from_str(&value))
182        .transpose()
183        .map(|value| value.filter(|extra| extra != &AnnotationExtra::default()))
184        .map_err(|err| AnnotationError::SerializationError(err.to_string()))
185}
186
187impl<'a> Capnp<'a> for Annotation {
188    type Builder = annotation::Builder<'a>;
189    type Reader = annotation::Reader<'a>;
190
191    fn write_capnp(&self, builder: &mut Self::Builder) {
192        builder.set_id(&self.id.0).unwrap();
193        builder.set_name(&self.name);
194        builder.set_annotation_group(&self.group);
195        builder.set_accession_id(&self.accession_id.0).unwrap();
196        builder.set_extra(
197            serialize_annotation_extra(self.extra.as_ref())
198                .unwrap_or_default()
199                .as_str(),
200        );
201    }
202
203    fn read_capnp(reader: Self::Reader) -> Self {
204        let id = reader
205            .get_id()
206            .unwrap()
207            .as_slice()
208            .unwrap()
209            .try_into()
210            .unwrap();
211        let name = reader.get_name().unwrap().to_string().unwrap();
212        let group = reader.get_annotation_group().unwrap().to_string().unwrap();
213        let accession_id = reader
214            .get_accession_id()
215            .unwrap()
216            .as_slice()
217            .unwrap()
218            .try_into()
219            .unwrap();
220        let extra = deserialize_annotation_extra(
221            reader
222                .get_extra()
223                .ok()
224                .map(|value| value.to_string().unwrap())
225                .filter(|value| !value.is_empty()),
226        )
227        .unwrap_or(None);
228
229        Annotation {
230            id,
231            name,
232            group,
233            accession_id,
234            extra,
235        }
236    }
237}
238
239impl Query for Annotation {
240    type Model = Annotation;
241
242    const TABLE_NAME: &'static str = "annotations";
243
244    fn process_row(row: &Row) -> Self::Model {
245        Annotation {
246            id: row.get(0).unwrap(),
247            name: row.get(1).unwrap(),
248            group: row.get(2).unwrap(),
249            accession_id: row.get(3).unwrap(),
250            extra: deserialize_annotation_extra(row.get(4).unwrap())
251                .expect("should deserialize annotation extra from database"),
252        }
253    }
254}
255
256#[derive(Debug, Error, PartialEq)]
257pub enum AnnotationError {
258    #[error("Database error: {0}")]
259    DatabaseError(#[from] rusqlite::Error),
260    #[error("Annotation group error: {0}")]
261    AnnotationGroupError(#[from] AnnotationGroupError),
262    #[error("Accession error: {0}")]
263    AccessionError(#[from] AccessionError),
264    #[error("Annotation extra serialization error: {0}")]
265    SerializationError(String),
266}
267
268impl Annotation {
269    pub fn generate_id(name: &str, group: &str, accession_id: &HashId) -> HashId {
270        HashId(calculate_hash(&format!("{name}:{group}:{accession_id}",)))
271    }
272
273    pub fn create(
274        conn: &GraphConnection,
275        name: &str,
276        group: &str,
277        accession_id: &HashId,
278        extra: Option<&AnnotationExtra>,
279    ) -> Result<Annotation, AnnotationError> {
280        let id = Annotation::generate_id(name, group, accession_id);
281        let query = "INSERT INTO annotations (id, name, annotation_group, accession_id, extra) VALUES (?1, ?2, ?3, ?4, ?5);";
282        let mut stmt = conn.prepare(query)?;
283        let extra_json = serialize_annotation_extra(extra)?;
284        stmt.execute(params![id, name, group, accession_id, extra_json])?;
285        Ok(Annotation {
286            id,
287            name: name.to_string(),
288            group: group.to_string(),
289            accession_id: *accession_id,
290            extra: extra.cloned(),
291        })
292    }
293
294    pub fn get_or_create(
295        conn: &GraphConnection,
296        name: &str,
297        group: &str,
298        accession_id: &HashId,
299        extra: Option<&AnnotationExtra>,
300    ) -> Result<Annotation, AnnotationError> {
301        AnnotationGroup::get_or_create(conn, group)?;
302        match Annotation::create(conn, name, group, accession_id, extra) {
303            Ok(annotation) => Ok(annotation),
304            Err(AnnotationError::DatabaseError(rusqlite::Error::SqliteFailure(err, _details)))
305                if err.code == rusqlite::ErrorCode::ConstraintViolation =>
306            {
307                let id = Annotation::generate_id(name, group, accession_id);
308                Ok(Annotation {
309                    id,
310                    name: name.to_string(),
311                    group: group.to_string(),
312                    accession_id: *accession_id,
313                    extra: extra.cloned(),
314                })
315            }
316            Err(err) => Err(err),
317        }
318    }
319
320    pub fn create_with_samples(
321        conn: &GraphConnection,
322        name: &str,
323        group: &str,
324        accession_id: &HashId,
325        extra: Option<&AnnotationExtra>,
326        sample_names: &[&str],
327    ) -> Result<Annotation, AnnotationError> {
328        let annotation = Annotation::get_or_create(conn, name, group, accession_id, extra)?;
329        annotation.add_samples(conn, sample_names)?;
330        Ok(annotation)
331    }
332
333    pub fn add_samples(
334        &self,
335        conn: &GraphConnection,
336        sample_names: &[&str],
337    ) -> Result<(), AnnotationError> {
338        if sample_names.is_empty() {
339            return Ok(());
340        }
341        AnnotationGroup::get_or_create(conn, &self.group)?;
342        let query = "INSERT OR IGNORE INTO annotation_group_samples (annotation_group, sample_name) VALUES (?1, ?2);";
343        let mut stmt = conn.prepare(query)?;
344        for sample_name in sample_names {
345            stmt.execute(params![self.group, sample_name])?;
346        }
347        Ok(())
348    }
349
350    pub fn get_samples(
351        conn: &GraphConnection,
352        annotation_group: &str,
353    ) -> Result<Vec<String>, AnnotationError> {
354        let query = "SELECT sample_name FROM annotation_group_samples WHERE annotation_group = ?1;";
355        let mut stmt = conn.prepare(query)?;
356        let rows = stmt.query_map(params![annotation_group], |row| row.get(0))?;
357        let mut samples = Vec::new();
358        for row in rows {
359            samples.push(row?);
360        }
361        Ok(samples)
362    }
363
364    pub fn query_by_sample(
365        conn: &GraphConnection,
366        sample_name: &str,
367    ) -> Result<Vec<Annotation>, AnnotationError> {
368        let query = "select a.* from annotations a left join annotation_group_samples s on (a.annotation_group = s.annotation_group) where s.sample_name = ?1";
369        Ok(Annotation::query(conn, query, params![sample_name]))
370    }
371
372    pub fn query_by_group(
373        conn: &GraphConnection,
374        group: &str,
375    ) -> Result<Vec<Annotation>, AnnotationError> {
376        let query = "select * from annotations where annotation_group = ?1";
377        Ok(Annotation::query(conn, query, params![group]))
378    }
379
380    /// List every annotation on a block group, following the sample lineage.
381    ///
382    /// Collects annotations attached to the block group named `block_group_name`
383    /// in `collection_name`, considering `sample_name` together with all of its
384    /// ancestor samples. This mirrors how a block group inherits its parents'
385    /// annotations. Results are de-duplicated by annotation id and ordered from
386    /// the closest sample in the lineage outward. Two annotations that share a
387    /// name but come from different samples (e.g. a parent and child both
388    /// annotating "mreB") are both included, since each is a distinct
389    /// annotation record; unlike [`RegionResolver::resolve`], this is a listing
390    /// operation and does not need to disambiguate by name.
391    ///
392    /// # Arguments
393    ///
394    /// * `collection_name` - Collection the block group belongs to.
395    /// * `sample_name` - Sample whose lineage is walked, including the sample
396    ///   itself.
397    /// * `block_group_name` - Name shared by the block group across the lineage.
398    ///
399    /// # Errors
400    ///
401    /// Returns [`AnnotationError::DatabaseError`] if the query fails.
402    pub fn query_with_lineage(
403        conn: &GraphConnection,
404        collection_name: &str,
405        sample_name: &str,
406        block_group_name: &str,
407    ) -> Result<Vec<Annotation>, AnnotationError> {
408        let query = "WITH RECURSIVE visible_samples(name, depth, path) AS (
409                 SELECT ?2, 0, ',' || ?2 || ','
410                 UNION ALL
411                 SELECT sl.parent_sample_name,
412                        visible.depth + 1,
413                        visible.path || sl.parent_sample_name || ','
414                 FROM sample_lineage sl
415                 JOIN visible_samples visible ON sl.child_sample_name = visible.name
416                 WHERE instr(visible.path, ',' || sl.parent_sample_name || ',') = 0
417             )
418             SELECT a.id,
419                    a.name,
420                    a.annotation_group,
421                    a.accession_id,
422                    a.extra \
423             FROM annotations a \
424             JOIN accessions acc ON a.accession_id = acc.id \
425             JOIN block_groups bg ON acc.block_group_id = bg.id \
426             JOIN visible_samples visible ON bg.sample_name = visible.name \
427             WHERE bg.collection_name = ?1 \
428               AND bg.name = ?3
429             GROUP BY a.id, a.name, a.annotation_group, a.accession_id, a.extra
430             ORDER BY min(visible.depth), a.name, a.id";
431        Ok(Annotation::query(
432            conn,
433            query,
434            params![collection_name, sample_name, block_group_name],
435        ))
436    }
437
438    pub fn intervaltree(
439        &self,
440        conn: &GraphConnection,
441    ) -> Result<IntervalTree<i64, NodeIntervalBlock>, AnnotationError> {
442        let accession = Accession::get(
443            conn,
444            "select * from accessions where id = ?1",
445            params![self.accession_id],
446        )?;
447        accession.intervaltree(conn).map_err(Into::into)
448    }
449}
450
451impl RegionResolver for Annotation {
452    type Connection = GraphConnection;
453    type Error = AnnotationError;
454
455    fn resolve(
456        region: &Region,
457        conn: &Self::Connection,
458        collection_name: &str,
459        sample_name: &str,
460    ) -> Result<Self, RegionResolutionError<Self::Error>> {
461        let matches = Annotation::query(
462            conn,
463            "WITH RECURSIVE visible_samples(name, depth, path) AS (
464                 SELECT ?2, 0, ',' || ?2 || ','
465                 UNION ALL
466                 SELECT sl.parent_sample_name,
467                        visible.depth + 1,
468                        visible.path || sl.parent_sample_name || ','
469                 FROM sample_lineage sl
470                 JOIN visible_samples visible ON sl.child_sample_name = visible.name
471                 WHERE instr(visible.path, ',' || sl.parent_sample_name || ',') = 0
472             ),
473             matching_annotations AS (
474                 SELECT a.id,
475                        a.name,
476                        a.annotation_group,
477                        a.accession_id,
478                        a.extra,
479                        min(visible.depth) AS depth \
480                 FROM annotations a \
481                 JOIN accessions acc ON a.accession_id = acc.id \
482                 JOIN block_groups bg ON acc.block_group_id = bg.id \
483                 JOIN visible_samples visible ON bg.sample_name = visible.name \
484                 WHERE bg.collection_name = ?1 \
485                   AND lower(a.name) = lower(?3)
486                 GROUP BY a.id, a.name, a.annotation_group, a.accession_id, a.extra
487             )
488             SELECT id, name, annotation_group, accession_id, extra \
489             FROM matching_annotations \
490             WHERE depth = (SELECT min(depth) FROM matching_annotations)",
491            params![collection_name, sample_name, region.name],
492        );
493
494        match matches.len() {
495            0 => Err(RegionResolutionError::NotFound(region.name.clone())),
496            1 => Ok(matches.into_iter().next().unwrap()),
497            _ => Err(RegionResolutionError::Ambiguous(format!(
498                "multiple annotations named {}",
499                region.name
500            ))),
501        }
502    }
503}
504
505#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
506pub struct AnnotationGroupSample {
507    pub annotation_group: String,
508    pub sample_name: String,
509}
510
511impl<'a> Capnp<'a> for AnnotationGroupSample {
512    type Builder = annotation_group_sample::Builder<'a>;
513    type Reader = annotation_group_sample::Reader<'a>;
514
515    fn write_capnp(&self, builder: &mut Self::Builder) {
516        builder.set_annotation_group(&self.annotation_group);
517        builder.set_sample_name(&self.sample_name);
518    }
519
520    fn read_capnp(reader: Self::Reader) -> Self {
521        let annotation_group = reader.get_annotation_group().unwrap().to_string().unwrap();
522        let sample_name = reader.get_sample_name().unwrap().to_string().unwrap();
523        AnnotationGroupSample {
524            annotation_group,
525            sample_name,
526        }
527    }
528}
529
530impl AnnotationGroupSample {
531    pub fn create(
532        conn: &GraphConnection,
533        annotation_group: &str,
534        sample_name: &str,
535    ) -> Result<(), AnnotationError> {
536        AnnotationGroup::get_or_create(conn, annotation_group)?;
537        let query = "INSERT OR IGNORE INTO annotation_group_samples (annotation_group, sample_name) VALUES (?1, ?2);";
538        let mut stmt = conn.prepare(query)?;
539        stmt.execute(params![annotation_group, sample_name])?;
540        Ok(())
541    }
542
543    pub fn delete(
544        conn: &GraphConnection,
545        annotation_group: &str,
546        sample_name: &str,
547    ) -> Result<(), AnnotationError> {
548        let query = "DELETE FROM annotation_group_samples WHERE annotation_group = ?1 AND sample_name = ?2;";
549        let mut stmt = conn.prepare(query)?;
550        stmt.execute(params![annotation_group, sample_name])?;
551        Ok(())
552    }
553}
554
555#[derive(Debug, Error, PartialEq)]
556pub enum AnnotationGroupError {
557    #[error("Database error: {0}")]
558    DatabaseError(#[from] rusqlite::Error),
559}
560
561#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
562pub struct AnnotationFileInfo {
563    pub file_addition: FileAddition,
564    pub index_file_addition: Option<FileAddition>,
565    pub name: Option<String>,
566}
567
568#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
569pub struct AnnotationFileAdditionInput {
570    pub file_path: String,
571    pub file_type: FileTypes,
572    pub checksum_override: Option<HashId>,
573    pub name: Option<String>,
574    pub index_file_path: Option<String>,
575}
576
577#[derive(Debug, Error)]
578pub enum AnnotationFileError {
579    #[error("Database error: {0}")]
580    DatabaseError(#[from] rusqlite::Error),
581    #[error("File addition error: {0}")]
582    FileAdditionError(#[from] FileAdditionError),
583    #[error("Index file must be Tabix, got: {0:?}")]
584    InvalidIndexFileType(FileTypes),
585    #[error("Unsupported annotation file type: {0}")]
586    UnsupportedFileType(String),
587}
588
589pub fn parse_annotation_file_type(value: &str) -> Result<FileTypes, AnnotationFileError> {
590    match value.trim().to_ascii_lowercase().as_str() {
591        "gff3" | "gff" => Ok(FileTypes::Gff3),
592        "bed" => Ok(FileTypes::Bed),
593        "genbank" | "gb" => Ok(FileTypes::GenBank),
594        other => Err(AnnotationFileError::UnsupportedFileType(other.to_string())),
595    }
596}
597
598pub fn annotation_file_extension(path: &str) -> Option<String> {
599    let path = Path::new(path);
600    let mut ext = path
601        .extension()
602        .and_then(|ext| ext.to_str())
603        .map(|ext| ext.to_ascii_lowercase());
604    if matches!(ext.as_deref(), Some("gz") | Some("bgz")) {
605        ext = path
606            .file_stem()
607            .and_then(|stem| stem.to_str())
608            .and_then(|stem| Path::new(stem).extension().and_then(|ext| ext.to_str()))
609            .map(|ext| ext.to_ascii_lowercase());
610    }
611    ext
612}
613
614pub fn annotation_index_file_path(
615    workspace: &Workspace,
616    path: &str,
617    explicit_index_path: Option<&str>,
618) -> Option<String> {
619    if let Some(index_path) = explicit_index_path {
620        return Some(index_path.to_string());
621    }
622
623    let mut candidates = vec![format!("{path}.tbi")];
624    let path_buf = PathBuf::from(path);
625    if let Some(extension) = path_buf.extension().and_then(|ext| ext.to_str()) {
626        let mut extension_candidate = path_buf.clone();
627        extension_candidate.set_extension(format!("{extension}.tbi"));
628        let extension_candidate = extension_candidate.to_string_lossy().to_string();
629        if !candidates
630            .iter()
631            .any(|candidate| candidate == &extension_candidate)
632        {
633            candidates.push(extension_candidate);
634        }
635    }
636
637    for candidate in candidates {
638        let exists = if Path::new(&candidate).is_absolute() {
639            Path::new(&candidate).exists()
640        } else {
641            workspace
642                .repo_root()
643                .ok()
644                .is_some_and(|repo_root| repo_root.join(&candidate).exists())
645        };
646        if exists {
647            return Some(candidate);
648        }
649    }
650
651    None
652}
653
654pub fn add_annotation(
655    context: &DbContext,
656    collection: &str,
657    name: &str,
658    group: Option<&str>,
659    sample: &str,
660    region: &str,
661) -> Result<Operation, Box<dyn std::error::Error>> {
662    let graph_conn = context.graph().conn();
663    let operation_conn = context.operations().conn();
664    let parsed_region = Region::parse(region)?;
665    let resolved_region = crate::region::resolve(&parsed_region, graph_conn, collection, sample)?;
666    let spans = AccessionSpan::from_resolved_region(graph_conn, &resolved_region, None)?;
667
668    let mut session = start_operation(graph_conn);
669    graph_conn.execute("BEGIN TRANSACTION", [])?;
670    operation_conn.execute("BEGIN TRANSACTION", [])?;
671
672    let accession = Accession::create(
673        graph_conn,
674        &NewAccession {
675            name: name.to_string(),
676            block_group_id: resolved_region.block_group.id,
677            parent_accession_id: None,
678            spans,
679        },
680    )?;
681
682    let annotation_group = group.unwrap_or("default");
683    let annotation =
684        Annotation::get_or_create(graph_conn, name, annotation_group, &accession.id, None)?;
685    AnnotationGroupSample::create(graph_conn, &annotation.group, sample)?;
686
687    let operation = end_operation(
688        context,
689        &mut session,
690        &OperationInfo {
691            files: vec![],
692            description: format!("add annotation {name}"),
693        },
694        &format!("add annotation {name}"),
695        None,
696    )?;
697
698    graph_conn.execute("END TRANSACTION", [])?;
699    operation_conn.execute("END TRANSACTION", [])?;
700
701    Ok(operation)
702}
703
704pub fn add_annotation_file(
705    context: &DbContext,
706    path: &str,
707    format: Option<&str>,
708    index: Option<&str>,
709    name: Option<&str>,
710    message: Option<&str>,
711) -> Result<Operation, Box<dyn std::error::Error>> {
712    let workspace = context.workspace();
713    let operation_conn = context.operations().conn();
714    let graph_conn = context.graph().conn();
715    let db_uuid = metadata::get_db_uuid(graph_conn);
716
717    let file_type = match format {
718        Some(format) => parse_annotation_file_type(format)?,
719        None => {
720            let ext = annotation_file_extension(path).ok_or_else(|| {
721                anyhow!(
722                    "Unable to detect annotation file format from the file extension. Use --format to specify it explicitly."
723                )
724            })?;
725            parse_annotation_file_type(&ext)?
726        }
727    };
728    let file_addition =
729        FileAddition::get_or_create(workspace, operation_conn, path, file_type, None)?;
730    let index_file_addition = annotation_index_file_path(workspace, path, index)
731        .map(|index_path| {
732            FileAddition::get_or_create(
733                workspace,
734                operation_conn,
735                &index_path,
736                FileTypes::Tabix,
737                None,
738            )
739        })
740        .transpose()?;
741    let name_value = name.unwrap_or_default();
742    let index_file_addition_id = index_file_addition
743        .as_ref()
744        .map(|index_file| index_file.id.to_string())
745        .unwrap_or_default();
746    let operation_hash = HashId(calculate_hash(&format!(
747        "{file_addition_id}:{name_value}:{index_file_addition_id}",
748        file_addition_id = file_addition.id
749    )));
750    let operation = match Operation::create(operation_conn, "annotation-file", &operation_hash) {
751        Ok(operation) => operation,
752        Err(rusqlite::Error::SqliteFailure(err, _details))
753            if err.code == rusqlite::ErrorCode::ConstraintViolation =>
754        {
755            return Err(OperationError::NoChanges.into());
756        }
757        Err(err) => return Err(err.into()),
758    };
759    AnnotationFile::link_to_operation(
760        operation_conn,
761        &operation.hash,
762        &file_addition.id,
763        index_file_addition
764            .as_ref()
765            .map(|index_file| &index_file.id),
766        name,
767    )?;
768    Operation::add_database(operation_conn, &operation.hash, &db_uuid)?;
769    let summary = message
770        .map(str::to_string)
771        .unwrap_or_else(|| format!("Add annotation file {path}"));
772    OperationSummary::create(operation_conn, &operation.hash, &summary);
773
774    let gen_db = GenDatabase::get_by_uuid(operation_conn, &db_uuid)?;
775    write_changeset(
776        workspace,
777        &operation,
778        DatabaseChangeset {
779            db_path: gen_db.path,
780            changes: ChangesetModels::default(),
781        },
782        &DependencyModels::default(),
783    );
784
785    if file_type != FileTypes::Changeset && file_type != FileTypes::None {
786        file_addition.store_file(workspace)?;
787        if let Some(index_file_addition) = index_file_addition {
788            index_file_addition.store_file(workspace)?;
789        }
790    }
791
792    Ok(operation)
793}
794
795#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
796pub struct AnnotationFile {
797    pub id: i64,
798    pub operation_hash: HashId,
799    pub file_addition_id: HashId,
800    pub index_file_addition_id: Option<HashId>,
801    pub name: Option<String>,
802}
803
804impl Query for AnnotationFile {
805    type Model = AnnotationFile;
806
807    const TABLE_NAME: &'static str = "annotation_files";
808
809    fn process_row(row: &Row) -> Self::Model {
810        AnnotationFile {
811            id: row.get(0).unwrap(),
812            operation_hash: row.get(1).unwrap(),
813            file_addition_id: row.get(2).unwrap(),
814            index_file_addition_id: row.get(3).unwrap(),
815            name: row.get(4).unwrap(),
816        }
817    }
818}
819
820impl AnnotationFile {
821    pub fn load_index(
822        conn: &OperationsConnection,
823        file_addition_id: Option<&HashId>,
824    ) -> Result<Option<FileAddition>, AnnotationFileError> {
825        let Some(file_addition_id) = file_addition_id else {
826            return Ok(None);
827        };
828        let index_file_addition = FileAddition::get_by_id(conn, file_addition_id).ok_or(
829            AnnotationFileError::DatabaseError(rusqlite::Error::QueryReturnedNoRows),
830        )?;
831        if index_file_addition.file_type != FileTypes::Tabix {
832            return Err(AnnotationFileError::InvalidIndexFileType(
833                index_file_addition.file_type,
834            ));
835        }
836        Ok(Some(index_file_addition))
837    }
838
839    pub fn link_to_operation(
840        conn: &OperationsConnection,
841        operation_hash: &HashId,
842        file_addition_id: &HashId,
843        index_file_addition_id: Option<&HashId>,
844        name: Option<&str>,
845    ) -> Result<(), AnnotationFileError> {
846        AnnotationFile::load_index(conn, index_file_addition_id)?;
847        let query = "INSERT INTO annotation_files (operation_hash, file_addition_id, index_file_addition_id, name) VALUES (?1, ?2, ?3, ?4);";
848        let mut stmt = conn.prepare(query)?;
849        stmt.execute(params![
850            operation_hash,
851            file_addition_id,
852            index_file_addition_id,
853            name
854        ])?;
855        Ok(())
856    }
857
858    pub fn add_to_operation(
859        workspace: &Workspace,
860        conn: &OperationsConnection,
861        operation_hash: &HashId,
862        input: &AnnotationFileAdditionInput,
863    ) -> Result<FileAddition, AnnotationFileError> {
864        let file_addition = FileAddition::get_or_create(
865            workspace,
866            conn,
867            &input.file_path,
868            input.file_type,
869            input.checksum_override,
870        )?;
871        let index_file_addition = input
872            .index_file_path
873            .as_deref()
874            .map(|path| FileAddition::get_or_create(workspace, conn, path, FileTypes::Tabix, None))
875            .transpose()?;
876        AnnotationFile::link_to_operation(
877            conn,
878            operation_hash,
879            &file_addition.id,
880            index_file_addition.as_ref().map(|index| &index.id),
881            input.name.as_deref(),
882        )?;
883        Ok(file_addition)
884    }
885
886    pub fn get_files_for_operation(
887        conn: &OperationsConnection,
888        operation_hash: &HashId,
889    ) -> Vec<AnnotationFileInfo> {
890        let query = "select fa.*, af.index_file_addition_id, af.name from file_additions fa join annotation_files af on (fa.id = af.file_addition_id) where af.operation_hash = ?1";
891        let mut stmt = conn.prepare(query).unwrap();
892        let rows = stmt
893            .query_map(params![operation_hash], |row| {
894                Ok((
895                    FileAddition::process_row(row),
896                    row.get::<_, Option<HashId>>(4)?,
897                    row.get::<_, Option<String>>(5)?,
898                ))
899            })
900            .unwrap();
901        rows.map(|row| {
902            let (file_addition, index_file_addition_id, name) = row.unwrap();
903            AnnotationFileInfo {
904                file_addition,
905                index_file_addition: AnnotationFile::load_index(
906                    conn,
907                    index_file_addition_id.as_ref(),
908                )
909                .unwrap(),
910                name,
911            }
912        })
913        .collect()
914    }
915
916    pub fn get_all_files(conn: &OperationsConnection) -> Vec<AnnotationFileInfo> {
917        let query = "select fa.*, af.index_file_addition_id, af.name from file_additions fa join annotation_files af on (fa.id = af.file_addition_id)";
918        let mut stmt = conn.prepare(query).unwrap();
919        let rows = stmt
920            .query_map([], |row| {
921                Ok((
922                    FileAddition::process_row(row),
923                    row.get::<_, Option<HashId>>(4)?,
924                    row.get::<_, Option<String>>(5)?,
925                ))
926            })
927            .unwrap();
928        let mut entries: Vec<AnnotationFileInfo> = rows
929            .map(|row| {
930                let (file_addition, index_file_addition_id, name) = row.unwrap();
931                AnnotationFileInfo {
932                    file_addition,
933                    index_file_addition: AnnotationFile::load_index(
934                        conn,
935                        index_file_addition_id.as_ref(),
936                    )
937                    .unwrap(),
938                    name,
939                }
940            })
941            .collect();
942        entries.sort_by(|a, b| {
943            let a_path = a.file_addition.file_path();
944            let b_path = b.file_addition.file_path();
945            let a_name = std::path::Path::new(a_path)
946                .file_name()
947                .map(|name| name.to_string_lossy().to_string())
948                .unwrap_or_else(|| a_path.to_string());
949            let b_name = std::path::Path::new(b_path)
950                .file_name()
951                .map(|name| name.to_string_lossy().to_string())
952                .unwrap_or_else(|| b_path.to_string());
953            a_name.cmp(&b_name).then_with(|| a_path.cmp(b_path))
954        });
955        entries
956    }
957
958    pub fn query_by_operations(
959        conn: &OperationsConnection,
960        operations: &[HashId],
961    ) -> Result<HashMap<HashId, Vec<FileAddition>>, AnnotationFileError> {
962        let query = "select fa.*, af.operation_hash from file_additions fa left join annotation_files af on (fa.id = af.file_addition_id) where af.operation_hash in rarray(?1)";
963        let mut stmt = conn.prepare(query)?;
964        let rows = stmt.query_map(
965            params![Rc::new(
966                operations
967                    .iter()
968                    .map(|h| Value::from(*h))
969                    .collect::<Vec<Value>>()
970            )],
971            |row| Ok((FileAddition::process_row(row), row.get::<_, HashId>(4)?)),
972        )?;
973        rows.into_iter()
974            .try_fold(HashMap::new(), |mut acc: HashMap<_, Vec<_>>, row| {
975                let (item, hash) = row?;
976                acc.entry(hash).or_default().push(item);
977                Ok(acc)
978            })
979            .map_err(AnnotationFileError::DatabaseError)
980    }
981}
982
983#[cfg(test)]
984mod tests {
985    use std::{collections::HashSet, fs};
986
987    use gen_core::{HashId, region::RegionResolutionError};
988
989    use super::*;
990    use crate::{
991        block_group::{BlockGroup, PathCache},
992        block_group_edge::{BlockGroupEdge, BlockGroupEdgeData},
993        errors::OperationError,
994        files::GenDatabase,
995        metadata,
996        path::Path,
997        path_edge::PathEdge,
998        sample::Sample,
999        sample_lineage::SampleLineage,
1000        test_helpers::{create_bg, get_connection, setup_block_group, setup_gen},
1001    };
1002
1003    mod region_resolver {
1004        use super::*;
1005
1006        #[test]
1007        fn resolves_annotation_by_name_case_insensitively() {
1008            let conn = get_connection(None).unwrap();
1009            let (block_group_id, path) = setup_block_group(&conn);
1010            let mut cache = PathCache::new(&conn);
1011            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
1012            let accession =
1013                BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5, &mut cache).unwrap();
1014            let annotation =
1015                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
1016
1017            let region = Region::parse("MREB").unwrap();
1018            let resolved = Annotation::resolve(&region, &conn, "test", "test").unwrap();
1019            assert_eq!(resolved.id, annotation.id);
1020        }
1021
1022        #[test]
1023        fn returns_not_found_for_missing_annotation() {
1024            let conn = get_connection(None).unwrap();
1025            let (_block_group_id, _path) = setup_block_group(&conn);
1026
1027            let region = Region::parse("missing").unwrap();
1028            let err = Annotation::resolve(&region, &conn, "test", "test").unwrap_err();
1029            assert!(matches!(
1030                err,
1031                RegionResolutionError::NotFound(name) if name == "missing"
1032            ));
1033        }
1034
1035        #[test]
1036        fn returns_ambiguous_for_multiple_matching_annotations() {
1037            let conn = get_connection(None).unwrap();
1038            let (block_group_id, path) = setup_block_group(&conn);
1039            let mut cache = PathCache::new(&conn);
1040            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
1041            let accession =
1042                BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5, &mut cache).unwrap();
1043            let _ = Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
1044
1045            let other_block_group = create_bg(&conn, "test", "test", "other");
1046            let edge_ids = PathEdge::edges_for_path(&conn, &path.id)
1047                .into_iter()
1048                .map(|edge| edge.id)
1049                .collect::<Vec<_>>();
1050            let block_group_edges = edge_ids
1051                .iter()
1052                .map(|edge_id| BlockGroupEdgeData {
1053                    block_group_id: other_block_group.id,
1054                    edge_id: *edge_id,
1055                    chromosome_index: 0,
1056                    phased: 0,
1057                })
1058                .collect::<Vec<_>>();
1059            crate::block_group_edge::BlockGroupEdge::bulk_create(&conn, &block_group_edges);
1060            let other_path =
1061                Path::create(&conn, "other-path", &other_block_group.id, &edge_ids).unwrap();
1062            let other_accession =
1063                BlockGroup::add_accession(&conn, &other_path, "ann-accession-2", 0, 5, &mut cache)
1064                    .unwrap();
1065            let _ = Annotation::get_or_create(&conn, "MREB", "genes", &other_accession.id, None)
1066                .unwrap();
1067
1068            let region = Region::parse("mreB").unwrap();
1069            let err = Annotation::resolve(&region, &conn, "test", "test").unwrap_err();
1070            assert!(matches!(
1071                err,
1072                RegionResolutionError::Ambiguous(name) if name == "multiple annotations named mreB"
1073            ));
1074        }
1075
1076        #[test]
1077        fn resolves_closest_annotation_in_sample_lineage() {
1078            let conn = get_connection(None).unwrap();
1079            let (parent_block_group_id, parent_path) = setup_block_group(&conn);
1080            let mut cache = PathCache::new(&conn);
1081            let _ = PathCache::lookup(&mut cache, &parent_block_group_id, parent_path.name.clone())
1082                .unwrap();
1083            let parent_accession = BlockGroup::add_accession(
1084                &conn,
1085                &parent_path,
1086                "parent-accession",
1087                0,
1088                5,
1089                &mut cache,
1090            )
1091            .unwrap();
1092            let _parent_annotation =
1093                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
1094                    .unwrap();
1095
1096            let child_block_group = create_bg(&conn, "test", "child", "chr1");
1097            let edge_ids = PathEdge::edges_for_path(&conn, &parent_path.id)
1098                .into_iter()
1099                .map(|edge| edge.id)
1100                .collect::<Vec<_>>();
1101            let block_group_edges = edge_ids
1102                .iter()
1103                .map(|edge_id| BlockGroupEdgeData {
1104                    block_group_id: child_block_group.id,
1105                    edge_id: *edge_id,
1106                    chromosome_index: 0,
1107                    phased: 0,
1108                })
1109                .collect::<Vec<_>>();
1110            crate::block_group_edge::BlockGroupEdge::bulk_create(&conn, &block_group_edges);
1111            let child_path =
1112                Path::create(&conn, "child-path", &child_block_group.id, &edge_ids).unwrap();
1113            let child_accession =
1114                BlockGroup::add_accession(&conn, &child_path, "child-accession", 0, 5, &mut cache)
1115                    .unwrap();
1116            let child_annotation =
1117                Annotation::get_or_create(&conn, "MREB", "genes", &child_accession.id, None)
1118                    .unwrap();
1119            SampleLineage::create(&conn, "test", "child").unwrap();
1120
1121            let region = Region::parse("mreB").unwrap();
1122            let resolved = Annotation::resolve(&region, &conn, "test", "child").unwrap();
1123
1124            assert_eq!(resolved.id, child_annotation.id);
1125        }
1126
1127        #[test]
1128        fn falls_back_to_parent_annotation_when_child_has_none() {
1129            let conn = get_connection(None).unwrap();
1130            let (parent_block_group_id, parent_path) = setup_block_group(&conn);
1131            let mut cache = PathCache::new(&conn);
1132            let _ = PathCache::lookup(&mut cache, &parent_block_group_id, parent_path.name.clone())
1133                .unwrap();
1134            let parent_accession = BlockGroup::add_accession(
1135                &conn,
1136                &parent_path,
1137                "parent-only-accession",
1138                0,
1139                5,
1140                &mut cache,
1141            )
1142            .unwrap();
1143            let parent_annotation =
1144                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
1145                    .unwrap();
1146
1147            let child_block_group = create_bg(&conn, "test", "child", "chr1");
1148            let edge_ids = PathEdge::edges_for_path(&conn, &parent_path.id)
1149                .into_iter()
1150                .map(|edge| edge.id)
1151                .collect::<Vec<_>>();
1152            let block_group_edges = edge_ids
1153                .iter()
1154                .map(|edge_id| BlockGroupEdgeData {
1155                    block_group_id: child_block_group.id,
1156                    edge_id: *edge_id,
1157                    chromosome_index: 0,
1158                    phased: 0,
1159                })
1160                .collect::<Vec<_>>();
1161            crate::block_group_edge::BlockGroupEdge::bulk_create(&conn, &block_group_edges);
1162            let _child_path =
1163                Path::create(&conn, "child-path", &child_block_group.id, &edge_ids).unwrap();
1164            SampleLineage::create(&conn, "test", "child").unwrap();
1165
1166            let region = Region::parse("mreB").unwrap();
1167            let resolved = Annotation::resolve(&region, &conn, "test", "child").unwrap();
1168
1169            assert_eq!(resolved.id, parent_annotation.id);
1170        }
1171    }
1172
1173    mod lineage_listing {
1174        use super::*;
1175
1176        /// Attach a block group that shares `parent_path`'s edges, give it its
1177        /// own path and accession, and annotate it. Returns the annotation.
1178        #[expect(clippy::too_many_arguments, reason = "test helper wiring")]
1179        fn annotate_block_group(
1180            conn: &GraphConnection,
1181            parent_path: &Path,
1182            cache: &mut PathCache,
1183            collection_name: &str,
1184            sample_name: &str,
1185            block_group_name: &str,
1186            accession_name: &str,
1187            annotation_name: &str,
1188        ) -> Annotation {
1189            let block_group = create_bg(conn, collection_name, sample_name, block_group_name);
1190            let edge_ids = PathEdge::edges_for_path(conn, &parent_path.id)
1191                .into_iter()
1192                .map(|edge| edge.id)
1193                .collect::<Vec<_>>();
1194            let block_group_edges = edge_ids
1195                .iter()
1196                .map(|edge_id| BlockGroupEdgeData {
1197                    block_group_id: block_group.id,
1198                    edge_id: *edge_id,
1199                    chromosome_index: 0,
1200                    phased: 0,
1201                })
1202                .collect::<Vec<_>>();
1203            BlockGroupEdge::bulk_create(conn, &block_group_edges);
1204            let path = Path::create(conn, accession_name, &block_group.id, &edge_ids).unwrap();
1205            let accession =
1206                BlockGroup::add_accession(conn, &path, accession_name, 0, 5, cache).unwrap();
1207            Annotation::get_or_create(conn, annotation_name, "genes", &accession.id, None).unwrap()
1208        }
1209
1210        #[test]
1211        fn test_lists_annotations_on_block_group() {
1212            let conn = get_connection(None).unwrap();
1213            let (block_group_id, path) = setup_block_group(&conn);
1214            let mut cache = PathCache::new(&conn);
1215            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
1216            let accession =
1217                BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5, &mut cache).unwrap();
1218            let annotation =
1219                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
1220
1221            let listed = Annotation::query_with_lineage(&conn, "test", "test", "chr1").unwrap();
1222
1223            assert_eq!(listed, vec![annotation]);
1224        }
1225
1226        #[test]
1227        fn test_includes_parent_annotations_via_lineage() {
1228            let conn = get_connection(None).unwrap();
1229            let (parent_block_group_id, parent_path) = setup_block_group(&conn);
1230            let mut cache = PathCache::new(&conn);
1231            let _ = PathCache::lookup(&mut cache, &parent_block_group_id, parent_path.name.clone())
1232                .unwrap();
1233            let parent_accession = BlockGroup::add_accession(
1234                &conn,
1235                &parent_path,
1236                "parent-accession",
1237                0,
1238                5,
1239                &mut cache,
1240            )
1241            .unwrap();
1242            let parent_annotation =
1243                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
1244                    .unwrap();
1245
1246            let child_annotation = annotate_block_group(
1247                &conn,
1248                &parent_path,
1249                &mut cache,
1250                "test",
1251                "child",
1252                "chr1",
1253                "child-accession",
1254                "ftsZ",
1255            );
1256            SampleLineage::create(&conn, "test", "child").unwrap();
1257
1258            let listed = Annotation::query_with_lineage(&conn, "test", "child", "chr1").unwrap();
1259
1260            let ids: HashSet<HashId> = listed.iter().map(|a| a.id).collect();
1261            assert_eq!(
1262                ids,
1263                HashSet::from([parent_annotation.id, child_annotation.id])
1264            );
1265        }
1266
1267        #[test]
1268        fn test_excludes_annotations_on_other_block_group_names() {
1269            let conn = get_connection(None).unwrap();
1270            let (block_group_id, path) = setup_block_group(&conn);
1271            let mut cache = PathCache::new(&conn);
1272            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
1273            let accession =
1274                BlockGroup::add_accession(&conn, &path, "chr1-accession", 0, 5, &mut cache)
1275                    .unwrap();
1276            let chr1_annotation =
1277                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
1278
1279            let _chr2_annotation = annotate_block_group(
1280                &conn,
1281                &path,
1282                &mut cache,
1283                "test",
1284                "test",
1285                "chr2",
1286                "chr2-accession",
1287                "ftsZ",
1288            );
1289
1290            let listed = Annotation::query_with_lineage(&conn, "test", "test", "chr1").unwrap();
1291
1292            assert_eq!(listed, vec![chr1_annotation]);
1293        }
1294
1295        #[test]
1296        fn test_excludes_annotations_from_samples_outside_the_lineage() {
1297            let conn = get_connection(None).unwrap();
1298            let (block_group_id, path) = setup_block_group(&conn);
1299            let mut cache = PathCache::new(&conn);
1300            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
1301            let accession =
1302                BlockGroup::add_accession(&conn, &path, "test-accession", 0, 5, &mut cache)
1303                    .unwrap();
1304            let test_annotation =
1305                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
1306
1307            let _unrelated_annotation = annotate_block_group(
1308                &conn,
1309                &path,
1310                &mut cache,
1311                "test",
1312                "unrelated",
1313                "chr1",
1314                "unrelated-accession",
1315                "ftsZ",
1316            );
1317
1318            let listed = Annotation::query_with_lineage(&conn, "test", "test", "chr1").unwrap();
1319
1320            assert_eq!(listed, vec![test_annotation]);
1321        }
1322
1323        #[test]
1324        fn test_keeps_both_when_parent_and_child_share_an_annotation_name() {
1325            let conn = get_connection(None).unwrap();
1326            let (parent_block_group_id, parent_path) = setup_block_group(&conn);
1327            let mut cache = PathCache::new(&conn);
1328            let _ = PathCache::lookup(&mut cache, &parent_block_group_id, parent_path.name.clone())
1329                .unwrap();
1330            let parent_accession = BlockGroup::add_accession(
1331                &conn,
1332                &parent_path,
1333                "parent-accession",
1334                0,
1335                5,
1336                &mut cache,
1337            )
1338            .unwrap();
1339            let parent_annotation =
1340                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
1341                    .unwrap();
1342
1343            let child_annotation = annotate_block_group(
1344                &conn,
1345                &parent_path,
1346                &mut cache,
1347                "test",
1348                "child",
1349                "chr1",
1350                "child-accession",
1351                "mreB",
1352            );
1353            SampleLineage::create(&conn, "test", "child").unwrap();
1354
1355            let listed = Annotation::query_with_lineage(&conn, "test", "child", "chr1").unwrap();
1356
1357            // Same name, distinct annotation ids: listing keeps both rather than
1358            // collapsing by name. `resolve` would pick only the child's here
1359            // since it's the closer match (depth 0 vs. depth 1) and error on tie.
1360            assert_eq!(listed, vec![child_annotation, parent_annotation]);
1361        }
1362    }
1363
1364    #[test]
1365    fn create_annotation_with_samples() {
1366        let conn = get_connection(None).unwrap();
1367        let (block_group_id, path) = setup_block_group(&conn);
1368
1369        let _ = Sample::create(
1370            &conn,
1371            crate::sample::NewSample {
1372                name: "sample-1",
1373                is_reference: false,
1374            },
1375        )
1376        .unwrap();
1377        let _ = Sample::create(
1378            &conn,
1379            crate::sample::NewSample {
1380                name: "sample-2",
1381                is_reference: false,
1382            },
1383        )
1384        .unwrap();
1385
1386        let mut cache = PathCache::new(&conn);
1387        let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
1388        let accession =
1389            BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5, &mut cache).unwrap();
1390
1391        let annotation =
1392            Annotation::get_or_create(&conn, "gene-a", "project-tracks", &accession.id, None)
1393                .unwrap();
1394        annotation
1395            .add_samples(&conn, &["sample-1", "sample-2"])
1396            .unwrap();
1397
1398        let mut samples = Annotation::get_samples(&conn, &annotation.group).unwrap();
1399        samples.sort();
1400        assert_eq!(
1401            samples,
1402            vec!["sample-1".to_string(), "sample-2".to_string()]
1403        );
1404
1405        let by_sample = Annotation::query_by_sample(&conn, "sample-1").unwrap();
1406        assert_eq!(by_sample.len(), 1);
1407        assert_eq!(by_sample[0], annotation);
1408
1409        let by_group = Annotation::query_by_group(&conn, "project-tracks").unwrap();
1410        assert_eq!(by_group, vec![annotation]);
1411    }
1412
1413    #[test]
1414    fn deserialize_annotation_extra_defaults_missing_fields() {
1415        // Ensure that if we add new fields to the AnnotationExtra struct, like new_annotation_format we still parse old ones
1416        let extra = deserialize_annotation_extra(Some(r#"{"genbank":{"kind":"CDS"}}"#.to_string()))
1417            .unwrap()
1418            .unwrap();
1419
1420        assert_eq!(
1421            extra.genbank,
1422            Some(GenBankExtra {
1423                kind: "CDS".to_string(),
1424                ..GenBankExtra::default()
1425            })
1426        );
1427        assert_eq!(extra.gff, None);
1428        assert_eq!(extra.bed, None);
1429    }
1430
1431    #[test]
1432    fn deserialize_annotation_extra_ignores_unknown_fields() {
1433        // ensure if we drop a format, removed_top_level key here, we still parse
1434        let extra = deserialize_annotation_extra(Some(
1435            r#"{"genbank":{"kind":"CDS","legacy_field":"value"},"removed_top_level":true}"#
1436                .to_string(),
1437        ))
1438        .unwrap()
1439        .unwrap();
1440
1441        assert_eq!(
1442            extra.genbank,
1443            Some(GenBankExtra {
1444                kind: "CDS".to_string(),
1445                ..GenBankExtra::default()
1446            })
1447        );
1448        assert_eq!(extra.gff, None);
1449        assert_eq!(extra.bed, None);
1450    }
1451
1452    #[test]
1453    fn deserialize_and_reserialize_annotation_extra_keeps_compatible_fields() {
1454        // Ensure that if we parse an older field, we can still reserialize it with the compatible fields kept.
1455        let extra = deserialize_annotation_extra(Some(
1456            r#"{"genbank":{"kind":"CDS","legacy_field":"value"},"removed_top_level":true}"#
1457                .to_string(),
1458        ))
1459        .unwrap()
1460        .unwrap();
1461
1462        let reserialized = serialize_annotation_extra(Some(&extra)).unwrap();
1463        let reparsed: AnnotationExtra = serde_json::from_str(&reserialized).unwrap();
1464
1465        assert_eq!(
1466            reparsed.genbank,
1467            Some(GenBankExtra {
1468                kind: "CDS".to_string(),
1469                ..GenBankExtra::default()
1470            })
1471        );
1472        assert_eq!(reparsed.gff, None);
1473        assert_eq!(reparsed.bed, None);
1474    }
1475
1476    #[test]
1477    fn add_annotation_file_to_operation() {
1478        let context = setup_gen();
1479        let op_conn = context.operations().conn();
1480        let workspace = context.workspace();
1481        let repo_root = workspace.repo_root().unwrap();
1482        let annotation_path = repo_root.join("fixtures").join("annotation.gff3");
1483        fs::create_dir_all(annotation_path.parent().unwrap()).unwrap();
1484        fs::write(&annotation_path, "##gff-version 3\n").unwrap();
1485
1486        let op_hash = HashId::random_str();
1487        let _ = crate::operations::Operation::create(op_conn, "annotation-file", &op_hash)
1488            .expect("should create operation");
1489
1490        let file_addition = AnnotationFile::add_to_operation(
1491            workspace,
1492            op_conn,
1493            &op_hash,
1494            &AnnotationFileAdditionInput {
1495                file_path: annotation_path.to_string_lossy().to_string(),
1496                file_type: FileTypes::Gff3,
1497                checksum_override: None,
1498                name: Some("fixtures-annotation".to_string()),
1499                index_file_path: None,
1500            },
1501        )
1502        .unwrap();
1503
1504        let files = AnnotationFile::get_files_for_operation(op_conn, &op_hash);
1505        assert_eq!(files.len(), 1);
1506        assert_eq!(files[0].file_addition, file_addition);
1507        assert!(files[0].index_file_addition.is_none());
1508    }
1509
1510    #[test]
1511    fn parse_annotation_file_type_values() {
1512        assert_eq!(parse_annotation_file_type("gff3").unwrap(), FileTypes::Gff3);
1513        assert_eq!(parse_annotation_file_type("GFF").unwrap(), FileTypes::Gff3);
1514        assert_eq!(parse_annotation_file_type("bed").unwrap(), FileTypes::Bed);
1515        assert_eq!(
1516            parse_annotation_file_type("GenBank").unwrap(),
1517            FileTypes::GenBank
1518        );
1519        assert_eq!(
1520            parse_annotation_file_type("gb").unwrap(),
1521            FileTypes::GenBank
1522        );
1523        let err = parse_annotation_file_type("bam").unwrap_err();
1524        assert!(matches!(err, AnnotationFileError::UnsupportedFileType(_)));
1525    }
1526
1527    #[test]
1528    fn add_annotation_creates_annotation() {
1529        let context = setup_gen();
1530        let graph_conn = context.graph().conn();
1531        let operation_conn = context.operations().conn();
1532        let db_uuid = metadata::get_db_uuid(graph_conn);
1533        let _ = GenDatabase::create(operation_conn, &db_uuid, "test-db", "test-db-path").unwrap();
1534        let _ = setup_block_group(graph_conn);
1535
1536        let operation = add_annotation(
1537            &context,
1538            "test",
1539            "gene-a",
1540            Some("track-1"),
1541            "test",
1542            "chr1:1-5",
1543        )
1544        .unwrap();
1545        assert_eq!(operation.change_type, "add annotation gene-a");
1546
1547        let annotations = Annotation::query_by_group(graph_conn, "track-1").unwrap();
1548        assert_eq!(annotations.len(), 1);
1549        assert_eq!(annotations[0].name, "gene-a");
1550    }
1551
1552    #[test]
1553    fn add_annotation_file_creates_operation() {
1554        let context = setup_gen();
1555        let graph_conn = context.graph().conn();
1556        let operation_conn = context.operations().conn();
1557        let db_uuid = metadata::get_db_uuid(graph_conn);
1558        let _ = GenDatabase::create(operation_conn, &db_uuid, "test-db", "test-db-path").unwrap();
1559
1560        let repo_root = context.workspace().repo_root().unwrap();
1561        let annotation_path = repo_root.join("fixtures").join("annotation.gff3");
1562        fs::create_dir_all(annotation_path.parent().unwrap()).unwrap();
1563        fs::write(&annotation_path, "##gff-version 3\n").unwrap();
1564        let annotation_path_str = annotation_path.to_string_lossy().to_string();
1565
1566        let operation = add_annotation_file(
1567            &context,
1568            &annotation_path_str,
1569            None,
1570            None,
1571            Some("track-1"),
1572            None,
1573        )
1574        .unwrap();
1575        assert_eq!(operation.change_type, "annotation-file");
1576
1577        let files = AnnotationFile::get_files_for_operation(operation_conn, &operation.hash);
1578        assert_eq!(files.len(), 1);
1579        assert_eq!(files[0].name.as_deref(), Some("track-1"));
1580
1581        let err = add_annotation_file(
1582            &context,
1583            &annotation_path_str,
1584            None,
1585            None,
1586            Some("track-1"),
1587            None,
1588        )
1589        .unwrap_err();
1590        let op_err = err
1591            .downcast_ref::<OperationError>()
1592            .expect("should be an OperationError");
1593        assert_eq!(*op_err, OperationError::NoChanges);
1594    }
1595}