gen-models 0.5.1

Models for the gen sequence graph and version control system.
Documentation
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
use std::{
    fmt::Debug,
    fs,
    ops::{Add, Deref, DerefMut},
    rc::Rc,
    sync::OnceLock,
};

use gen_core::{
    HashId, PATH_END_NODE_ID, PATH_START_NODE_ID, Strand, config::Workspace,
    errors::ConnectionError,
};
use intervaltree::IntervalTree;
use rusqlite::Connection;
use tempfile::{TempDir, tempdir};

use crate::{
    block_group::{BlockGroup, NewBlockGroup},
    block_group_edge::{BlockGroupEdge, BlockGroupEdgeData},
    collection::Collection,
    db::{ConfigConnection, DbContext, GraphConnection},
    edge::Edge,
    migrations::{run_config_migrations, run_migrations},
    node::Node,
    path::Path,
    sample::{NewSample, Sample},
    sequence::Sequence,
};

/// Owns a database context and the temporary workspace created for a test.
///
/// Cloned fixtures share the workspace guard. Raw context or handle clones must not outlive their
/// owning fixture because production database models do not own test directories.
#[derive(Clone)]
pub struct TestContext {
    context: DbContext,
    _temp_dir: Rc<TempDir>,
}

impl TestContext {
    /// Keeps the temporary workspace alive until the final fixture clone drops.
    pub fn new(context: DbContext, temp_dir: TempDir) -> Self {
        Self {
            context,
            _temp_dir: Rc::new(temp_dir),
        }
    }

    /// Borrows the context for runtime structures that store a raw database context.
    ///
    /// Keep this fixture alive as long as any raw context or handle clone is used.
    pub fn db_context(&self) -> &DbContext {
        &self.context
    }
}

impl Deref for TestContext {
    type Target = DbContext;

    fn deref(&self) -> &Self::Target {
        &self.context
    }
}

impl DerefMut for TestContext {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.context
    }
}

pub fn create_bg(
    conn: &GraphConnection,
    collection_name: &str,
    sample_name: &str,
    name: &str,
) -> BlockGroup {
    Sample::get_or_create(
        conn,
        NewSample {
            name: sample_name,
            ..Default::default()
        },
    )
    .unwrap();
    BlockGroup::create(
        conn,
        NewBlockGroup {
            collection_name,
            sample_name,
            name,
            ..Default::default()
        },
    )
    .unwrap()
}

pub fn get_connection<'a>(
    db_path: impl Into<Option<&'a str>>,
) -> Result<GraphConnection, ConnectionError> {
    let path: Option<&str> = db_path.into();
    let mut conn;
    if let Some(v) = path {
        if fs::metadata(v).is_ok() {
            fs::remove_file(v).expect("Unable to remove database entry.");
        }
        conn = Connection::open(v).map_err(ConnectionError::OpenFailed)?;
    } else {
        conn = Connection::open_in_memory().map_err(ConnectionError::OpenFailed)?;
    }
    rusqlite::vtab::array::load_module(&conn)?;
    run_migrations(&mut conn);
    Ok(GraphConnection(conn))
}

pub fn get_config_connection<'a>(
    db_path: impl Into<Option<&'a str>>,
) -> Result<ConfigConnection, ConnectionError> {
    let path: Option<&str> = db_path.into();
    let mut conn;
    if let Some(v) = path {
        if fs::metadata(v).is_ok() {
            fs::remove_file(v).expect("Unable to remove database entry.");
        }
        conn = Connection::open(v).map_err(ConnectionError::OpenFailed)?;
    } else {
        conn = Connection::open_in_memory().map_err(ConnectionError::OpenFailed)?;
    }
    rusqlite::vtab::array::load_module(&conn)?;
    run_config_migrations(&mut conn);
    Ok(ConfigConnection(conn))
}

pub fn setup_gen() -> TestContext {
    let tmp_dir = tempdir().unwrap();
    let workspace = Workspace::new(tmp_dir.path());
    workspace.ensure_gen_dir();
    let graph_conn = get_connection(None).unwrap();
    let config_conn = get_config_connection(None).unwrap();
    TestContext::new(
        DbContext::new(workspace, graph_conn, config_conn).unwrap(),
        tmp_dir,
    )
}

