Skip to main content

gen_models/
annotations.rs

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