gen-models 0.3.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use std::rc::Rc;

use gen_core::{DoltHashId, HashId};
use rusqlite::{ToSql, named_params, params, types::Value};
use serde::{Deserialize, Serialize};

use crate::{
    assets::{AssetRef, OperationAsset, OperationKind, OperationLog},
    db::GraphConnection,
    file_types::FileTypes,
    operations::OperationFileInfo,
};

/// An executable statement returned by DoltLite's `dolt_patch` table function.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct DoltPatchStatement {
    /// The order in which DoltLite requires this statement to be applied.
    pub statement_order: i64,
    /// The resolved commit hash for the beginning of the patch range.
    pub from_commit_hash: DoltHashId,
    /// The resolved commit hash for the end of the patch range.
    pub to_commit_hash: DoltHashId,
    /// The table changed by the statement.
    pub table_name: String,
    /// Whether the statement changes the table's schema or its data.
    pub diff_type: String,
    /// The SQL statement generated by DoltLite.
    pub statement: String,
}

/// Identify operations between two commits
pub fn operation_logs_added_between(
    conn: &GraphConnection,
    from_ref: &str,
    to_ref: &str,
) -> rusqlite::Result<Vec<(HashId, OperationKind)>> {
    let mut statement = conn.prepare(
        "SELECT to_id, to_operation_kind, diff_type FROM dolt_diff_gen_operation_log(?1, ?2)",
    )?;
    let rows = statement.query_map(params![from_ref, to_ref], |row| {
        Ok((
            row.get::<_, Option<HashId>>(0)?,
            row.get::<_, Option<OperationKind>>(1)?,
            row.get::<_, String>(2)?,
        ))
    })?;

    rows.filter_map(|row| match row {
        Ok((Some(log_id), operation_kind, diff_type)) if diff_type == "added" => Some(Ok((
            log_id,
            operation_kind.unwrap_or(OperationKind::HistoryCommit),
        ))),
        Ok(_) => None,
        Err(error) => Some(Err(error)),
    })
    .collect()
}

pub fn operation_logs_at_ref(
    conn: &GraphConnection,
    history_ref: &str,
) -> rusqlite::Result<Vec<(HashId, OperationKind)>> {
    let operation_logs_table = OperationLog::table_name_with_history_ref(Some(history_ref));
    let query =
        format!("SELECT id, operation_kind FROM {operation_logs_table} ORDER BY created_on, id");
    let mut statement = conn.prepare(&query)?;
    let rows = statement.query_map(named_params! { ":history_ref": history_ref }, |row| {
        Ok((row.get::<_, HashId>(0)?, row.get::<_, OperationKind>(1)?))
    })?;
    rows.collect::<Result<Vec<_>, _>>()
}

/// From the list of log ids (operation logs), return the operation files (such as fastas) associated with each one.
pub fn operation_asset_files_for_logs(
    conn: &GraphConnection,
    log_ids: &[HashId],
    history_ref: Option<&str>,
) -> rusqlite::Result<Vec<OperationFileInfo>> {
    if log_ids.is_empty() {
        return Ok(Vec::new());
    }

    let operation_assets_table = OperationAsset::table_name_with_history_ref(history_ref);
    let asset_refs_table = AssetRef::table_name_with_history_ref(history_ref);
    let query = format!(
        "SELECT asset_refs.id, asset_refs.uri, asset_refs.file_type, asset_refs.checksum, \
         asset_refs.logical_path, asset_refs.name \
         FROM {operation_assets_table} operation_assets \
         JOIN {asset_refs_table} asset_refs ON asset_refs.id = operation_assets.asset_ref_id \
         WHERE operation_assets.log_id IN rarray(:log_ids) \
         ORDER BY asset_refs.created_on, asset_refs.name, operation_assets.role",
    );
    let mut statement = conn.prepare(&query)?;
    let log_values = Rc::new(
        log_ids
            .iter()
            .map(|log_id| Value::from(*log_id))
            .collect::<Vec<_>>(),
    );
    let mut query_params: Vec<(&str, &dyn ToSql)> = vec![(":log_ids", &log_values)];
    if let Some(history_ref) = history_ref.as_ref() {
        query_params.push((":history_ref", history_ref));
    }

    statement
        .query_map(&query_params[..], |row| {
            let asset_uri = row.get::<_, String>(1)?;
            let file_type = row.get::<_, String>(2)?;
            let logical_path = row.get::<_, Option<String>>(4)?;
            let name = row.get::<_, Option<String>>(5)?;
            let file_type = FileTypes::from_storage_tag(&file_type);
            let file_path = patch_file_path(&asset_uri, logical_path.as_deref());
            let filename = patch_file_name(&asset_uri, logical_path.as_deref(), name.as_deref());
            Ok(OperationFileInfo {
                id: row.get(0)?,
                filename,
                file_path,
                asset_uri,
                file_type,
                checksum: row.get(3)?,
            })
        })?
        .collect::<Result<Vec<_>, _>>()
}

