Skip to main content

gen_models/
accession.rs

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