Skip to main content

gen_models/
sequence.rs

1use std::{collections::HashMap, fs, str, sync};
2
3use cached::proc_macro::cached;
4use gen_core::{HashId, traits::Capnp};
5use noodles::{
6    bgzf::{self, gzi},
7    core::Region,
8    fasta::{self, fai, io::indexed_reader::Builder as IndexBuilder},
9};
10use rusqlite::{Row, params};
11use serde::{Deserialize, Serialize};
12use sha2::{Digest, Sha256};
13use thiserror::Error;
14
15use crate::{db::GraphConnection, gen_models_capnp::sequence, traits::*};
16
17#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
18pub struct Sequence {
19    pub hash: HashId,
20    pub sequence_type: String,
21    sequence: String,
22    // these 2 fields are only relevant when the sequence is stored externally
23    pub name: String,
24    pub file_path: String,
25    pub length: i64,
26    // indicates whether the sequence is stored externally, a quick flag instead of having to
27    // check sequence or file_path and do the logic in function calls.
28    pub external_sequence: bool,
29}
30
31#[derive(Debug, Error, PartialEq)]
32pub enum SequenceError {
33    #[error("Database error: {0}")]
34    DatabaseError(#[from] rusqlite::Error),
35    #[error("Sequence or file_path must be set.")]
36    NoSequence(),
37    #[error("A filepath must have an accompanying sequence name.")]
38    FilepathMissingSequenceName(),
39    #[error("Sequence length must be specified.")]
40    MissingSequenceLength(),
41    #[error("Sequence cache lock poisoned: {0}")]
42    CachePoisoned(String),
43    #[error("Invalid indexed sequence region '{name}': {reason}")]
44    InvalidRegion { name: String, reason: String },
45    #[error("Sequence I/O error: {0}")]
46    Io(String),
47    #[error("Invalid UTF-8 while reading sequence data: {0}")]
48    Utf8(String),
49    #[error("Sequence id '{name}' not found in fasta file {file_path}")]
50    IdMissing { file_path: String, name: String },
51    #[error("Sequence bounds out of range: start={start}, end={end}, length={length}")]
52    BoundsError { start: i64, end: i64, length: i64 },
53}
54
55impl<'a> Capnp<'a> for Sequence {
56    type Builder = sequence::Builder<'a>;
57    type Reader = sequence::Reader<'a>;
58
59    fn write_capnp(&self, builder: &mut Self::Builder) {
60        builder.set_hash(&self.hash.0).unwrap();
61        builder.set_sequence_type(&self.sequence_type);
62        builder.set_sequence(&self.sequence);
63        builder.set_name(&self.name);
64        builder.set_file_path(&self.file_path);
65        builder.set_length(self.length);
66        builder.set_external_sequence(self.external_sequence);
67    }
68
69    fn read_capnp(reader: Self::Reader) -> Self {
70        let hash = reader
71            .get_hash()
72            .unwrap()
73            .as_slice()
74            .unwrap()
75            .try_into()
76            .unwrap();
77        let sequence_type = reader.get_sequence_type().unwrap().to_string().unwrap();
78        let sequence = reader.get_sequence().unwrap().to_string().unwrap();
79        let name = reader.get_name().unwrap().to_string().unwrap();
80        let file_path = reader.get_file_path().unwrap().to_string().unwrap();
81        let length = reader.get_length();
82        let external_sequence = reader.get_external_sequence();
83
84        Sequence {
85            hash,
86            sequence_type,
87            sequence,
88            name,
89            file_path,
90            length,
91            external_sequence,
92        }
93    }
94}
95
96#[derive(Default, Debug)]
97pub struct NewSequence<'a> {
98    sequence_type: Option<&'a str>,
99    sequence: Option<&'a str>,
100    name: Option<&'a str>,
101    file_path: Option<&'a str>,
102    length: Option<i64>,
103    shallow: bool,
104}
105
106impl<'a> From<&'a Sequence> for NewSequence<'a> {
107    fn from(value: &'a Sequence) -> NewSequence<'a> {
108        NewSequence::new()
109            .sequence_type(&value.sequence_type)
110            .sequence(&value.sequence)
111            .name(&value.name)
112            .file_path(&value.file_path)
113            .length(value.length)
114    }
115}
116
117impl<'a> NewSequence<'a> {
118    pub fn new() -> NewSequence<'static> {
119        NewSequence {
120            shallow: false,
121            ..NewSequence::default()
122        }
123    }
124
125    pub fn shallow(mut self, setting: bool) -> Self {
126        self.shallow = setting;
127        self
128    }
129
130    pub fn sequence_type(mut self, seq_type: &'a str) -> Self {
131        self.sequence_type = Some(seq_type);
132        self
133    }
134
135    pub fn sequence(mut self, sequence: &'a str) -> Self {
136        self.sequence = Some(sequence);
137        self.length = Some(sequence.len() as i64);
138        self
139    }
140
141    pub fn name(mut self, name: &'a str) -> Self {
142        self.name = Some(name);
143        self
144    }
145
146    pub fn file_path(mut self, path: &'a str) -> Self {
147        if !path.is_empty() {
148            self.file_path = Some(path);
149            self.shallow = true;
150        }
151        self
152    }
153
154    pub fn length(mut self, length: i64) -> Self {
155        self.length = Some(length);
156        self
157    }
158
159    pub fn hash(&self) -> HashId {
160        let mut hasher = Sha256::new();
161        hasher.update(self.sequence_type.expect("Sequence type must be defined."));
162        hasher.update(";");
163        if let Some(v) = self.sequence {
164            hasher.update(v);
165        } else {
166            hasher.update("");
167        }
168        hasher.update(";");
169        if let Some(v) = self.name {
170            hasher.update(v);
171        } else {
172            hasher.update("");
173        }
174        hasher.update(";");
175        if let Some(v) = self.file_path {
176            hasher.update(v);
177        } else {
178            hasher.update("");
179        }
180        hasher.update(";");
181
182        HashId(hasher.finalize().into())
183    }
184
185    pub fn build(self) -> Sequence {
186        let file_path = self.file_path.unwrap_or("").to_string();
187        let external_sequence = !file_path.is_empty();
188        Sequence {
189            hash: self.hash(),
190            sequence_type: self.sequence_type.unwrap().to_string(),
191            sequence: self.sequence.unwrap_or("").to_string(),
192            name: self.name.unwrap_or("").to_string(),
193            file_path,
194            length: self.length.unwrap(),
195            external_sequence,
196        }
197    }
198
199    pub fn save(self, conn: &GraphConnection) -> Result<Sequence, SequenceError> {
200        let mut length = 0;
201        if self.sequence.is_none() && self.file_path.is_none() {
202            return Err(SequenceError::NoSequence());
203        }
204        if self.file_path.is_some() && self.name.is_none() {
205            return Err(SequenceError::FilepathMissingSequenceName());
206        }
207        if self.length.is_none() {
208            if let Some(v) = self.sequence {
209                length = v.len() as i64;
210            } else {
211                // TODO: if name/path specified, grab length automatically
212                return Err(SequenceError::MissingSequenceLength());
213            }
214        }
215        let hash = self.hash();
216        match conn.query_row(
217            "SELECT hash from sequences where hash = ?1;",
218            [hash],
219            |row| row.get::<_, HashId>(0),
220        ) {
221            Ok(_) => {}
222            Err(rusqlite::Error::QueryReturnedNoRows) => {
223                let mut stmt = conn.prepare("INSERT INTO sequences (hash, sequence_type, sequence, name, file_path, length) VALUES (?1, ?2, ?3, ?4, ?5, ?6);")?;
224                match stmt.execute(params![
225                    hash,
226                    self.sequence_type.unwrap().to_string(),
227                    if self.shallow {
228                        ""
229                    } else {
230                        self.sequence.unwrap()
231                    },
232                    self.name.unwrap_or(""),
233                    self.file_path.unwrap_or(""),
234                    self.length.unwrap_or(length)
235                ]) {
236                    Ok(_) => {}
237                    Err(err) => return Err(SequenceError::DatabaseError(err)),
238                }
239            }
240            Err(err) => return Err(SequenceError::DatabaseError(err)),
241        };
242
243        Ok(Sequence {
244            hash,
245            sequence_type: self.sequence_type.unwrap().to_string(),
246            sequence: self.sequence.unwrap_or("").to_string(),
247            name: self.name.unwrap_or("").to_string(),
248            file_path: self.file_path.unwrap_or("").to_string(),
249            length: self.length.unwrap_or(length),
250            external_sequence: !self.file_path.unwrap_or("").is_empty(),
251        })
252    }
253}
254
255#[cached(key = "String", convert = r#"{ format!("{}", path) }"#)]
256fn fasta_index(path: &str) -> Option<fai::Index> {
257    let index_path = format!("{path}.fai");
258    if fs::metadata(&index_path).is_ok() {
259        return Some(fai::fs::read(&index_path).unwrap());
260    }
261    None
262}
263
264#[cached(key = "String", convert = r#"{ format!("{}", path) }"#)]
265fn fasta_gzi_index(path: &str) -> Option<gzi::Index> {
266    let index_path = format!("{path}.gzi");
267    if fs::metadata(&index_path).is_ok() {
268        return Some(gzi::fs::read(&index_path).unwrap());
269    }
270    None
271}
272
273fn validate_sequence_bounds(
274    start: i64,
275    end: i64,
276    length: i64,
277) -> Result<(usize, usize), SequenceError> {
278    if start < 0 || end < 0 || start > length || end > length {
279        return Err(SequenceError::BoundsError { start, end, length });
280    }
281
282    Ok((start as usize, end as usize))
283}
284
285fn circular_sequence_slice(sequence: &str, start: i64, end: i64) -> Result<String, SequenceError> {
286    let length = sequence.len() as i64;
287    if length == 0 {
288        if start == 0 && end == 0 {
289            return Ok(String::new());
290        }
291        return Err(SequenceError::BoundsError { start, end, length });
292    }
293
294    let (start, end) = validate_sequence_bounds(start, end, length)?;
295    if start <= end {
296        return Ok(sequence[start..end].to_string());
297    }
298
299    let mut result = String::with_capacity((length as usize - start) + end);
300    result.push_str(&sequence[start..]);
301    result.push_str(&sequence[..end]);
302
303    Ok(result)
304}
305
306fn sequence_slice(
307    sequence: &str,
308    start: i64,
309    end: i64,
310    circular: bool,
311) -> Result<String, SequenceError> {
312    if circular {
313        return circular_sequence_slice(sequence, start, end);
314    }
315
316    let length = sequence.len() as i64;
317    let (start, end) = validate_sequence_bounds(start, end, length)?;
318    if start <= end {
319        return Ok(sequence[start..end].to_string());
320    }
321
322    Err(SequenceError::BoundsError {
323        start: start as i64,
324        end: end as i64,
325        length,
326    })
327}
328
329pub fn cached_sequence(
330    file_path: &str,
331    name: &str,
332    start: i64,
333    end: i64,
334    circular: bool,
335) -> Result<String, SequenceError> {
336    static SEQUENCE_CACHE: sync::LazyLock<sync::RwLock<HashMap<String, Option<String>>>> =
337        sync::LazyLock::new(|| sync::RwLock::new(HashMap::new()));
338    let key = format!("{file_path}-{name}");
339
340    {
341        let cache = SEQUENCE_CACHE
342            .read()
343            .map_err(|err| SequenceError::CachePoisoned(err.to_string()))?;
344        if let Some(cached_sequence) = cache.get(&key) {
345            if let Some(sequence) = cached_sequence {
346                return sequence_slice(sequence, start, end, circular);
347            }
348            return Err(SequenceError::IdMissing {
349                file_path: file_path.to_string(),
350                name: name.to_string(),
351            });
352        }
353    }
354
355    let mut cache = SEQUENCE_CACHE
356        .write()
357        .map_err(|err| SequenceError::CachePoisoned(err.to_string()))?;
358
359    let mut sequence: Option<String> = None;
360    if let Some(index) = fasta_index(file_path) {
361        let region = name
362            .parse::<Region>()
363            .map_err(|err| SequenceError::InvalidRegion {
364                name: name.to_string(),
365                reason: err.to_string(),
366            })?;
367        let builder = IndexBuilder::default().set_index(index);
368        if let Some(gzi_index) = fasta_gzi_index(file_path) {
369            let bgzf_reader = bgzf::io::indexed_reader::Builder::default()
370                .set_index(gzi_index)
371                .build_from_path(file_path)
372                .map_err(|err| SequenceError::Io(err.to_string()))?;
373            let mut reader = builder
374                .build_from_reader(bgzf_reader)
375                .map_err(|err| SequenceError::Io(err.to_string()))?;
376            sequence = Some(
377                str::from_utf8(
378                    reader
379                        .query(&region)
380                        .map_err(|err| SequenceError::Io(err.to_string()))?
381                        .sequence()
382                        .as_ref(),
383                )
384                .map_err(|err| SequenceError::Utf8(err.to_string()))?
385                .to_string(),
386            )
387        } else {
388            let mut reader = builder
389                .build_from_path(file_path)
390                .map_err(|err| SequenceError::Io(err.to_string()))?;
391            sequence = Some(
392                str::from_utf8(
393                    reader
394                        .query(&region)
395                        .map_err(|err| SequenceError::Io(err.to_string()))?
396                        .sequence()
397                        .as_ref(),
398                )
399                .map_err(|err| SequenceError::Utf8(err.to_string()))?
400                .to_string(),
401            );
402        }
403    } else {
404        let mut reader = fasta::io::reader::Builder
405            .build_from_path(file_path)
406            .map_err(|err| SequenceError::Io(err.to_string()))?;
407        for result in reader.records() {
408            let record = result.map_err(|err| SequenceError::Io(err.to_string()))?;
409            if String::from_utf8(record.name().to_vec())
410                .map_err(|err| SequenceError::Utf8(err.to_string()))?
411                == name
412            {
413                sequence = Some(
414                    str::from_utf8(record.sequence().as_ref())
415                        .map_err(|err| SequenceError::Utf8(err.to_string()))?
416                        .to_string(),
417                );
418                break;
419            }
420        }
421    }
422    // this is a LRU cache setup, we just keep the last sequence we fetched so we don't end up loading
423    // plant genomes into memory.
424    cache.clear();
425    cache.insert(key.clone(), sequence);
426    // we do this to avoid a clone of potentially large data.
427    if let Some(seq) = &cache[&key] {
428        return sequence_slice(seq, start, end, circular);
429    }
430    Err(SequenceError::IdMissing {
431        file_path: file_path.to_string(),
432        name: name.to_string(),
433    })
434}
435
436impl Sequence {
437    #[allow(clippy::new_ret_no_self)]
438    pub fn new() -> NewSequence<'static> {
439        NewSequence::new()
440    }
441
442    fn is_circular(&self) -> bool {
443        self.sequence_type
444            .split_whitespace()
445            .any(|part| part.eq_ignore_ascii_case("circular"))
446    }
447
448    pub fn get_sequence(
449        &self,
450        start: impl Into<Option<i64>>,
451        end: impl Into<Option<i64>>,
452    ) -> Result<String, SequenceError> {
453        // todo: handle circles
454
455        let start: Option<i64> = start.into();
456        let end: Option<i64> = end.into();
457        let start = start.unwrap_or(0);
458        let end = end.unwrap_or(self.length);
459        if self.external_sequence {
460            return cached_sequence(&self.file_path, &self.name, start, end, self.is_circular());
461        }
462        if start == 0 && end == self.length {
463            return Ok(self.sequence.clone());
464        }
465        sequence_slice(&self.sequence, start, end, self.is_circular())
466    }
467
468    pub fn delete_by_hash(conn: &GraphConnection, hash: &HashId) {
469        let mut stmt = conn
470            .prepare("delete from sequences where hash = ?1;")
471            .unwrap();
472        stmt.execute(params![hash]).unwrap();
473    }
474
475    pub fn query_by_blockgroup(conn: &GraphConnection, block_group_id: &HashId) -> Vec<Sequence> {
476        Sequence::query(
477            conn,
478            "select sequences.* from block_group_edges bge left join edges on bge.edge_id = edges.id left join nodes on (edges.source_node_id = nodes.id or edges.target_node_id = nodes.id) left join sequences on (nodes.sequence_hash = sequences.hash) where bge.block_group_id = ?1;",
479            params![block_group_id],
480        )
481    }
482}
483
484impl Query for Sequence {
485    type Model = Sequence;
486
487    const PRIMARY_KEY: &'static str = "hash";
488    const TABLE_NAME: &'static str = "sequences";
489
490    fn process_row(row: &Row) -> Self::Model {
491        let file_path: String = row.get(4).unwrap();
492        let mut external_sequence = false;
493        if !file_path.is_empty() {
494            external_sequence = true;
495        }
496        let hash: HashId = row.get(0).unwrap();
497        let sequence = row.get(2).unwrap();
498        Sequence {
499            hash,
500            sequence_type: row.get(1).unwrap(),
501            sequence,
502            name: row.get(3).unwrap(),
503            file_path,
504            length: row.get(5).unwrap(),
505            external_sequence,
506        }
507    }
508}
509
510pub fn reverse_complement(seq: &[u8]) -> Vec<u8> {
511    seq.iter()
512        .rev()
513        .map(|&base| match base.to_ascii_uppercase() {
514            b'A' => b'T',
515            b'T' => b'A',
516            b'C' => b'G',
517            b'G' => b'C',
518            b'U' => b'A',
519            b'N' => b'N',
520            b'R' => b'Y',
521            b'Y' => b'R',
522            b'S' => b'S',
523            b'W' => b'W',
524            b'K' => b'M',
525            b'M' => b'K',
526            b'B' => b'V',
527            b'V' => b'B',
528            b'D' => b'H',
529            b'H' => b'D',
530            _ => base,
531        })
532        .collect()
533}
534
535#[cfg(test)]
536mod tests {
537    // Note this useful idiom: importing names from outer (for mod tests) scope.
538    #[allow(unused_imports)]
539    use std::time;
540    use std::{fs::OpenOptions, io::Write};
541
542    use rand::RngExt;
543
544    use super::*;
545    use crate::test_helpers::get_connection;
546
547    #[test]
548    fn test_builder() {
549        let sequence = Sequence::new()
550            .sequence_type("DNA")
551            .sequence("ATCG")
552            .build();
553        assert_eq!(sequence.length, 4);
554        assert_eq!(sequence.sequence, "ATCG");
555    }
556
557    #[test]
558    fn test_builder_with_from_disk() {
559        let sequence = Sequence::new()
560            .sequence_type("DNA")
561            .name("chr1")
562            .file_path("/foo/bar")
563            .length(50)
564            .build();
565        assert_eq!(sequence.length, 50);
566        assert_eq!(sequence.sequence, "");
567    }
568
569    #[test]
570    fn test_create_sequence_in_db() {
571        let conn = &get_connection(None).unwrap();
572        let sequence = Sequence::new()
573            .sequence_type("DNA")
574            .sequence("AACCTT")
575            .save(conn)
576            .unwrap();
577        assert_eq!(&sequence.sequence, "AACCTT");
578        assert_eq!(sequence.sequence_type, "DNA");
579        assert!(!sequence.external_sequence);
580    }
581
582    #[test]
583    fn test_delete_sequence_by_hash() {
584        let conn = &get_connection(None).unwrap();
585        let before_count = Sequence::all(conn).len();
586        let sequence = Sequence::new()
587            .sequence_type("DNA")
588            .sequence("AACCTT")
589            .save(conn)
590            .unwrap();
591        let sequence2 = Sequence::new()
592            .sequence_type("DNA")
593            .sequence("AACCTTAA")
594            .save(conn)
595            .unwrap();
596
597        let sequences = Sequence::all(conn);
598        assert_eq!(sequences.len(), before_count + 2);
599
600        Sequence::delete_by_hash(conn, &sequence.hash);
601
602        let sequences = Sequence::all(conn);
603        assert_eq!(sequences.len(), before_count + 1);
604        assert!(sequences.iter().any(|s| s.hash == sequence2.hash));
605    }
606
607    #[test]
608    fn test_create_sequence_on_disk() {
609        let conn = &get_connection(None).unwrap();
610        let sequence = Sequence::new()
611            .sequence_type("DNA")
612            .name("chr1")
613            .file_path("/some/path.fa")
614            .length(10)
615            .save(conn)
616            .unwrap();
617        assert_eq!(sequence.sequence_type, "DNA");
618        assert_eq!(&sequence.sequence, "");
619        assert_eq!(sequence.name, "chr1");
620        assert_eq!(sequence.file_path, "/some/path.fa");
621        assert_eq!(sequence.length, 10);
622        assert!(sequence.external_sequence);
623    }
624
625    #[test]
626    fn test_get_sequence() {
627        let conn = &get_connection(None).unwrap();
628        let sequence = Sequence::new()
629            .sequence_type("DNA")
630            .sequence("ATCGATCGATCGATCGATCGGGAACACACAGAGA")
631            .save(conn)
632            .unwrap();
633        assert_eq!(
634            sequence.get_sequence(None, None).unwrap(),
635            "ATCGATCGATCGATCGATCGGGAACACACAGAGA"
636        );
637        assert_eq!(sequence.get_sequence(0, 5).unwrap(), "ATCGA");
638        assert_eq!(sequence.get_sequence(10, 15).unwrap(), "CGATC");
639        assert_eq!(
640            sequence.get_sequence(3, None).unwrap(),
641            "GATCGATCGATCGATCGGGAACACACAGAGA"
642        );
643        assert_eq!(sequence.get_sequence(None, 5).unwrap(), "ATCGA");
644        assert_eq!(
645            sequence.get_sequence(0, 100),
646            Err(SequenceError::BoundsError {
647                start: 0,
648                end: 100,
649                length: 34,
650            })
651        );
652        assert_eq!(
653            sequence.get_sequence(5, 2),
654            Err(SequenceError::BoundsError {
655                start: 5,
656                end: 2,
657                length: 34,
658            })
659        );
660    }
661
662    #[test]
663    fn test_get_sequence_circular() {
664        let conn = &get_connection(None).unwrap();
665        let sequence = Sequence::new()
666            .sequence_type("circular")
667            .sequence("AAACCCTTT")
668            .save(conn)
669            .unwrap();
670        assert_eq!(sequence.get_sequence(4, 2).unwrap(), "CCTTTAA");
671        assert_eq!(
672            sequence.get_sequence(0, 10),
673            Err(SequenceError::BoundsError {
674                start: 0,
675                end: 10,
676                length: 9,
677            })
678        );
679    }
680
681    #[test]
682    fn test_get_sequence_from_disk() {
683        let conn = &get_connection(None).unwrap();
684        let temp_dir = tempfile::tempdir().unwrap();
685        let temp_file_path = temp_dir.path().join("simple.fa");
686        fs::write(
687            &temp_file_path,
688            ">m123\nATCGATCGATCGATCGATCGGGAACACACAGAGA\n",
689        )
690        .unwrap();
691        let seq = Sequence::new()
692            .sequence_type("DNA")
693            .name("m123")
694            .file_path(temp_file_path.to_str().unwrap())
695            .length(34)
696            .save(conn)
697            .unwrap();
698        assert_eq!(
699            seq.get_sequence(None, None).unwrap(),
700            "ATCGATCGATCGATCGATCGGGAACACACAGAGA"
701        );
702        assert_eq!(seq.get_sequence(0, 5).unwrap(), "ATCGA");
703        assert_eq!(seq.get_sequence(10, 15).unwrap(), "CGATC");
704        assert_eq!(
705            seq.get_sequence(3, None).unwrap(),
706            "GATCGATCGATCGATCGGGAACACACAGAGA"
707        );
708        assert_eq!(seq.get_sequence(None, 5).unwrap(), "ATCGA");
709    }
710
711    #[test]
712    fn test_get_sequence_from_disk_circular() {
713        let conn = &get_connection(None).unwrap();
714        let temp_dir = tempfile::tempdir().unwrap();
715        let temp_file_path = temp_dir.path().join("simple.fa");
716        fs::write(&temp_file_path, ">m123\nAAACCCTTT\n").unwrap();
717        let seq = Sequence::new()
718            .sequence_type("circular")
719            .name("m123")
720            .file_path(temp_file_path.to_str().unwrap())
721            .length(9)
722            .save(conn)
723            .unwrap();
724        assert_eq!(seq.get_sequence(4, 2).unwrap(), "CCTTTAA");
725        assert_eq!(
726            seq.get_sequence(0, 10),
727            Err(SequenceError::BoundsError {
728                start: 0,
729                end: 10,
730                length: 9,
731            })
732        );
733    }
734
735    #[test]
736    // #[cfg(feature = "benchmark")]
737    fn test_cached_sequence_performance() {
738        let conn = &get_connection(None).unwrap();
739        let temp_dir = tempfile::tempdir().unwrap();
740        let temp_file_path = temp_dir.path().join("large.fa");
741        let mut file = OpenOptions::new()
742            .append(true)
743            .create(true)
744            .open(&temp_file_path)
745            .unwrap();
746        writeln!(file, ">chr22").unwrap();
747        for _ in 1..3_000_000 {
748            writeln!(
749                file,
750                "ATCGATCGATCGATCGATCGGGAACACACAGAGAATCGATCGATCGATCGATCGGGAACACACAGAGA"
751            )
752            .unwrap();
753        }
754        // write index
755        let index_path = temp_dir.path().join("large.fa.fai");
756        fs::write(&index_path, "chr22	203999932	7	68	69\n").unwrap();
757        let sequence = Sequence::new()
758            .sequence_type("DNA")
759            .file_path(temp_file_path.to_str().unwrap())
760            .name("chr22")
761            .length(203_999_932)
762            .save(conn)
763            .unwrap();
764        let s = time::Instant::now();
765        for _ in 1..1_000_000 {
766            let start = rand::rng().random_range(1..200_000_000);
767
768            sequence.get_sequence(start, start + 20).unwrap();
769        }
770        let elapsed = s.elapsed().as_secs();
771        assert!(
772            elapsed < 5,
773            "Cached sequence benchmark failed: {elapsed}s elapsed"
774        );
775    }
776
777    #[test]
778    fn test_capnp_serialization() {
779        use capnp::message::TypedBuilder;
780
781        let sequence = Sequence {
782            hash: HashId::convert_str("test_hash"),
783            sequence_type: "DNA".to_string(),
784            sequence: "ATCG".to_string(),
785            name: "test_seq".to_string(),
786            file_path: "/path/to/file".to_string(),
787            length: 4,
788            external_sequence: false,
789        };
790
791        let mut message = TypedBuilder::<sequence::Owned>::new_default();
792        let mut root = message.init_root();
793        sequence.write_capnp(&mut root);
794
795        let deserialized = Sequence::read_capnp(root.into_reader());
796        assert_eq!(sequence, deserialized);
797    }
798}