pub fn setup_gen_on_disk() -> TestContext {
    let tmp_dir = tempdir().unwrap();
    let workspace = Workspace::new(tmp_dir.path());
    workspace.ensure_gen_dir();
    let graph_conn = get_connection(workspace.graph_db_path().unwrap().to_str().unwrap()).unwrap();
    let config_conn = get_config_connection(workspace.gen_db_path().unwrap().to_str()).unwrap();
    TestContext::new(
        DbContext::new(workspace, graph_conn, config_conn).unwrap(),
        tmp_dir,
    )
}

pub fn test_workspace() -> &'static Workspace {
    static WORKSPACE: OnceLock<Workspace> = OnceLock::new();

    WORKSPACE.get_or_init(|| {
        let workspace = Workspace::new(tempdir().unwrap().keep());
        workspace.ensure_gen_dir();
        workspace
    })
}

pub fn setup_block_group(conn: &GraphConnection) -> (HashId, Path) {
    let a_seq = Sequence::new()
        .sequence_type("DNA")
        .sequence("AAAAAAAAAA")
        .save(conn)
        .unwrap();
    let a_node_id = Node::create(conn, &a_seq.hash, &HashId::convert_str("test-a-node")).unwrap();
    let t_seq = Sequence::new()
        .sequence_type("DNA")
        .sequence("TTTTTTTTTT")
        .save(conn)
        .unwrap();
    let t_node_id = Node::create(conn, &t_seq.hash, &HashId::convert_str("test-t-node")).unwrap();
    let c_seq = Sequence::new()
        .sequence_type("DNA")
        .sequence("CCCCCCCCCC")
        .save(conn)
        .unwrap();
    let c_node_id = Node::create(conn, &c_seq.hash, &HashId::convert_str("test-c-node")).unwrap();
    let g_seq = Sequence::new()
        .sequence_type("DNA")
        .sequence("GGGGGGGGGG")
        .save(conn)
        .unwrap();
    let g_node_id = Node::create(conn, &g_seq.hash, &HashId::convert_str("test-g-node")).unwrap();
    Collection::get_or_create(conn, "test").unwrap();
    Sample::get_or_create(
        conn,
        NewSample {
            name: "test",
            ..Default::default()
        },
    )
    .unwrap();
    let block_group = create_bg(conn, "test", "test", "chr1");
    let edge0 = Edge::create(
        conn,
        PATH_START_NODE_ID,
        0,
        Strand::Forward,
        a_node_id,
        0,
        Strand::Forward,
    )
    .unwrap();
    let edge1 = Edge::create(
        conn,
        a_node_id,
        10,
        Strand::Forward,
        t_node_id,
        0,
        Strand::Forward,
    )
    .unwrap();
    let edge2 = Edge::create(
        conn,
        t_node_id,
        10,
        Strand::Forward,
        c_node_id,
        0,
        Strand::Forward,
    )
    .unwrap();
    let edge3 = Edge::create(
        conn,
        c_node_id,
        10,
        Strand::Forward,
        g_node_id,
        0,
        Strand::Forward,
    )
    .unwrap();
    let edge4 = Edge::create(
        conn,
        g_node_id,
        10,
        Strand::Forward,
        PATH_END_NODE_ID,
        0,
        Strand::Forward,
    )
    .unwrap();

    let block_group_edges = vec![
        BlockGroupEdgeData {
            block_group_id: block_group.id,
            edge_id: edge0.id,
            chromosome_index: 0,
            phased: 0,
        },
        BlockGroupEdgeData {
            block_group_id: block_group.id,
            edge_id: edge1.id,
            chromosome_index: 0,
            phased: 0,
        },
        BlockGroupEdgeData {
            block_group_id: block_group.id,
            edge_id: edge2.id,
            chromosome_index: 0,
            phased: 0,
        },
        BlockGroupEdgeData {
            block_group_id: block_group.id,
            edge_id: edge3.id,
            chromosome_index: 0,
            phased: 0,
        },
        BlockGroupEdgeData {
            block_group_id: block_group.id,
            edge_id: edge4.id,
            chromosome_index: 0,
            phased: 0,
        },
    ];
    BlockGroupEdge::bulk_create(conn, &block_group_edges);

    let path = Path::create(
        conn,
        "chr1",
        &block_group.id,
        &[edge0.id, edge1.id, edge2.id, edge3.id, edge4.id],
    )
    .unwrap();
    (block_group.id, path)
}

