Skip to main content

gen_models/
accession.rs

1use std::{collections::HashMap, ops::Range as StdRange};
2
3use gen_core::{
4    HashId, NodeIntervalBlock, PATH_END_NODE_ID, PATH_START_NODE_ID, Strand, Workspace,
5    calculate_hash, is_terminal,
6    range::Range,
7    region::{Region, RegionResolutionError, RegionResolver},
8    traits::Capnp,
9};
10use intervaltree::IntervalTree;
11use rusqlite::params;
12use serde::{Deserialize, Serialize};
13use thiserror::Error;
14
15use crate::{
16    Direction, ModelSelect, ModelSelectError,
17    block_group::{BlockGroup, BlockGroupSelect},
18    block_group_edge::AugmentedEdgeData,
19    db::{GraphConnection, max_rows_per_batch},
20    gen_models_capnp::{accession, accession_node},
21    region::ResolvedGenRegion,
22};
23
24#[derive(Clone, Deserialize, Serialize, Debug, Eq, PartialEq, ModelSelect)]
25#[model_select(table = "accessions")]
26pub struct Accession {
27    pub id: HashId,
28    pub name: String,
29    pub block_group_id: HashId,
30    pub parent_accession_id: Option<HashId>,
31}
32
33#[derive(Debug, Error, PartialEq)]
34pub enum AccessionError {
35    #[error("Database error: {0}")]
36    DatabaseError(#[from] rusqlite::Error),
37    #[error("Selector error: {0}")]
38    ModelSelect(#[from] ModelSelectError),
39    #[error("Accession node creation error: {0}")]
40    AccessionNodeError(#[from] AccessionNodeError),
41    #[error("Duplicate entry with uuid: {0}")]
42    Duplicate(String),
43    #[error("Accession {0} has no nodes in accession_nodes")]
44    MissingPath(HashId),
45    #[error("Accession has no spans")]
46    EmptySpans,
47    #[error("Invalid accession range: {start}-{end}")]
48    InvalidRange { start: i64, end: i64 },
49    #[error("Unable to determine interval tree length")]
50    MissingIntervalTreeLength,
51    #[error("Unable to project region into accession spans: {0}")]
52    RegionProjection(String),
53}
54
55impl<'a> Capnp<'a> for Accession {
56    type Builder = accession::Builder<'a>;
57    type Reader = accession::Reader<'a>;
58
59    fn write_capnp(&self, builder: &mut Self::Builder) {
60        builder.set_id(&self.id.0).unwrap();
61        builder.set_name(&self.name);
62        builder.set_block_group_id(&self.block_group_id.0).unwrap();
63        match &self.parent_accession_id {
64            None => {
65                builder.reborrow().get_parent_accession_id().set_none(());
66            }
67            Some(n) => {
68                builder
69                    .reborrow()
70                    .get_parent_accession_id()
71                    .set_some(&n.0)
72                    .unwrap();
73            }
74        }
75    }
76
77    fn read_capnp(reader: Self::Reader) -> Self {
78        let id = reader
79            .get_id()
80            .unwrap()
81            .as_slice()
82            .unwrap()
83            .try_into()
84            .unwrap();
85        let name = reader.get_name().unwrap().to_string().unwrap();
86        let block_group_id = reader
87            .get_block_group_id()
88            .unwrap()
89            .as_slice()
90            .unwrap()
91            .try_into()
92            .unwrap();
93        let parent_accession_id: Option<HashId> =
94            match reader.get_parent_accession_id().which().unwrap() {
95                accession::parent_accession_id::None(()) => None,
96                accession::parent_accession_id::Some(n) => {
97                    Some(n.unwrap().as_slice().unwrap().try_into().unwrap())
98                }
99            };
100
101        Accession {
102            id,
103            name,
104            block_group_id,
105            parent_accession_id,
106        }
107    }
108}
109
110#[derive(Deserialize, Serialize, Debug, PartialEq, Eq, Hash, ModelSelect)]
111#[model_select(table = "accession_nodes")]
112pub struct AccessionNode {
113    pub id: HashId,
114    pub accession_id: HashId,
115    pub node_id: HashId,
116    pub sequence_start: i64,
117    pub sequence_end: i64,
118    pub strand: Strand,
119    pub index_in_path: i64,
120}
121
122#[derive(Debug, Error, PartialEq)]
123pub enum AccessionNodeError {
124    #[error("Database error: {0}")]
125    DatabaseError(#[from] rusqlite::Error),
126}
127
128impl<'a> Capnp<'a> for AccessionNode {
129    type Builder = accession_node::Builder<'a>;
130    type Reader = accession_node::Reader<'a>;
131
132    fn write_capnp(&self, builder: &mut Self::Builder) {
133        builder.set_id(&self.id.0).unwrap();
134        builder.set_accession_id(&self.accession_id.0).unwrap();
135        builder.set_node_id(&self.node_id.0).unwrap();
136        builder.set_sequence_start(self.sequence_start);
137        builder.set_sequence_end(self.sequence_end);
138        builder.set_strand(self.strand.into());
139        builder.set_index_in_path(self.index_in_path);
140    }
141
142    fn read_capnp(reader: Self::Reader) -> Self {
143        let id = reader
144            .get_id()
145            .unwrap()
146            .as_slice()
147            .unwrap()
148            .try_into()
149            .unwrap();
150        let accession_id = reader
151            .get_accession_id()
152            .unwrap()
153            .as_slice()
154            .unwrap()
155            .try_into()
156            .unwrap();
157        let node_id = reader
158            .get_node_id()
159            .unwrap()
160            .as_slice()
161            .unwrap()
162            .try_into()
163            .unwrap();
164        let sequence_start = reader.get_sequence_start();
165        let sequence_end = reader.get_sequence_end();
166        let strand = reader.get_strand().unwrap().into();
167        let index_in_path = reader.get_index_in_path();
168
169        AccessionNode {
170            id,
171            accession_id,
172            node_id,
173            sequence_start,
174            sequence_end,
175            strand,
176            index_in_path,
177        }
178    }
179}
180
181/// AccessionNodeData is a non-database form of AccessionNode. It allows callers to construct
182/// an AccessionNode without having to calculate the id.
183#[derive(Clone, Debug, Eq, Hash, PartialEq)]
184pub struct AccessionNodeData {
185    pub accession_id: HashId,
186    pub node_id: HashId,
187    pub sequence_start: i64,
188    pub sequence_end: i64,
189    pub strand: Strand,
190    pub index_in_path: i64,
191}
192
193/// AccessionSpan is similar to AnnotationSegment in shape, but its primary use is
194/// for creating AccessionNodes
195#[derive(Clone, Copy, Debug, Eq, PartialEq)]
196pub struct AccessionSpan {
197    pub node_id: HashId,
198    pub range: Range,
199    pub strand: Strand,
200}
201
202impl AccessionNodeData {
203    pub fn id_hash(&self) -> HashId {
204        HashId(calculate_hash(&format!(
205            "{}:{}:{}:{}:{}:{}",
206            self.accession_id,
207            self.node_id,
208            self.sequence_start,
209            self.sequence_end,
210            self.strand,
211            self.index_in_path
212        )))
213    }
214}
215
216impl From<&AccessionNode> for AccessionNodeData {
217    fn from(item: &AccessionNode) -> Self {
218        AccessionNodeData {
219            accession_id: item.accession_id,
220            node_id: item.node_id,
221            sequence_start: item.sequence_start,
222            sequence_end: item.sequence_end,
223            strand: item.strand,
224            index_in_path: item.index_in_path,
225        }
226    }
227}
228
229impl From<AccessionNodeData> for AccessionNode {
230    fn from(item: AccessionNodeData) -> Self {
231        AccessionNode {
232            id: item.id_hash(),
233            accession_id: item.accession_id,
234            node_id: item.node_id,
235            sequence_start: item.sequence_start,
236            sequence_end: item.sequence_end,
237            strand: item.strand,
238            index_in_path: item.index_in_path,
239        }
240    }
241}
242
243#[derive(Clone, Debug, Eq, PartialEq)]
244pub struct NewAccession {
245    pub name: String,
246    pub block_group_id: HashId,
247    pub parent_accession_id: Option<HashId>,
248    pub spans: Vec<AccessionSpan>,
249}
250
251impl Accession {
252    /// An accession is an ordered array of slices of nodes. The purpose
253    /// of an accession is to provide additional layers of information to
254    /// a graph. These extra pieces of information can be features such
255    /// as gene annotations, epigenetic markers, translocations, and so on.
256    ///
257    /// From a modeling stance, there is a table AccessionNodes, which holds
258    /// the positions within a Node the accession covers, its strand, and what
259    /// position it is in the array. Accessions are not meant to be restricted
260    /// to a graph topology. Take the following example of a spliced gene:
261    ///
262    /// ```text
263    /// AAAAAAAAAAAAAAAATTTTTTTTTTTTCCCCCCCCCCCCCCCCCCCGGGGGGGGGGGGGGGG
264    ///     [part-a]--->[part-b]---->[part-c]-->[part-d]
265    /// ```
266    ///
267    /// There are no edges in the primary sequence, but there are 4 accession nodes
268    /// linked together. There is similarly no guarantee that nodes are on the same
269    /// blockgroup, which enables modeling of events such as translocations.
270    ///
271    /// Similarly, we do not model an accession on the edges of the graph
272    /// because the variation in the graph does not impact the accession. Take an example
273    /// where a variant is introduced in the intronic region of a gene:
274    ///
275    /// ```text
276    ///             A
277    ///            / \
278    /// AAAAAAAAAA-TTT-TTTTTTCCCCCCCCCCC
279    /// [part-1]----------->[part-2]
280    /// ```
281    ///
282    /// If we annotated according to edges, the introduction of the A variant questions
283    /// if we should store part-1/part-2 also on the new edge between them. Storing it
284    /// on nodes means it is up to the context the graph is being used to determine how to
285    /// treat the graph topology.
286    fn id_hash(
287        block_group_id: &HashId,
288        parent_accession_id: Option<&HashId>,
289        name: &str,
290    ) -> HashId {
291        HashId(calculate_hash(&format!(
292            "{block_group_id}:{parent_accession_id:?}:{name}"
293        )))
294    }
295
296    pub fn create(conn: &GraphConnection, new: &NewAccession) -> Result<Accession, AccessionError> {
297        if new.spans.is_empty() {
298            return Err(AccessionError::EmptySpans);
299        }
300        let query = "INSERT INTO accessions (id, name, block_group_id, parent_accession_id) VALUES (?1, ?2, ?3, ?4);";
301        let mut stmt = match conn.prepare(query) {
302            Ok(s) => s,
303            Err(e) => return Err(AccessionError::DatabaseError(e)),
304        };
305        let parent_accession_id = new.parent_accession_id.as_ref();
306        let hash = Accession::id_hash(&new.block_group_id, parent_accession_id, &new.name);
307        let accession = match stmt.execute((
308            hash,
309            &new.name,
310            &new.block_group_id,
311            parent_accession_id,
312        )) {
313            Ok(_) => Accession {
314                id: hash,
315                name: new.name.clone(),
316                block_group_id: new.block_group_id,
317                parent_accession_id: new.parent_accession_id,
318            },
319            Err(rusqlite::Error::SqliteFailure(err, _details))
320                if err.code == rusqlite::ErrorCode::ConstraintViolation =>
321            {
322                return Err(AccessionError::Duplicate(format!(
323                    "An accession with the same name, block_group_id, and parent_accession_id already exists. name: {}, block_group_id: {}, parent_accession_id: {:?}",
324                    new.name, new.block_group_id, new.parent_accession_id
325                )));
326            }
327            Err(e) => return Err(AccessionError::DatabaseError(e)),
328        };
329        Self::insert_spans(conn, &accession.id, &new.spans)?;
330        Ok(accession)
331    }
332
333    pub fn create_from_edges(
334        conn: &GraphConnection,
335        name: &str,
336        block_group_id: &HashId,
337        parent_accession_id: Option<&HashId>,
338        edges: &[AugmentedEdgeData],
339    ) -> Result<Accession, AccessionError> {
340        let spans = edges
341            .windows(2)
342            .map(|edge_pair| {
343                let into = &edge_pair[0].edge_data;
344                let out_of = &edge_pair[1].edge_data;
345                AccessionSpan {
346                    node_id: into.target_node_id,
347                    range: Range {
348                        start: into.target_coordinate,
349                        end: out_of.source_coordinate,
350                    },
351                    strand: into.target_strand,
352                }
353            })
354            .collect::<Vec<_>>();
355        Self::create(
356            conn,
357            &NewAccession {
358                name: name.to_string(),
359                block_group_id: *block_group_id,
360                parent_accession_id: parent_accession_id.copied(),
361                spans,
362            },
363        )
364    }
365
366    pub fn get_or_create(
367        conn: &GraphConnection,
368        new: &NewAccession,
369    ) -> Result<Accession, AccessionError> {
370        match Accession::create(conn, new) {
371            Ok(accession) => Ok(accession),
372            Err(AccessionError::Duplicate(message)) => {
373                let accession = Accession {
374                    id: Accession::id_hash(
375                        &new.block_group_id,
376                        new.parent_accession_id.as_ref(),
377                        &new.name,
378                    ),
379                    name: new.name.clone(),
380                    block_group_id: new.block_group_id,
381                    parent_accession_id: new.parent_accession_id,
382                };
383                let nodes = Self::get_nodes_by_id(conn, &accession.id, None);
384                if nodes.is_empty() {
385                    Self::insert_spans(conn, &accession.id, &new.spans)?;
386                } else if !Self::nodes_match_spans(&nodes, &new.spans) {
387                    return Err(AccessionError::Duplicate(message));
388                }
389                Ok(accession)
390            }
391            Err(err) => Err(err),
392        }
393    }
394
395    fn nodes_match_spans(nodes: &[AccessionNode], spans: &[AccessionSpan]) -> bool {
396        nodes.len() == spans.len()
397            && nodes
398                .iter()
399                .zip(spans)
400                .enumerate()
401                .all(|(index, (node, span))| {
402                    node.index_in_path == index as i64
403                        && node.node_id == span.node_id
404                        && node.sequence_start == span.range.start
405                        && node.sequence_end == span.range.end
406                        && node.strand == span.strand
407                })
408    }
409
410    fn insert_spans(
411        conn: &GraphConnection,
412        accession_id: &HashId,
413        spans: &[AccessionSpan],
414    ) -> Result<(), AccessionError> {
415        let nodes = spans
416            .iter()
417            .enumerate()
418            .map(|(index, span)| AccessionNodeData {
419                accession_id: *accession_id,
420                node_id: span.node_id,
421                sequence_start: span.range.start,
422                sequence_end: span.range.end,
423                strand: span.strand,
424                index_in_path: index as i64,
425            })
426            .collect::<Vec<_>>();
427        AccessionNode::bulk_create(conn, &nodes)?;
428        Ok(())
429    }
430
431    pub fn get_nodes_by_id(
432        conn: &GraphConnection,
433        accession_id: &HashId,
434        history_ref: Option<&str>,
435    ) -> Vec<AccessionNode> {
436        let select = AccessionNode::select(conn)
437            .accession_id(*accession_id)
438            .order_by(AccessionNodeSelect::IndexInPath, Direction::Asc)
439            .with_ref(history_ref);
440        select.load().expect("should load accession nodes")
441    }
442
443    pub fn blocks(&self, conn: &GraphConnection) -> Result<Vec<NodeIntervalBlock>, AccessionError> {
444        let nodes = Self::get_nodes_by_id(conn, &self.id, None);
445        if nodes.is_empty() {
446            return Err(AccessionError::MissingPath(self.id));
447        }
448
449        let mut offset = 0;
450        let mut blocks = vec![NodeIntervalBlock {
451            node_id: PATH_START_NODE_ID,
452            start: i64::MIN + 1,
453            end: 0,
454            sequence_start: 0,
455            sequence_end: 0,
456            strand: Strand::Forward,
457        }];
458
459        for node in nodes {
460            let block_len = node.sequence_end - node.sequence_start;
461            blocks.push(NodeIntervalBlock {
462                node_id: node.node_id,
463                start: offset,
464                end: offset + block_len,
465                sequence_start: node.sequence_start,
466                sequence_end: node.sequence_end,
467                strand: node.strand,
468            });
469            offset += block_len;
470        }
471
472        blocks.push(NodeIntervalBlock {
473            node_id: PATH_END_NODE_ID,
474            start: offset,
475            end: i64::MAX - 1,
476            sequence_start: 0,
477            sequence_end: 0,
478            strand: Strand::Forward,
479        });
480
481        Ok(blocks)
482    }
483
484    pub fn length(&self, conn: &GraphConnection) -> Result<i64, AccessionError> {
485        let nodes = Self::get_nodes_by_id(conn, &self.id, None);
486        if nodes.is_empty() {
487            return Err(AccessionError::MissingPath(self.id));
488        }
489
490        Ok(nodes
491            .iter()
492            .map(|node| node.sequence_end - node.sequence_start)
493            .sum())
494    }
495
496    pub fn intervaltree(
497        &self,
498        conn: &GraphConnection,
499    ) -> Result<IntervalTree<i64, NodeIntervalBlock>, AccessionError> {
500        Ok(self
501            .blocks(conn)?
502            .into_iter()
503            .map(|block| (block.start..block.end, block))
504            .collect())
505    }
506}
507
508impl AccessionSpan {
509    /// Given an intervaltree, create AccessionSpans on the provided range positions.
510    /// For example:
511    /// from_intervaltree_ranges(tree, [(1..3), (5..10)])
512    /// would create 2 AccessionSpans corresponding to the Nodes and positions in the
513    /// input ranges.
514    pub fn from_intervaltree_ranges(
515        tree: &IntervalTree<i64, NodeIntervalBlock>,
516        ranges: &[StdRange<i64>],
517    ) -> Result<Vec<AccessionSpan>, AccessionError> {
518        let length = intervaltree_length(tree)?;
519        let mut spans = Vec::new();
520        for range in ranges {
521            if range.start > range.end {
522                // TODO: When circular stuff is better supported, this should not be an error. We should
523                // check if the blockgroup is circular and wrap around.
524                return Err(AccessionError::InvalidRange {
525                    start: range.start,
526                    end: range.end,
527                });
528            }
529            if range.start < 0 || range.end < 0 || range.start > length || range.end > length {
530                return Err(AccessionError::InvalidRange {
531                    start: range.start,
532                    end: range.end,
533                });
534            }
535            if range.start == range.end {
536                continue;
537            }
538            let mut blocks = tree
539                .query(range.start..range.end)
540                .map(|entry| &entry.value)
541                .filter(|block| !is_terminal(block.node_id))
542                .collect::<Vec<_>>();
543            blocks.sort_by_key(|block| block.start);
544            spans.extend(blocks.into_iter().map(|block| {
545                let clipped_start = range.start.max(block.start);
546                let clipped_end = range.end.min(block.end);
547                AccessionSpan {
548                    node_id: block.node_id,
549                    range: Range {
550                        start: clipped_start - block.start + block.sequence_start,
551                        end: clipped_end - block.start + block.sequence_start,
552                    },
553                    strand: block.strand,
554                }
555            }));
556        }
557        Ok(spans)
558    }
559
560    /// convert a ResolvedGenRegion to an AccessionSpan. If no sub-region is selected,
561    /// the entire region is used.
562    pub fn from_resolved_region(
563        conn: &GraphConnection,
564        workspace: &Workspace,
565        region: &ResolvedGenRegion,
566        ranges: Option<&[StdRange<i64>]>,
567    ) -> Result<Vec<AccessionSpan>, AccessionError> {
568        let tree = region
569            .intervaltree(conn, workspace)
570            .map_err(|err| AccessionError::RegionProjection(err.to_string()))?;
571        match ranges {
572            Some(ranges) => Self::from_intervaltree_ranges(&tree, ranges),
573            None => {
574                let range = region.start..region.end;
575                Self::from_intervaltree_ranges(&tree, std::slice::from_ref(&range))
576            }
577        }
578    }
579}
580
581fn intervaltree_length(tree: &IntervalTree<i64, NodeIntervalBlock>) -> Result<i64, AccessionError> {
582    if let Some(end_block) = tree
583        .query_point(i64::MAX - 2)
584        .map(|entry| &entry.value)
585        .find(|block| block.node_id == PATH_END_NODE_ID)
586    {
587        return Ok(end_block.start);
588    }
589
590    tree.iter_sorted()
591        .map(|entry| &entry.value.end)
592        .last()
593        .copied()
594        .ok_or(AccessionError::MissingIntervalTreeLength)
595}
596
597impl RegionResolver for Accession {
598    type Connection = GraphConnection;
599    type Error = AccessionError;
600
601    fn resolve(
602        region: &Region,
603        conn: &Self::Connection,
604        collection_name: &str,
605        sample_name: &str,
606    ) -> Result<Self, RegionResolutionError<Self::Error>> {
607        let matches = Accession::select(conn)
608            .name_case_insensitive(&region.name)
609            .join_filtered_on(
610                AccessionSelect::BlockGroupId,
611                BlockGroupSelect::Id,
612                BlockGroup::select(conn)
613                    .collection_name(collection_name)
614                    .sample_name(sample_name),
615            )
616            .load()
617            .map_err(AccessionError::from)?;
618
619        match matches.len() {
620            0 => Err(RegionResolutionError::NotFound(region.name.clone())),
621            1 => {
622                if let Some(accession) = matches.into_iter().next() {
623                    Ok(accession)
624                } else {
625                    Err(RegionResolutionError::NotFound(region.name.clone()))
626                }
627            }
628            _ => Err(RegionResolutionError::Ambiguous(format!(
629                "multiple accessions named {}",
630                region.name
631            ))),
632        }
633    }
634}
635
636impl AccessionNode {
637    pub fn query_accessions(
638        conn: &GraphConnection,
639        accession_ids: &[HashId],
640    ) -> Result<HashMap<HashId, Vec<AccessionNode>>, ModelSelectError> {
641        if accession_ids.is_empty() {
642            return Ok(HashMap::new());
643        }
644
645        let nodes = AccessionNode::select(conn)
646            .accession_id_in(accession_ids.iter().copied())
647            .order_by(AccessionNodeSelect::AccessionId, Direction::Asc)
648            .order_by(AccessionNodeSelect::IndexInPath, Direction::Asc)
649            .load()?;
650        let mut nodes_by_accession = HashMap::new();
651        for node in nodes {
652            nodes_by_accession
653                .entry(node.accession_id)
654                .or_insert_with(Vec::new)
655                .push(node);
656        }
657        Ok(nodes_by_accession)
658    }
659
660    pub fn create(
661        conn: &GraphConnection,
662        node: AccessionNodeData,
663    ) -> Result<AccessionNode, AccessionNodeError> {
664        let hash = node.id_hash();
665        let insert_statement = "INSERT INTO accession_nodes (id, accession_id, node_id, sequence_start, sequence_end, strand, index_in_path) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7);";
666        let mut stmt = conn.prepare(insert_statement)?;
667        match stmt.execute(params![
668            hash,
669            node.accession_id,
670            node.node_id,
671            node.sequence_start,
672            node.sequence_end,
673            node.strand,
674            node.index_in_path
675        ]) {
676            Ok(_) => {}
677            Err(rusqlite::Error::SqliteFailure(err, _details)) => {
678                if err.code == rusqlite::ErrorCode::ConstraintViolation {}
679            }
680            Err(err) => return Err(AccessionNodeError::DatabaseError(err)),
681        };
682        Ok(AccessionNode::from(node))
683    }
684
685    pub fn bulk_create(
686        conn: &GraphConnection,
687        nodes: &[AccessionNodeData],
688    ) -> Result<Vec<HashId>, AccessionNodeError> {
689        let node_ids = nodes
690            .iter()
691            .map(AccessionNodeData::id_hash)
692            .collect::<Vec<_>>();
693        let batch_size = max_rows_per_batch(conn, 7);
694
695        for chunk in nodes.chunks(batch_size) {
696            let mut rows = vec![];
697            let mut params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
698            for node in chunk {
699                params.push(Box::new(node.id_hash()));
700                params.push(Box::new(node.accession_id));
701                params.push(Box::new(node.node_id));
702                params.push(Box::new(node.sequence_start));
703                params.push(Box::new(node.sequence_end));
704                params.push(Box::new(node.strand));
705                params.push(Box::new(node.index_in_path));
706                rows.push("(?, ?, ?, ?, ?, ?, ?)");
707            }
708            let sql = format!(
709                "INSERT OR IGNORE INTO accession_nodes (id, accession_id, node_id, sequence_start, sequence_end, strand, index_in_path) VALUES {};",
710                rows.join(",")
711            );
712            conn.execute(&sql, rusqlite::params_from_iter(params))?;
713        }
714        Ok(node_ids)
715    }
716
717    pub fn bulk_delete(conn: &GraphConnection, nodes: &[AccessionNodeData]) {
718        let ids = nodes
719            .iter()
720            .map(AccessionNodeData::id_hash)
721            .collect::<Vec<_>>();
722        AccessionNode::select(conn)
723            .delete_by_ids(ids)
724            .expect("should delete accession nodes by id");
725    }
726}
727
728#[cfg(test)]
729mod tests {
730    use capnp::message::TypedBuilder;
731    use gen_core::{HashId, region::RegionResolutionError};
732
733    use super::*;
734    use crate::{
735        block_group::{BlockGroup, PathCache},
736        block_group_edge::{AugmentedEdgeData, BlockGroupEdgeData},
737        edge::EdgeData,
738        path::Path,
739        test_helpers::{create_bg, get_connection, interval_tree_verify, setup_block_group},
740    };
741
742    mod region_resolver {
743        use super::*;
744
745        #[test]
746        fn test_resolves_accession_by_name_case_insensitively() {
747            let conn = &get_connection(None).unwrap();
748            let (_bg, path) = setup_block_group(conn);
749            let mut path_cache = PathCache::new(conn);
750            let accession =
751                BlockGroup::add_accession(conn, &path, "mreB", 5, 15, &mut path_cache).unwrap();
752
753            let region = Region::parse("MREB").unwrap();
754            let resolved = Accession::resolve(&region, conn, "test", "test").unwrap();
755            assert_eq!(resolved.id, accession.id);
756        }
757
758        #[test]
759        fn test_returns_not_found_for_missing_accession() {
760            let conn = &get_connection(None).unwrap();
761            let (_bg, _path) = setup_block_group(conn);
762
763            let region = Region::parse("missing").unwrap();
764            let err = Accession::resolve(&region, conn, "test", "test").unwrap_err();
765            assert!(matches!(
766                err,
767                RegionResolutionError::NotFound(name) if name == "missing"
768            ));
769        }
770
771        #[test]
772        fn test_returns_ambiguous_for_multiple_matching_accessions() {
773            let conn = &get_connection(None).unwrap();
774            let (_bg, path) = setup_block_group(conn);
775            let mut path_cache = PathCache::new(conn);
776            let _ = BlockGroup::add_accession(conn, &path, "mreB", 5, 15, &mut path_cache).unwrap();
777
778            let other_block_group = create_bg(conn, "test", "test", "other");
779            let edge_ids = Path::edges_for_path(conn, &path.id, None)
780                .into_iter()
781                .map(|edge| edge.id)
782                .collect::<Vec<_>>();
783            let block_group_edges = edge_ids
784                .iter()
785                .map(|edge_id| BlockGroupEdgeData {
786                    block_group_id: other_block_group.id,
787                    edge_id: *edge_id,
788                    chromosome_index: 0,
789                    phased: 0,
790                })
791                .collect::<Vec<_>>();
792            crate::block_group_edge::BlockGroupEdge::bulk_create(conn, &block_group_edges);
793            let other_path =
794                Path::create(conn, "other-path", &other_block_group.id, &edge_ids).unwrap();
795            let _ = BlockGroup::add_accession(conn, &other_path, "MREB", 5, 15, &mut path_cache)
796                .unwrap();
797
798            let region = Region::parse("mreB").unwrap();
799            let err = Accession::resolve(&region, conn, "test", "test").unwrap_err();
800            assert!(matches!(
801                err,
802                RegionResolutionError::Ambiguous(name) if name == "multiple accessions named mreB"
803            ));
804        }
805    }
806
807    #[test]
808    fn test_accession_capnp_serialization() {
809        let accession = Accession {
810            id: HashId::pad_str(200),
811            name: "test_accession".to_string(),
812            block_group_id: HashId::pad_str(150),
813            parent_accession_id: Some(HashId::pad_str(100)),
814        };
815
816        let mut message = TypedBuilder::<accession::Owned>::new_default();
817        let mut root = message.init_root();
818        accession.write_capnp(&mut root);
819
820        let deserialized = Accession::read_capnp(root.into_reader());
821        assert_eq!(accession, deserialized);
822    }
823
824    #[test]
825    fn test_accession_capnp_serialization_no_parent() {
826        let accession = Accession {
827            id: HashId::pad_str(201),
828            name: "test_accession_2".to_string(),
829            block_group_id: HashId::pad_str(151),
830            parent_accession_id: None,
831        };
832
833        let mut message = TypedBuilder::<accession::Owned>::new_default();
834        let mut root = message.init_root();
835        accession.write_capnp(&mut root);
836
837        let deserialized = Accession::read_capnp(root.into_reader());
838        assert_eq!(accession, deserialized);
839    }
840
841    #[test]
842    fn test_accession_node_capnp_serialization() {
843        let accession_node = AccessionNode {
844            id: HashId::pad_str(300),
845            accession_id: HashId::convert_str("accession"),
846            node_id: HashId::convert_str("20"),
847            sequence_start: 2,
848            sequence_end: 4,
849            strand: Strand::Reverse,
850            index_in_path: 1,
851        };
852
853        let mut message = TypedBuilder::<accession_node::Owned>::new_default();
854        let mut root = message.init_root();
855        accession_node.write_capnp(&mut root);
856
857        let deserialized = AccessionNode::read_capnp(root.into_reader());
858        assert_eq!(accession_node, deserialized);
859    }
860
861    #[test]
862    fn test_accession_create_query() {
863        let conn = &get_connection(None).unwrap();
864        let (block_group_id, _path) = setup_block_group(conn);
865        let accession = Accession::create(
866            conn,
867            &NewAccession {
868                name: "test".to_string(),
869                block_group_id,
870                parent_accession_id: None,
871                spans: vec![AccessionSpan {
872                    node_id: HashId::convert_str("test-a-node"),
873                    range: Range { start: 0, end: 1 },
874                    strand: Strand::Forward,
875                }],
876            },
877        )
878        .unwrap();
879        let _accession_2 = Accession::create(
880            conn,
881            &NewAccession {
882                name: "test2".to_string(),
883                block_group_id,
884                parent_accession_id: None,
885                spans: vec![AccessionSpan {
886                    node_id: HashId::convert_str("test-a-node"),
887                    range: Range { start: 1, end: 2 },
888                    strand: Strand::Forward,
889                }],
890            },
891        )
892        .unwrap();
893        assert_eq!(
894            Accession::select(conn)
895                .name("test")
896                .load()
897                .expect("should query the accession by name"),
898            vec![Accession {
899                id: accession.id,
900                name: "test".to_string(),
901                block_group_id,
902                parent_accession_id: None,
903            }]
904        );
905    }
906
907    #[test]
908    fn test_create_from_new_accession_inserts_ordered_spans() {
909        let conn = &get_connection(None).unwrap();
910        let (block_group_id, _path) = setup_block_group(conn);
911        let new_accession = NewAccession {
912            name: "test".to_string(),
913            block_group_id,
914            parent_accession_id: None,
915            spans: vec![
916                AccessionSpan {
917                    node_id: HashId::convert_str("test-a-node"),
918                    range: Range { start: 2, end: 4 },
919                    strand: Strand::Forward,
920                },
921                AccessionSpan {
922                    node_id: HashId::convert_str("test-t-node"),
923                    range: Range { start: 0, end: 2 },
924                    strand: Strand::Forward,
925                },
926            ],
927        };
928
929        let accession = Accession::create(conn, &new_accession).unwrap();
930
931        assert_eq!(accession.name, "test");
932        let nodes = Accession::get_nodes_by_id(conn, &accession.id, None);
933        assert_eq!(nodes.len(), 2);
934        assert_eq!(nodes[0].node_id, HashId::convert_str("test-a-node"));
935        assert_eq!(nodes[0].index_in_path, 0);
936        assert_eq!(nodes[1].node_id, HashId::convert_str("test-t-node"));
937        assert_eq!(nodes[1].index_in_path, 1);
938    }
939
940    #[test]
941    fn test_get_or_create_returns_existing_accession_for_duplicate() {
942        let conn = &get_connection(None).unwrap();
943        let (block_group_id, _path) = setup_block_group(conn);
944        let new_accession = NewAccession {
945            name: "test".to_string(),
946            block_group_id,
947            parent_accession_id: None,
948            spans: vec![AccessionSpan {
949                node_id: HashId::convert_str("test-a-node"),
950                range: Range { start: 2, end: 4 },
951                strand: Strand::Forward,
952            }],
953        };
954
955        let first = Accession::create(conn, &new_accession).unwrap();
956        let second = Accession::get_or_create(conn, &new_accession).unwrap();
957
958        assert_eq!(second.id, first.id);
959        assert_eq!(Accession::get_nodes_by_id(conn, &second.id, None).len(), 1);
960    }
961
962    #[test]
963    fn get_or_create_rejects_duplicate_name_with_different_spans() {
964        let conn = &get_connection(None).unwrap();
965        let (block_group_id, _path) = setup_block_group(conn);
966        let new_accession = NewAccession {
967            name: "test".to_string(),
968            block_group_id,
969            parent_accession_id: None,
970            spans: vec![AccessionSpan {
971                node_id: HashId::convert_str("test-a-node"),
972                range: Range { start: 2, end: 4 },
973                strand: Strand::Forward,
974            }],
975        };
976        let different_spans = NewAccession {
977            spans: vec![AccessionSpan {
978                node_id: HashId::convert_str("test-a-node"),
979                range: Range { start: 3, end: 5 },
980                strand: Strand::Forward,
981            }],
982            ..new_accession.clone()
983        };
984
985        Accession::create(conn, &new_accession).unwrap();
986        let err = Accession::get_or_create(conn, &different_spans).unwrap_err();
987
988        assert!(matches!(err, AccessionError::Duplicate(_)));
989    }
990
991    #[test]
992    fn test_spans_from_intervaltree_ranges_preserve_range_order_and_clip_blocks() {
993        let conn = &get_connection(None).unwrap();
994        let (_block_group_id, path) = setup_block_group(conn);
995        let tree = path.intervaltree(conn).unwrap();
996
997        let spans = AccessionSpan::from_intervaltree_ranges(&tree, &[12..16, 2..4]).unwrap();
998
999        assert_eq!(
1000            spans,
1001            vec![
1002                AccessionSpan {
1003                    node_id: HashId::convert_str("test-t-node"),
1004                    range: Range { start: 2, end: 6 },
1005                    strand: Strand::Forward,
1006                },
1007                AccessionSpan {
1008                    node_id: HashId::convert_str("test-a-node"),
1009                    range: Range { start: 2, end: 4 },
1010                    strand: Strand::Forward,
1011                },
1012            ]
1013        );
1014    }
1015
1016    #[test]
1017    fn test_spans_from_intervaltree_ranges_errors_on_wraparound_range() {
1018        let conn = &get_connection(None).unwrap();
1019        let (_block_group_id, path) = setup_block_group(conn);
1020        let tree = path.intervaltree(conn).unwrap();
1021
1022        let range = StdRange { start: 35, end: 3 };
1023        let err = AccessionSpan::from_intervaltree_ranges(&tree, std::slice::from_ref(&range))
1024            .unwrap_err();
1025
1026        assert!(matches!(
1027            err,
1028            AccessionError::InvalidRange { start: 35, end: 3 }
1029        ));
1030    }
1031
1032    #[test]
1033    fn test_intervaltree() {
1034        let conn = &get_connection(None).unwrap();
1035        let (_bg, path) = setup_block_group(conn);
1036        let mut path_cache = PathCache::new(conn);
1037        let accession =
1038            BlockGroup::add_accession(conn, &path, "test", 5, 35, &mut path_cache).unwrap();
1039
1040        let tree = accession.intervaltree(conn).unwrap();
1041        interval_tree_verify(
1042            &tree,
1043            0,
1044            &[NodeIntervalBlock {
1045                node_id: HashId::convert_str("test-a-node"),
1046                start: 0,
1047                end: 5,
1048                sequence_start: 5,
1049                sequence_end: 10,
1050                strand: Strand::Forward,
1051            }],
1052        );
1053        interval_tree_verify(
1054            &tree,
1055            5,
1056            &[NodeIntervalBlock {
1057                node_id: HashId::convert_str("test-t-node"),
1058                start: 5,
1059                end: 15,
1060                sequence_start: 0,
1061                sequence_end: 10,
1062                strand: Strand::Forward,
1063            }],
1064        );
1065        interval_tree_verify(
1066            &tree,
1067            15,
1068            &[NodeIntervalBlock {
1069                node_id: HashId::convert_str("test-c-node"),
1070                start: 15,
1071                end: 25,
1072                sequence_start: 0,
1073                sequence_end: 10,
1074                strand: Strand::Forward,
1075            }],
1076        );
1077        interval_tree_verify(
1078            &tree,
1079            25,
1080            &[NodeIntervalBlock {
1081                node_id: HashId::convert_str("test-g-node"),
1082                start: 25,
1083                end: 30,
1084                sequence_start: 0,
1085                sequence_end: 5,
1086                strand: Strand::Forward,
1087            }],
1088        );
1089    }
1090
1091    #[test]
1092    fn test_accession_node_to_accession_blocks_conversion() {
1093        let conn = &get_connection(None).unwrap();
1094        let (block_group_id, _path) = setup_block_group(conn);
1095        let accession = Accession::create(
1096            conn,
1097            &NewAccession {
1098                name: "test".to_string(),
1099                block_group_id,
1100                parent_accession_id: None,
1101                spans: vec![
1102                    AccessionSpan {
1103                        node_id: HashId::convert_str("test-a-node"),
1104                        range: Range { start: 2, end: 4 },
1105                        strand: Strand::Forward,
1106                    },
1107                    AccessionSpan {
1108                        node_id: HashId::convert_str("test-t-node"),
1109                        range: Range { start: 0, end: 2 },
1110                        strand: Strand::Forward,
1111                    },
1112                ],
1113            },
1114        )
1115        .unwrap();
1116
1117        assert_eq!(
1118            accession.blocks(conn).unwrap(),
1119            vec![
1120                NodeIntervalBlock {
1121                    node_id: PATH_START_NODE_ID,
1122                    start: i64::MIN + 1,
1123                    end: 0,
1124                    sequence_start: 0,
1125                    sequence_end: 0,
1126                    strand: Strand::Forward,
1127                },
1128                NodeIntervalBlock {
1129                    node_id: HashId::convert_str("test-a-node"),
1130                    start: 0,
1131                    end: 2,
1132                    sequence_start: 2,
1133                    sequence_end: 4,
1134                    strand: Strand::Forward,
1135                },
1136                NodeIntervalBlock {
1137                    node_id: HashId::convert_str("test-t-node"),
1138                    start: 2,
1139                    end: 4,
1140                    sequence_start: 0,
1141                    sequence_end: 2,
1142                    strand: Strand::Forward,
1143                },
1144                NodeIntervalBlock {
1145                    node_id: PATH_END_NODE_ID,
1146                    start: 4,
1147                    end: i64::MAX - 1,
1148                    sequence_start: 0,
1149                    sequence_end: 0,
1150                    strand: Strand::Forward,
1151                },
1152            ],
1153        );
1154    }
1155
1156    #[test]
1157    fn test_query_accessions() {
1158        let conn = &get_connection(None).unwrap();
1159        let (block_group_id, _path) = setup_block_group(conn);
1160        let accession_1 = Accession::create(
1161            conn,
1162            &NewAccession {
1163                name: "test-1".to_string(),
1164                block_group_id,
1165                parent_accession_id: None,
1166                spans: vec![
1167                    AccessionSpan {
1168                        node_id: HashId::convert_str("test-a-node"),
1169                        range: Range { start: 2, end: 4 },
1170                        strand: Strand::Forward,
1171                    },
1172                    AccessionSpan {
1173                        node_id: HashId::convert_str("test-t-node"),
1174                        range: Range { start: 0, end: 2 },
1175                        strand: Strand::Reverse,
1176                    },
1177                ],
1178            },
1179        )
1180        .unwrap();
1181        let accession_2 = Accession::create(
1182            conn,
1183            &NewAccession {
1184                name: "test-2".to_string(),
1185                block_group_id,
1186                parent_accession_id: None,
1187                spans: vec![AccessionSpan {
1188                    node_id: HashId::convert_str("test-c-node"),
1189                    range: Range { start: 1, end: 3 },
1190                    strand: Strand::Forward,
1191                }],
1192            },
1193        )
1194        .unwrap();
1195        let accession_1_nodes = vec![
1196            AccessionNodeData {
1197                accession_id: accession_1.id,
1198                node_id: HashId::convert_str("test-a-node"),
1199                sequence_start: 2,
1200                sequence_end: 4,
1201                strand: Strand::Forward,
1202                index_in_path: 0,
1203            },
1204            AccessionNodeData {
1205                accession_id: accession_1.id,
1206                node_id: HashId::convert_str("test-t-node"),
1207                sequence_start: 0,
1208                sequence_end: 2,
1209                strand: Strand::Reverse,
1210                index_in_path: 1,
1211            },
1212        ];
1213        let accession_2_nodes = vec![AccessionNodeData {
1214            accession_id: accession_2.id,
1215            node_id: HashId::convert_str("test-c-node"),
1216            sequence_start: 1,
1217            sequence_end: 3,
1218            strand: Strand::Forward,
1219            index_in_path: 0,
1220        }];
1221
1222        let grouped =
1223            AccessionNode::query_accessions(conn, &[accession_2.id, accession_1.id]).unwrap();
1224
1225        assert_eq!(
1226            grouped.get(&accession_1.id).unwrap(),
1227            &accession_1_nodes
1228                .into_iter()
1229                .map(AccessionNode::from)
1230                .collect::<Vec<_>>()
1231        );
1232        assert_eq!(
1233            grouped.get(&accession_2.id).unwrap(),
1234            &accession_2_nodes
1235                .into_iter()
1236                .map(AccessionNode::from)
1237                .collect::<Vec<_>>()
1238        );
1239    }
1240
1241    #[test]
1242    fn test_create_from_edges() {
1243        let conn = &get_connection(None).unwrap();
1244        let (block_group_id, _path) = setup_block_group(conn);
1245        let path_edges = vec![
1246            AugmentedEdgeData {
1247                edge_data: EdgeData {
1248                    source_node_id: PATH_START_NODE_ID,
1249                    source_coordinate: -1,
1250                    source_strand: Strand::Forward,
1251                    target_node_id: HashId::convert_str("test-a-node"),
1252                    target_coordinate: 2,
1253                    target_strand: Strand::Forward,
1254                },
1255                chromosome_index: 0,
1256                phased: 0,
1257            },
1258            AugmentedEdgeData {
1259                edge_data: EdgeData {
1260                    source_node_id: HashId::convert_str("test-a-node"),
1261                    source_coordinate: 4,
1262                    source_strand: Strand::Forward,
1263                    target_node_id: HashId::convert_str("test-t-node"),
1264                    target_coordinate: 0,
1265                    target_strand: Strand::Reverse,
1266                },
1267                chromosome_index: 0,
1268                phased: 0,
1269            },
1270            AugmentedEdgeData {
1271                edge_data: EdgeData {
1272                    source_node_id: HashId::convert_str("test-t-node"),
1273                    source_coordinate: 2,
1274                    source_strand: Strand::Reverse,
1275                    target_node_id: PATH_END_NODE_ID,
1276                    target_coordinate: -1,
1277                    target_strand: Strand::Forward,
1278                },
1279                chromosome_index: 0,
1280                phased: 0,
1281            },
1282        ];
1283
1284        let accession =
1285            Accession::create_from_edges(conn, "test", &block_group_id, None, &path_edges).unwrap();
1286        let expected_nodes = vec![
1287            AccessionNodeData {
1288                accession_id: accession.id,
1289                node_id: HashId::convert_str("test-a-node"),
1290                sequence_start: 2,
1291                sequence_end: 4,
1292                strand: Strand::Forward,
1293                index_in_path: 0,
1294            },
1295            AccessionNodeData {
1296                accession_id: accession.id,
1297                node_id: HashId::convert_str("test-t-node"),
1298                sequence_start: 0,
1299                sequence_end: 2,
1300                strand: Strand::Reverse,
1301                index_in_path: 1,
1302            },
1303        ];
1304
1305        assert_eq!(
1306            Accession::get_nodes_by_id(conn, &accession.id, None),
1307            expected_nodes
1308                .into_iter()
1309                .map(AccessionNode::from)
1310                .collect::<Vec<_>>(),
1311        );
1312    }
1313
1314    #[test]
1315    fn test_length() {
1316        let conn = &get_connection(None).unwrap();
1317        let (_bg, path) = setup_block_group(conn);
1318        let mut path_cache = PathCache::new(conn);
1319        let accession =
1320            BlockGroup::add_accession(conn, &path, "test", 5, 35, &mut path_cache).unwrap();
1321
1322        assert_eq!(accession.length(conn).unwrap(), 30);
1323    }
1324}