/// Loads DoltLite's ordered schema and data statements for a commit range.
pub fn load_dolt_patch(
    conn: &GraphConnection,
    from_ref: &str,
    to_ref: &str,
) -> rusqlite::Result<Vec<DoltPatchStatement>> {
    let mut query = conn.prepare(
        "SELECT statement_order, from_commit_hash, to_commit_hash, table_name, diff_type, \
         statement FROM dolt_patch(?1, ?2) ORDER BY statement_order",
    )?;
    let rows = query.query_map(params![from_ref, to_ref], |row| {
        Ok(DoltPatchStatement {
            statement_order: row.get("statement_order")?,
            from_commit_hash: row.get("from_commit_hash")?,
            to_commit_hash: row.get("to_commit_hash")?,
            table_name: row.get("table_name")?,
            diff_type: row.get("diff_type")?,
            statement: row.get("statement")?,
        })
    })?;
    rows.collect::<Result<Vec<_>, _>>()
}

/// Applies ordered statements produced by [`load_dolt_patch`] as one transaction.
///
/// Schema and data statements are applied together in their native `statement_order`. Foreign key
/// enforcement remains enabled, but its checks are deferred until the transaction commits so
/// related rows may be changed in either order without allowing an invalid final state.
pub fn apply_dolt_patch(
    conn: &GraphConnection,
    patch: &[DoltPatchStatement],
) -> rusqlite::Result<()> {
    if patch.is_empty() {
        return Ok(());
    }

    conn.execute_batch("PRAGMA foreign_keys = ON;")?;
    conn.execute_batch("BEGIN IMMEDIATE;")?;
    if let Err(error) = conn.execute_batch("PRAGMA defer_foreign_keys = ON;") {
        let _ = conn.execute_batch("ROLLBACK;");
        return Err(error);
    }
    for patch_statement in patch {
        if let Err(error) = conn.execute_batch(&patch_statement.statement) {
            let _ = conn.execute_batch("ROLLBACK;");
            return Err(error);
        }
    }
    if let Err(error) = conn.execute_batch("COMMIT;") {
        let _ = conn.execute_batch("ROLLBACK;");
        return Err(error);
    }
    Ok(())
}

fn patch_file_path(asset_uri: &str, logical_path: Option<&str>) -> String {
    logical_path.unwrap_or(asset_uri).to_string()
}

fn patch_file_name(asset_uri: &str, logical_path: Option<&str>, name: Option<&str>) -> String {
    if let Some(name) = name {
        return name.to_string();
    }

    let path = logical_path.unwrap_or(asset_uri.strip_prefix("file://").unwrap_or(asset_uri));
    std::path::Path::new(path)
        .file_name()
        .and_then(|value| value.to_str())
        .unwrap_or(path)
        .to_string()
}

#[cfg(test)]
mod tests {
    use gen_core::{DoltHashId, HashId};
    use rusqlite::Connection;

    use super::{
        DoltPatchStatement, apply_dolt_patch, load_dolt_patch, operation_asset_files_for_logs,
    };
    use crate::{
        assets::{AssetRef, AssetRole, OperationAsset, OperationKind, OperationLog},
        db::GraphConnection,
        file_types::FileTypes,
        history::dolt::commit_all,
        test_helpers::setup_gen,
    };

