1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
//! Code for enabling UTA access.
//!
//! C.f. https://github.com/biocommons/uta

use indexmap::IndexMap;
use postgres::{Client, NoTls, Row};
use quick_cache::sync::Cache;
use std::fmt::Debug;
use std::sync::Mutex;

use crate::sequences::seq_md5;
use crate::static_data::{Assembly, ASSEMBLY_INFOS};

use crate::data::{
    error::Error, interface, interface::GeneInfoRecord, interface::TxExonsRecord,
    interface::TxForRegionRecord, interface::TxIdentityInfo, interface::TxInfoRecord,
    interface::TxMappingOptionsRecord, interface::TxSimilarityRecord,
};

/// Configuration for the `data::uta::Provider`.
#[derive(Debug, PartialEq, Clone)]
pub struct Config {
    /// URL with the connection string, e.g.
    /// `"postgresql://anonymous:anonymous@uta.biocommons.org/uta'"`.
    pub db_url: String,
    /// The databaser schema to use, corresponds to the data version, e.g., `uta_20210129`.
    pub db_schema: String,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            db_url: "postgresql://anonymous:anonymous@uta.biocommons.org:5432\
            /uta"
                .to_string(),
            db_schema: "uta_20210129".to_string(),
        }
    }
}

impl TryFrom<Row> for GeneInfoRecord {
    type Error = Error;

    fn try_from(row: Row) -> Result<Self, Self::Error> {
        let aliases: String = row.try_get("aliases")?;
        let aliases = aliases.split(',').map(|s| s.to_owned()).collect::<Vec<_>>();
        Ok(Self {
            hgnc: row.try_get("hgnc")?,
            maploc: row.try_get("maploc")?,
            descr: row.try_get("descr")?,
            summary: row.try_get("summary")?,
            aliases,
            added: row.try_get("added")?,
        })
    }
}

impl TryFrom<Row> for TxSimilarityRecord {
    type Error = Error;

    fn try_from(row: Row) -> Result<Self, Self::Error> {
        Ok(Self {
            tx_ac1: row.try_get("tx_ac1")?,
            tx_ac2: row.try_get("tx_ac2")?,
            hgnc_eq: row.try_get("hgnc_eq").unwrap_or(false),
            cds_eq: row.try_get("cds_eq").unwrap_or(false),
            es_fp_eq: row.try_get("es_fp_eq").unwrap_or(false),
            cds_es_fp_eq: row.try_get("cds_es_fp_eq").unwrap_or(false),
            cds_exon_lengths_fp_eq: row.try_get("cds_exon_lengths_fp_eq").unwrap_or(false),
        })
    }
}

impl TryFrom<Row> for TxExonsRecord {
    type Error = Error;

    fn try_from(row: Row) -> Result<Self, Self::Error> {
        Ok(Self {
            hgnc: row.try_get("hgnc")?,
            tx_ac: row.try_get("tx_ac")?,
            alt_ac: row.try_get("alt_ac")?,
            alt_aln_method: row.try_get("alt_aln_method")?,
            alt_strand: row.try_get("alt_strand")?,
            ord: row.try_get("ord")?,
            tx_start_i: row.try_get("tx_start_i")?,
            tx_end_i: row.try_get("tx_end_i")?,
            alt_start_i: row.try_get("alt_start_i")?,
            alt_end_i: row.try_get("alt_end_i")?,
            cigar: row.try_get("cigar")?,
            tx_aseq: row.try_get("tx_aseq")?,
            alt_aseq: row.try_get("alt_aseq")?,
            tx_exon_set_id: row.try_get("tx_exon_set_id")?,
            alt_exon_set_id: row.try_get("alt_exon_set_id")?,
            tx_exon_id: row.try_get("tx_exon_id")?,
            alt_exon_id: row.try_get("alt_exon_id")?,
            exon_aln_id: row.try_get("exon_aln_id")?,
        })
    }
}

impl TryFrom<Row> for TxForRegionRecord {
    type Error = Error;