pub fn interval_tree_verify<K, V>(tree: &IntervalTree<K, V>, i: K, expected: &[V])
where
    K: Ord + Add<i64, Output = K> + Copy,
    V: Copy + Ord + Debug,
{
    let mut v1: Vec<_> = tree.query_point(i).map(|x| x.value).collect();
    v1.sort();
    let mut v2: Vec<_> = tree.query(i..(i + 1)).map(|x| x.value).collect();
    v2.sort();
    let mut expected = expected.to_vec();
    expected.sort();
    assert_eq!(v1, expected);
    assert_eq!(v2, expected);
}

pub fn run_query(conn: &Connection, query: &str) {
    let mut stmt = conn.prepare(query).unwrap();
    for _ in stmt
        .query_map([], |row| {
            dbg!(&row);
            Ok(())
        })
        .unwrap()
    {}
}

#[cfg(test)]
mod tests {
    use std::{fs, panic::AssertUnwindSafe};

    use super::{TestContext, setup_gen, setup_gen_on_disk};

    fn assert_temp_dir_lives_until_last_context_clone_drop(context: TestContext) {
        let base_dir = context.workspace().base_dir().to_path_buf();
        let nested_asset = context
            .workspace()
            .asset_dir()
            .expect("should resolve workspace asset directory")
            .join("nested/fixture.txt");
        fs::create_dir_all(
            nested_asset
                .parent()
                .expect("should have a parent directory"),
        )
        .expect("should create nested fixture asset directory");
        fs::write(&nested_asset, "temporary workspace asset")
            .expect("should write nested fixture asset");

        let context_clone = context.clone();
        drop(context);
        assert!(
            base_dir.is_dir(),
            "context clone should keep workspace alive"
        );
        assert_eq!(
            fs::read_to_string(&nested_asset).expect("should read nested fixture asset"),
            "temporary workspace asset"
        );

        assert_eq!(
            context_clone
                .graph()
                .conn()
                .query_row("SELECT 1", [], |row| row.get::<_, i64>(0))
                .expect("should query through cloned context"),
            1
        );
        drop(context_clone);
        assert!(
            !base_dir.exists(),
            "workspace should be removed after its last owner drops"
        );
    }

    #[test]
    fn test_setup_gen_temp_dir_cleanup() {
        assert_temp_dir_lives_until_last_context_clone_drop(setup_gen());
    }

    #[test]
    fn test_setup_gen_on_disk_temp_dir_cleanup() {
        assert_temp_dir_lives_until_last_context_clone_drop(setup_gen_on_disk());
    }

    #[test]
    fn test_setup_gen_on_disk_temp_dir_cleanup_during_unwind() {
        let mut base_dir = None;
        let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
            let context = setup_gen_on_disk();
            base_dir = Some(context.workspace().base_dir().to_path_buf());
            let fixture_asset = context
                .workspace()
                .asset_dir()
                .expect("should resolve workspace asset directory")
                .join("nested/fixture.txt");
            fs::create_dir_all(
                fixture_asset
                    .parent()
                    .expect("should have a parent directory"),
            )
            .expect("should create nested fixture asset directory");
            fs::write(fixture_asset, "temporary workspace asset")
                .expect("should write nested fixture asset");
            panic!("exercise temporary workspace cleanup during unwind");
        }));

        assert!(result.is_err(), "closure should unwind");
        let base_dir = base_dir.expect("should reach panic after workspace setup");
        assert!(
            !base_dir.exists(),
            "workspace should be removed during unwind"
        );
    }
}