    fn create_base_connection() -> GraphConnection {
        let conn = GraphConnection(Connection::open_in_memory().expect("should open database"));
        conn.execute_batch(
            "CREATE TABLE patch_items (
                collection_name TEXT NOT NULL,
                item_id INTEGER NOT NULL,
                value TEXT NOT NULL,
                PRIMARY KEY (collection_name, item_id)
             );
             INSERT INTO patch_items VALUES ('default', 1, 'before');",
        )
        .expect("should create base table");
        commit_all(&conn, "base").expect("should commit base table");
        conn
    }

    fn patch_statement(statement_order: i64, statement: &str) -> DoltPatchStatement {
        DoltPatchStatement {
            statement_order,
            from_commit_hash: DoltHashId::default(),
            to_commit_hash: DoltHashId::default(),
            table_name: "patch_children".to_string(),
            diff_type: "data".to_string(),
            statement: statement.to_string(),
        }
    }

    #[test]
    fn test_operation_asset_files_for_logs_preserves_missing_checksum() {
        let context = setup_gen();
        let conn = context.graph().conn();
        let log = OperationLog {
            id: HashId::convert_str("checksumless-log"),
            operation_kind: OperationKind::AddFile,
            command: "add remote file".to_string(),
            created_on: 1,
        };
        let asset = AssetRef {
            id: HashId::convert_str("checksumless-asset"),
            uri: "s3://private-bucket/reference.fa".to_string(),
            file_type: FileTypes::Fasta.as_str().to_string(),
            checksum: None,
            size: None,
            role: AssetRole::Input,
            logical_path: Some("inputs/reference.fa".to_string()),
            name: Some("reference.fa".to_string()),
            created_on: 1,
            upstream_asset_ref_id: None,
        };
        OperationLog::create(conn, &log).expect("should create operation log");
        AssetRef::create(conn, &asset).expect("should create checksumless asset");
        OperationAsset::create(
            conn,
            &OperationAsset {
                log_id: log.id,
                asset_ref_id: asset.id,
                role: AssetRole::Input,
            },
        )
        .expect("should link checksumless asset");

        let files = operation_asset_files_for_logs(conn, &[log.id], None)
            .expect("should load checksumless operation asset");

        assert_eq!(files.len(), 1);
        assert_eq!(files[0].asset_uri, asset.uri);
        assert_eq!(files[0].file_path, "inputs/reference.fa");
        assert_eq!(files[0].checksum, None);
    }

    #[test]
    fn test_dolt_patch_applies_schema_and_data_statements() {
        let source = create_base_connection();
        source
            .execute_batch(
                "ALTER TABLE patch_items ADD COLUMN note TEXT NOT NULL DEFAULT 'base';
                 CREATE INDEX patch_items_value_idx ON patch_items(value);
                 UPDATE patch_items
                 SET value = 'after', note = 'updated'
                 WHERE collection_name = 'default' AND item_id = 1;
                 INSERT INTO patch_items VALUES ('default', 2, 'added', 'new');",
            )
            .expect("should change source schema and data");
        commit_all(&source, "target").expect("should commit target state");

        let patch = load_dolt_patch(&source, "HEAD~1", "HEAD")
            .expect("should load native Dolt patch statements");
        assert!(
            patch
                .iter()
                .any(|statement| statement.diff_type == "schema"),
            "patch should contain schema statements"
        );
        assert!(
            patch.iter().any(|statement| statement.diff_type == "data"),
            "patch should contain data statements"
        );
        assert!(
            patch
                .windows(2)
                .all(|statements| statements[0].statement_order < statements[1].statement_order),
            "patch statements should preserve DoltLite ordering"
        );

        let target = create_base_connection();
        apply_dolt_patch(&target, &patch).expect("should apply native Dolt patch");

        let columns = target
            .prepare("PRAGMA table_info(patch_items)")
            .expect("should inspect target schema")
            .query_map([], |row| row.get::<_, String>("name"))
            .expect("should query target columns")
            .collect::<Result<Vec<_>, _>>()
            .expect("should decode target columns");
        assert!(columns.iter().any(|column| column == "note"));
        let index_exists = target
            .query_row(
                "SELECT EXISTS(
                    SELECT 1 FROM sqlite_master
                    WHERE type = 'index' AND name = 'patch_items_value_idx'
                )",
                [],
                |row| row.get::<_, bool>(0),
            )
            .expect("should inspect target indexes");
        assert!(index_exists, "patch should create the target index");
        let rows = target
            .prepare(
                "SELECT collection_name, item_id, value, note
                 FROM patch_items ORDER BY collection_name, item_id",
            )
            .expect("should query patched rows")
            .query_map([], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, i64>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, String>(3)?,
                ))
            })
            .expect("should read patched rows")
            .collect::<Result<Vec<_>, _>>()
            .expect("should decode patched rows");
        assert_eq!(
            rows,
            vec![
                (
                    "default".to_string(),
                    1,
                    "after".to_string(),
                    "updated".to_string()
                ),
                (
                    "default".to_string(),
                    2,
                    "added".to_string(),
                    "new".to_string()
                ),
            ]
        );
    }

    #[test]
    fn test_apply_dolt_patch_defers_and_validates_foreign_keys() {
        let conn = GraphConnection(Connection::open_in_memory().expect("should open database"));
        conn.execute_batch(
            "PRAGMA foreign_keys = ON;
             CREATE TABLE patch_parents (
                 id INTEGER PRIMARY KEY
             );
             CREATE TABLE patch_children (
                 id INTEGER PRIMARY KEY,
                 parent_id INTEGER NOT NULL REFERENCES patch_parents(id)
             );",
        )
        .expect("should create related patch tables");

        let out_of_order_patch = vec![
            patch_statement(
                1,
                "INSERT INTO patch_children (id, parent_id) VALUES (1, 1);",
            ),
            patch_statement(2, "INSERT INTO patch_parents (id) VALUES (1);"),
        ];
        apply_dolt_patch(&conn, &out_of_order_patch)
            .expect("should defer foreign keys until the complete patch is applied");

        let invalid_patch = vec![patch_statement(
            1,
            "INSERT INTO patch_children (id, parent_id) VALUES (2, 999);",
        )];
        apply_dolt_patch(&conn, &invalid_patch)
            .expect_err("should reject a patch with a foreign key violation");

        let children = conn
            .query_row("SELECT COUNT(*) FROM patch_children", [], |row| {
                row.get::<_, i64>(0)
            })
            .expect("should count child rows");
        assert_eq!(
            children, 1,
            "the invalid patch should be rolled back completely"
        );
        let violations = conn
            .query_row("SELECT COUNT(*) FROM pragma_foreign_key_check", [], |row| {
                row.get::<_, i64>(0)
            })
            .expect("should check referential integrity");
        assert_eq!(violations, 0, "the database should remain consistent");
        let foreign_keys_enabled = conn
            .query_row("PRAGMA foreign_keys", [], |row| row.get::<_, bool>(0))
            .expect("should read foreign key enforcement state");
        assert!(
            foreign_keys_enabled,
            "foreign key enforcement should remain enabled"
        );
    }
}