    fn try_from(row: Row) -> Result<Self, Self::Error> {
        Ok(Self {
            tx_ac: row.try_get("tx_ac")?,
            alt_ac: row.try_get("alt_ac")?,
            alt_strand: row.try_get("alt_strand")?,
            alt_aln_method: row.try_get("alt_aln_method")?,
            start_i: row.try_get("start_i")?,
            end_i: row.try_get("end_i")?,
        })
    }
}

impl TryFrom<Row> for TxIdentityInfo {
    type Error = Error;

    fn try_from(row: Row) -> Result<Self, Self::Error> {
        Ok(Self {
            tx_ac: row.try_get("tx_ac")?,
            alt_ac: row.try_get("alt_ac")?,
            alt_aln_method: row.try_get("alt_aln_method")?,
            cds_start_i: row.try_get("cds_start_i")?,
            cds_end_i: row.try_get("cds_end_i")?,
            lengths: row.try_get("lengths")?,
            hgnc: row.try_get("hgnc")?,
        })
    }
}

impl TryFrom<Row> for TxInfoRecord {
    type Error = Error;

    fn try_from(row: Row) -> Result<Self, Self::Error> {
        Ok(Self {
            hgnc: row.try_get("hgnc")?,
            cds_start_i: row.try_get("cds_start_i")?,
            cds_end_i: row.try_get("cds_end_i")?,
            tx_ac: row.try_get("tx_ac")?,
            alt_ac: row.try_get("alt_ac")?,
            alt_aln_method: row.try_get("alt_aln_method")?,
        })
    }
}

impl TryFrom<Row> for TxMappingOptionsRecord {
    type Error = Error;

    fn try_from(row: Row) -> Result<Self, Self::Error> {
        Ok(Self {
            tx_ac: row.try_get("tx_ac")?,
            alt_ac: row.try_get("alt_ac")?,
            alt_aln_method: row.try_get("alt_aln_method")?,
        })
    }
}

/// Caches for the Provider data structure.
struct ProviderCaches {
    get_gene_info: Cache<String, GeneInfoRecord>,
    get_pro_ac_for_tx_ac: Cache<String, Option<String>>,
    get_acs_for_protein_seq: Cache<String, Vec<String>>,
    get_similar_transcripts: Cache<String, Vec<TxSimilarityRecord>>,
    get_tx_exons: Cache<(String, String, String), Vec<TxExonsRecord>>,
    get_tx_for_gene: Cache<String, Vec<TxInfoRecord>>,
    get_tx_for_region: Cache<(String, String, i32, i32), Vec<TxForRegionRecord>>,
    get_tx_identity_info: Cache<String, TxIdentityInfo>,
    get_tx_info: Cache<(String, String, String), TxInfoRecord>,
    get_tx_mapping_options: Cache<String, Vec<TxMappingOptionsRecord>>,
}

impl ProviderCaches {
    fn new(items_capacity: usize) -> Self {
        Self {
            get_gene_info: Cache::new(items_capacity),
            get_pro_ac_for_tx_ac: Cache::new(items_capacity),
            get_acs_for_protein_seq: Cache::new(items_capacity),
            get_similar_transcripts: Cache::new(items_capacity),
            get_tx_exons: Cache::new(items_capacity),
            get_tx_for_gene: Cache::new(items_capacity),
            get_tx_for_region: Cache::new(items_capacity),
            get_tx_identity_info: Cache::new(items_capacity),
            get_tx_info: Cache::new(items_capacity),
            get_tx_mapping_options: Cache::new(items_capacity),
        }
    }
}

/// This provider provides information from a UTA Postgres database only.
///
/// The sequences are also read from the database which implies that no genome contig information
/// is available.  Use `uta_sr::Provider` for a variant that is enabled to use a SeqRepo.
pub struct Provider {
    /// Configuration for the access.
    config: Config,
    /// Connection to the postgres database.
    conn: Mutex<Client>,
    /// The schema version, set on creation.
    schema_version: String,
    /// Caches for the individual queries.
    caches: ProviderCaches,
}

impl Debug for Provider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Provider")
            .field("config", &self.config)
            .field("conn", &"...")
            .finish()
    }
}

