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