Skip to main content

gen_models/
accession.rs

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