impl Provider {
    pub fn with_config(config: &Config) -> Result<Self, Error> {
        let config = config.clone();
        let conn = Mutex::new(Client::connect(&config.db_url, NoTls)?);
        let schema_version = Self::fetch_schema_version(
            &mut conn.lock().expect("cannot obtain connection lock"),
            &config.db_schema,
        )?;
        Ok(Self {
            config,
            conn,
            schema_version,
            caches: ProviderCaches::new(10),
        })
    }

    fn fetch_schema_version(conn: &mut Client, db_schema: &str) -> Result<String, Error> {
        let sql = format!("select key, value from {db_schema}.meta where key = 'schema_version'");
        let row = conn.query_one(&sql, &[])?;
        Ok(row.get("value"))
    }
}

impl interface::Provider for Provider {
    fn data_version(&self) -> &str {
        &self.config.db_schema
    }

    fn schema_version(&self) -> &str {
        &self.schema_version
    }

    fn get_assembly_map(&self, assembly: Assembly) -> IndexMap<String, String> {
        IndexMap::from_iter(
            ASSEMBLY_INFOS[assembly]
                .sequences
                .iter()
                .map(|record| (record.refseq_ac.clone(), record.name.clone())),
        )
    }

    fn get_gene_info(&self, hgnc: &str) -> Result<GeneInfoRecord, Error> {
        if let Some(result) = self.caches.get_gene_info.get(hgnc) {
            return Ok(result);
        }

        let sql = format!(
            "SELECT * FROM {}.gene WHERE hgnc = $1",
            self.config.db_schema
        );
        let result: GeneInfoRecord = self
            .conn
            .lock()
            .expect("cannot obtain connection lock")
            .query_one(&sql, &[&hgnc])?
            .try_into()?;

        self.caches
            .get_gene_info
            .insert(hgnc.to_string(), result.clone());
        Ok(result)
    }

    fn get_pro_ac_for_tx_ac(&self, tx_ac: &str) -> Result<Option<String>, Error> {
        if let Some(result) = self.caches.get_pro_ac_for_tx_ac.get(tx_ac) {
            return Ok(result);
        }

        let sql = format!(
            "SELECT pro_ac FROM {}.associated_accessions \
            WHERE tx_ac = $1 ORDER BY pro_ac DESC",
            self.config.db_schema
        );
        if let Some(row) = (self
            .conn
            .lock()
            .expect("cannot obtain connection lock")
            .query(&sql, &[&tx_ac])?)
        .into_iter()
        .next()
        {
            let result = Some(row.try_get("pro_ac")?);
            self.caches
                .get_pro_ac_for_tx_ac
                .insert(tx_ac.to_string(), None);
            Ok(result)
        } else {
            self.caches
                .get_pro_ac_for_tx_ac
                .insert(tx_ac.to_string(), None);
            Ok(None)
        }
    }

    fn get_seq_part(
        &self,
        ac: &str,
        begin: Option<usize>,
        end: Option<usize>,
    ) -> Result<String, Error> {
        // NB: no caching
        let sql = format!(
            "SELECT seq_id FROM {}.seq_anno WHERE ac = $1",
            self.config.db_schema
        );
        let seq_id: String = self
            .conn
            .lock()
            .expect("cannot obtain connection lock")
            .query_one(&sql, &[&ac])?
            .try_get("seq_id")?;

        let sql = format!(
            "SELECT seq FROM {}.seq WHERE seq_id = $1",
            self.config.db_schema
        );
        let seq: String = self
            .conn
            .lock()
            .expect("cannot obtain connection lock")
            .query_one(&sql, &[&seq_id])?
            .try_get("seq")?;

        let begin = begin.unwrap_or_default();
        let end = end
            .map(|end| std::cmp::min(end, seq.len()))
            .unwrap_or(seq.len());
        Ok(seq[begin..end].into())
    }

    fn get_acs_for_protein_seq(&self, seq: &str) -> Result<Vec<String>, Error> {
        let md5 = seq_md5(seq, true)?;
        if let Some(result) = self.caches.get_acs_for_protein_seq.get(&md5) {
            return Ok(result);
        }

        let sql = format!(
            "SELECT ac FROM {}.seq_anno WHERE seq_id = $1",
            self.config.db_schema
        );
        let mut result = Vec::new();
        for row in self
            .conn
            .lock()
            .expect("cannot obtain connection lock")
            .query(&sql, &[&md5])?
        {
            result.push(row.get(0));
        }
        // Add sentinel sequence.
        result.push(format!("MD5_{}", &md5));

        self.caches
            .get_acs_for_protein_seq
            .insert(md5, result.clone());
        Ok(result)
    }

    fn get_similar_transcripts(&self, tx_ac: &str) -> Result<Vec<TxSimilarityRecord>, Error> {
        if let Some(result) = self.caches.get_similar_transcripts.get(tx_ac) {
            return Ok(result);
        }

        let sql = format!(
            "SELECT * FROM {}.tx_similarity_v \
            WHERE tx_ac1 = $1 \
            ORDER BY tx_ac1, tx_ac2",
            self.config.db_schema
        );
        let mut result = Vec::new();
        for row in self
            .conn
            .lock()
            .expect("cannot obtain connection lock")
            .query(&sql, &[&tx_ac])?
        {
            result.push(row.try_into()?);
        }

        self.caches
            .get_similar_transcripts
            .insert(tx_ac.to_string(), result.clone());
        Ok(result)
    }

    fn get_tx_exons(
        &self,
        tx_ac: &str,
        alt_ac: &str,
        alt_aln_method: &str,
    ) -> Result<Vec<TxExonsRecord>, Error> {
        let key = (
            tx_ac.to_string(),
            alt_ac.to_string(),
            alt_aln_method.to_string(),
        );
        if let Some(result) = self.caches.get_tx_exons.get(&key) {
            return Ok(result);
        }

        let sql = format!(
            "SELECT * FROM {}.tx_exon_aln_v \
            WHERE tx_ac = $1 AND alt_ac = $2 and alt_aln_method = $3 \
            ORDER BY alt_start_i",
            self.config.db_schema
        );
        let mut result = Vec::new();
        for row in self
            .conn
            .lock()
            .expect("cannot obtain connection lock")
            .query(&sql, &[&tx_ac, &alt_ac, &alt_aln_method])?
        {
            result.push(row.try_into()?);
        }
        if result.is_empty() {
            Err(Error::NoTxExons(
                tx_ac.to_string(),
                alt_ac.to_string(),
                alt_aln_method.to_string(),
            ))
        } else {
            self.caches.get_tx_exons.insert(key, result.clone());
            Ok(result)
        }
    }

    fn get_tx_for_gene(&self, gene: &str) -> Result<Vec<TxInfoRecord>, Error> {
        if let Some(result) = self.caches.get_tx_for_gene.get(gene) {
            return Ok(result);
        }

        let sql = format!(
            "SELECT hgnc, cds_start_i, cds_end_i, tx_ac, alt_ac, alt_aln_method \
            FROM {}.transcript T \
            JOIN {}.exon_set es ON T.ac=ES.tx_ac WHERE alt_aln_method != 'transcript' \
            AND hgnc = $1
            ORDER BY hgnc, cds_start_i, cds_end_i, tx_ac, alt_ac, alt_aln_method",
            self.config.db_schema, self.config.db_schema,
        );
        let mut result = Vec::new();
        for row in self
            .conn
            .lock()
            .expect("cannot obtain connection lock")
            .query(&sql, &[&gene])?
        {
            result.push(row.try_into()?);
        }

        self.caches
            .get_tx_for_gene
            .insert(gene.to_string(), result.clone());
        Ok(result)
    }

    fn get_tx_for_region(
        &self,
        alt_ac: &str,
        alt_aln_method: &str,
        start_i: i32,
        end_i: i32,
    ) -> Result<Vec<TxForRegionRecord>, Error> {
        let key = (
            alt_ac.to_string(),
            alt_aln_method.to_string(),
            start_i,
            end_i,
        );
        if let Some(result) = self.caches.get_tx_for_region.get(&key) {
            return Ok(result);
        }

        let sql = format!(
            "SELECT tx_ac, alt_ac, alt_strand, alt_aln_method, \
                    min(start_i) AS start_i, max(end_i) AS end_i \
            FROM {}.exon_set es \
            JOIN {}.exon e ON es.exon_set_id = e.exon_set_id \
            WHERE alt_ac = $1
            GROUP BY tx_ac, alt_ac, alt_strand, alt_aln_method
            HAVING MIN(start_i) < $2 AND $3 <= MAX(end_i)
            ORDER BY tx_ac, alt_ac, alt_strand, alt_aln_method, start_i, end_i",
            self.config.db_schema, self.config.db_schema,
        );
        let mut result = Vec::new();
        for row in self
            .conn
            .lock()
            .expect("cannot obtain connection lock")
            .query(&sql, &[&alt_ac, &start_i, &end_i])?
        {
            let record: TxForRegionRecord = row.try_into()?;
            // NB: The original Python code did not use alt_aln_method in the query either.
            if record.alt_aln_method == alt_aln_method {
                result.push(record);
            }
        }

        self.caches.get_tx_for_region.insert(key, result.clone());
        Ok(result)
    }

    fn get_tx_identity_info(&self, tx_ac: &str) -> Result<TxIdentityInfo, Error> {
        if let Some(result) = self.caches.get_tx_identity_info.get(tx_ac) {
            return Ok(result);
        }

        let sql = format!(
            "SELECT DISTINCT(tx_ac), alt_ac, alt_aln_method, cds_start_i, \
                    cds_end_i, lengths, hgnc \
            FROM {}.tx_def_summary_v \
            WHERE tx_ac = $1 \
            ORDER BY tx_ac, alt_ac, alt_aln_method, cds_start_i, cds_end_i, lengths, hgnc",
            self.config.db_schema
        );
        let result: TxIdentityInfo = self
            .conn
            .lock()
            .expect("cannot obtain connection lock")
            .query_one(&sql, &[&tx_ac])?
            .try_into()?;

        self.caches
            .get_tx_identity_info
            .insert(tx_ac.to_string(), result.clone());
        Ok(result)
    }

    fn get_tx_info(
        &self,
        tx_ac: &str,
        alt_ac: &str,
        alt_aln_method: &str,
    ) -> Result<TxInfoRecord, Error> {
        let key = (
            tx_ac.to_string(),
            alt_ac.to_string(),
            alt_aln_method.to_string(),
        );
        if let Some(result) = self.caches.get_tx_info.get(&key) {
            return Ok(result);
        }

        let sql = format!(
            "SELECT hgnc, cds_start_i, cds_end_i, tx_ac, alt_ac, alt_aln_method
            FROM {}.transcript t \
            JOIN {}.exon_set es ON t.ac=es.tx_ac \
            WHERE tx_ac = $1 AND alt_ac = $2 AND alt_aln_method = $3 \
            ORDER BY hgnc, cds_start_i, cds_end_i, tx_ac, alt_ac, alt_aln_method",
            self.config.db_schema, self.config.db_schema,
        );
        let result: TxInfoRecord = self
            .conn
            .lock()
            .expect("cannot obtain connection lock")
            .query_one(&sql, &[&tx_ac, &alt_ac, &alt_aln_method])?
            .try_into()?;

        self.caches.get_tx_info.insert(key, result.clone());
        Ok(result)
    }

    fn get_tx_mapping_options(&self, tx_ac: &str) -> Result<Vec<TxMappingOptionsRecord>, Error> {
        if let Some(result) = self.caches.get_tx_mapping_options.get(tx_ac) {
            return Ok(result);
        }

        let sql = format!(
            "SELECT DISTINCT tx_ac, alt_ac, alt_aln_method \
            FROM {}.tx_exon_aln_v \
            WHERE tx_ac = $1 AND exon_aln_id IS NOT NULL \
            ORDER BY tx_ac, alt_ac, alt_aln_method",
            self.config.db_schema
        );
        let mut result = Vec::new();
        for row in self
            .conn
            .lock()
            .expect("cannot obtain connection lock")
            .query(&sql, &[&tx_ac])?
        {
            result.push(row.try_into()?);
        }

        self.caches
            .get_tx_mapping_options
            .insert(tx_ac.to_string(), result.clone());
        Ok(result)
    }
}

#[cfg(test)]
mod test {
    use crate::{data::interface::Provider as InterfaceProvider, static_data::Assembly};
    use anyhow::Error;

    use super::{Config, Provider};

    #[test]
    fn test_sync() {
        fn is_sync<T: Sync>() {}
        is_sync::<super::Provider>();
    }

    fn get_config() -> Config {
        Config {
            db_url: std::env::var("TEST_UTA_DATABASE_URL")
                .expect("Environment variable TEST_UTA_DATABASE_URL undefined!"),
            db_schema: std::env::var("TEST_UTA_DATABASE_SCHEMA")
                .expect("Environment variable TEST_UTA_DATABASE_SCHEMA undefined!"),
        }
    }

    #[test]
    fn construction() -> Result<(), Error> {
        let config = get_config();
        let provider = Provider::with_config(&config)?;

        assert_eq!(provider.data_version(), config.db_schema);
        assert_eq!(provider.schema_version(), "1.1");

        Ok(())
    }

    #[test]
    fn get_assembly_map() -> Result<(), Error> {
        let provider = Provider::with_config(&get_config())?;

        let am37 = provider.get_assembly_map(Assembly::Grch37);
        assert_eq!(am37.len(), 92);
        assert_eq!(am37.get("NC_000001.10"), Some(&"1".to_string()));

        let am38 = provider.get_assembly_map(Assembly::Grch38);
        assert_eq!(am38.len(), 455);
        assert_eq!(am38.get("NC_000001.11"), Some(&"1".to_string()));

        Ok(())
    }

    #[test]
    fn get_gene_info() -> Result<(), Error> {
        let provider = Provider::with_config(&get_config())?;

        assert_eq!(
            format!("{:?}", provider.get_gene_info("OMA1")?),
            "GeneInfoRecord { hgnc: \"OMA1\", maploc: \"1p32.2-p32.1\", \
            descr: \"OMA1 zinc metallopeptidase\", summary: \"OMA1 zinc metallopeptidase\", \
            aliases: [\"{2010001O09Rik\", \"DAB1\", \"MPRP-1\", \"MPRP1\", \"YKR087C\", \
            \"ZMPOMA1\", \"peptidase}\"], added: 2014-02-10T22:59:21.153414 }"
        );

        Ok(())
    }

    #[test]
    fn get_pro_ac_for_tx_ac() -> Result<(), Error> {
        let provider = Provider::with_config(&get_config())?;

        assert_eq!(
            provider.get_pro_ac_for_tx_ac("NM_130831.2")?,
            Some("NP_570844.1".to_string())
        );
        assert_eq!(provider.get_pro_ac_for_tx_ac("NM_130831.x")?, None);

        Ok(())
    }

    #[test]
    fn get_seq() -> Result<(), Error> {
        let provider = Provider::with_config(&get_config())?;

        assert_eq!(provider.get_seq("NM_001354664.1")?.len(), 6386);

        Ok(())
    }

    #[test]
    fn get_seq_part() -> Result<(), Error> {
        let provider = Provider::with_config(&get_config())?;

        assert_eq!(
            provider
                .get_seq_part("NM_001354664.1", Some(10), Some(100))?
                .len(),
            90
        );

        Ok(())
    }

    #[test]
    fn get_similar_transcripts() -> Result<(), Error> {
        let provider = Provider::with_config(&get_config())?;

        let records = provider.get_similar_transcripts("NM_001354664.1")?;

        assert_eq!(records.len(), 38,);
        assert_eq!(
            format!("{:?}", &records[0]),
            "TxSimilarityRecord { tx_ac1: \"NM_001354664.1\", tx_ac2: \
            \"ENST00000361150\", hgnc_eq: true, cds_eq: false, es_fp_eq: \
            false, cds_es_fp_eq: false, cds_exon_lengths_fp_eq: false }",
        );

        Ok(())
    }

    #[test]
    fn get_tx_exons() -> Result<(), Error> {
        let provider = Provider::with_config(&get_config())?;

        let records = provider.get_tx_exons("NM_001354664.1", "NC_000003.11", "splign")?;

        assert_eq!(records.len(), 30,);
        assert_eq!(
            format!("{:?}", &records[0]),
            "TxExonsRecord { hgnc: \"OPA1\", tx_ac: \"NM_001354664.1\", \
            alt_ac: \"NC_000003.11\", alt_aln_method: \"splign\", alt_strand: 1, \
            ord: 0, tx_start_i: 0, tx_end_i: 266, alt_start_i: 193310932, alt_end_i: \
            193311198, cigar: \"266=\", tx_aseq: None, alt_aseq: None, \
            tx_exon_set_id: 837345, alt_exon_set_id: 840099, tx_exon_id: 7236723, \
            alt_exon_id: 7270903, exon_aln_id: 4626713 }",
        );

        Ok(())
    }

    #[test]
    fn get_tx_for_gene() -> Result<(), Error> {
        let provider = Provider::with_config(&get_config())?;

        let records = provider.get_tx_for_gene("OMA1")?;

        assert_eq!(records.len(), 21,);
        assert_eq!(
            format!("{:?}", &records[0]),
            "TxInfoRecord { hgnc: \"OMA1\", cds_start_i: Some(0), cds_end_i: \
            Some(985), tx_ac: \"ENST00000421528\", alt_ac: \"NC_000001.10\", \
            alt_aln_method: \"genebuild\" }",
        );

        Ok(())
    }

    #[test]
    fn get_tx_for_region() -> Result<(), Error> {
        let provider = Provider::with_config(&get_config())?;

        let records = provider.get_tx_for_region("NC_000001.10", "splign", 58946391, 59012446)?;

        assert_eq!(records.len(), 2,);
        assert_eq!(
            format!("{:?}", &records[0]),
            "TxForRegionRecord { tx_ac: \"NM_145243.3\", alt_ac: \"NC_000001.10\", \
            alt_strand: -1, alt_aln_method: \"splign\", start_i: 58946390, \
            end_i: 59012446 }",
        );

        Ok(())
    }

    #[test]
    fn get_tx_identity_info() -> Result<(), Error> {
        let provider = Provider::with_config(&get_config())?;

        let record = provider.get_tx_identity_info("ENST00000421528")?;

        assert_eq!(
            format!("{:?}", &record),
            "TxIdentityInfo { tx_ac: \"ENST00000421528\", alt_ac: \"ENST00000421528\", \
            alt_aln_method: \"transcript\", cds_start_i: 0, cds_end_i: 985, lengths: \
            [24, 229, 174, 108, 129, 75, 150, 143, 1073], hgnc: \"OMA1\" }",
        );

        Ok(())
    }

    #[test]
    fn get_tx_info() -> Result<(), Error> {
        let provider = Provider::with_config(&get_config())?;

        let record = provider.get_tx_info("ENST00000421528", "NC_000001.10", "genebuild")?;

        assert_eq!(
            format!("{:?}", &record),
            "TxInfoRecord { hgnc: \"OMA1\", cds_start_i: Some(0), cds_end_i: \
            Some(985), tx_ac: \"ENST00000421528\", alt_ac: \"NC_000001.10\", \
            alt_aln_method: \"genebuild\" }",
        );

        Ok(())
    }

    #[test]
    fn get_tx_mapping_options() -> Result<(), Error> {
        let provider = Provider::with_config(&get_config())?;

        let records = provider.get_tx_mapping_options("ENST00000421528")?;

        assert_eq!(records.len(), 1);
        assert_eq!(
            format!("{:?}", &records[0]),
            "TxMappingOptionsRecord { tx_ac: \"ENST00000421528\", alt_ac: \"NC_000001.10\", \
            alt_aln_method: \"genebuild\" }",
        );

        Ok(())
    }
}

// <LICENSE>
// Copyright 2023 hgvs-rs Contributors
// Copyright 2014 Bioutils Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </LICENSE>