Skip to main content

gen_models/
patch.rs

1use std::rc::Rc;
2
3use gen_core::{DoltHashId, HashId};
4use rusqlite::{ToSql, named_params, params, types::Value};
5use serde::{Deserialize, Serialize};
6
7use crate::{
8    assets::{AssetRef, OperationAsset, OperationKind, OperationLog},
9    db::GraphConnection,
10    file_types::FileTypes,
11    operations::OperationFileInfo,
12};
13
14/// An executable statement returned by DoltLite's `dolt_patch` table function.
15#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
16pub struct DoltPatchStatement {
17    /// The order in which DoltLite requires this statement to be applied.
18    pub statement_order: i64,
19    /// The resolved commit hash for the beginning of the patch range.
20    pub from_commit_hash: DoltHashId,
21    /// The resolved commit hash for the end of the patch range.
22    pub to_commit_hash: DoltHashId,
23    /// The table changed by the statement.
24    pub table_name: String,
25    /// Whether the statement changes the table's schema or its data.
26    pub diff_type: String,
27    /// The SQL statement generated by DoltLite.
28    pub statement: String,
29}
30
31/// Identify operations between two commits
32pub fn operation_logs_added_between(
33    conn: &GraphConnection,
34    from_ref: &str,
35    to_ref: &str,
36) -> rusqlite::Result<Vec<(HashId, OperationKind)>> {
37    let mut statement = conn.prepare(
38        "SELECT to_id, to_operation_kind, diff_type FROM dolt_diff_gen_operation_log(?1, ?2)",
39    )?;
40    let rows = statement.query_map(params![from_ref, to_ref], |row| {
41        Ok((
42            row.get::<_, Option<HashId>>(0)?,
43            row.get::<_, Option<OperationKind>>(1)?,
44            row.get::<_, String>(2)?,
45        ))
46    })?;
47
48    rows.filter_map(|row| match row {
49        Ok((Some(log_id), operation_kind, diff_type)) if diff_type == "added" => Some(Ok((
50            log_id,
51            operation_kind.unwrap_or(OperationKind::HistoryCommit),
52        ))),
53        Ok(_) => None,
54        Err(error) => Some(Err(error)),
55    })
56    .collect()
57}
58
59pub fn operation_logs_at_ref(
60    conn: &GraphConnection,
61    history_ref: &str,
62) -> rusqlite::Result<Vec<(HashId, OperationKind)>> {
63    let operation_logs_table = OperationLog::table_name_with_history_ref(Some(history_ref));
64    let query =
65        format!("SELECT id, operation_kind FROM {operation_logs_table} ORDER BY created_on, id");
66    let mut statement = conn.prepare(&query)?;
67    let rows = statement.query_map(named_params! { ":history_ref": history_ref }, |row| {
68        Ok((row.get::<_, HashId>(0)?, row.get::<_, OperationKind>(1)?))
69    })?;
70    rows.collect::<Result<Vec<_>, _>>()
71}
72
73/// From the list of log ids (operation logs), return the operation files (such as fastas) associated with each one.
74pub fn operation_asset_files_for_logs(
75    conn: &GraphConnection,
76    log_ids: &[HashId],
77    history_ref: Option<&str>,
78) -> rusqlite::Result<Vec<OperationFileInfo>> {
79    if log_ids.is_empty() {
80        return Ok(Vec::new());
81    }
82
83    let operation_assets_table = OperationAsset::table_name_with_history_ref(history_ref);
84    let asset_refs_table = AssetRef::table_name_with_history_ref(history_ref);
85    let query = format!(
86        "SELECT asset_refs.id, asset_refs.uri, asset_refs.file_type, asset_refs.checksum, \
87         asset_refs.logical_path, asset_refs.name \
88         FROM {operation_assets_table} operation_assets \
89         JOIN {asset_refs_table} asset_refs ON asset_refs.id = operation_assets.asset_ref_id \
90         WHERE operation_assets.log_id IN rarray(:log_ids) \
91         ORDER BY asset_refs.created_on, asset_refs.name, operation_assets.role",
92    );
93    let mut statement = conn.prepare(&query)?;
94    let log_values = Rc::new(
95        log_ids
96            .iter()
97            .map(|log_id| Value::from(*log_id))
98            .collect::<Vec<_>>(),
99    );
100    let mut query_params: Vec<(&str, &dyn ToSql)> = vec![(":log_ids", &log_values)];
101    if let Some(history_ref) = history_ref.as_ref() {
102        query_params.push((":history_ref", history_ref));
103    }
104
105    statement
106        .query_map(&query_params[..], |row| {
107            let asset_uri = row.get::<_, String>(1)?;
108            let file_type = row.get::<_, String>(2)?;
109            let logical_path = row.get::<_, Option<String>>(4)?;
110            let name = row.get::<_, Option<String>>(5)?;
111            let file_type = FileTypes::from_storage_tag(&file_type);
112            let file_path = patch_file_path(&asset_uri, logical_path.as_deref());
113            let filename = patch_file_name(&asset_uri, logical_path.as_deref(), name.as_deref());
114            Ok(OperationFileInfo {
115                id: row.get(0)?,
116                filename,
117                file_path,
118                asset_uri,
119                file_type,
120                checksum: row.get(3)?,
121            })
122        })?
123        .collect::<Result<Vec<_>, _>>()
124}
125
126/// Loads DoltLite's ordered schema and data statements for a commit range.
127pub fn load_dolt_patch(
128    conn: &GraphConnection,
129    from_ref: &str,
130    to_ref: &str,
131) -> rusqlite::Result<Vec<DoltPatchStatement>> {
132    let mut query = conn.prepare(
133        "SELECT statement_order, from_commit_hash, to_commit_hash, table_name, diff_type, \
134         statement FROM dolt_patch(?1, ?2) ORDER BY statement_order",
135    )?;
136    let rows = query.query_map(params![from_ref, to_ref], |row| {
137        Ok(DoltPatchStatement {
138            statement_order: row.get("statement_order")?,
139            from_commit_hash: row.get("from_commit_hash")?,
140            to_commit_hash: row.get("to_commit_hash")?,
141            table_name: row.get("table_name")?,
142            diff_type: row.get("diff_type")?,
143            statement: row.get("statement")?,
144        })
145    })?;
146    rows.collect::<Result<Vec<_>, _>>()
147}
148
149/// Applies ordered statements produced by [`load_dolt_patch`] as one transaction.
150///
151/// Schema and data statements are applied together in their native `statement_order`. Foreign key
152/// enforcement remains enabled, but its checks are deferred until the transaction commits so
153/// related rows may be changed in either order without allowing an invalid final state.
154pub fn apply_dolt_patch(
155    conn: &GraphConnection,
156    patch: &[DoltPatchStatement],
157) -> rusqlite::Result<()> {
158    if patch.is_empty() {
159        return Ok(());
160    }
161
162    conn.execute_batch("PRAGMA foreign_keys = ON;")?;
163    conn.execute_batch("BEGIN IMMEDIATE;")?;
164    if let Err(error) = conn.execute_batch("PRAGMA defer_foreign_keys = ON;") {
165        let _ = conn.execute_batch("ROLLBACK;");
166        return Err(error);
167    }
168    for patch_statement in patch {
169        if let Err(error) = conn.execute_batch(&patch_statement.statement) {
170            let _ = conn.execute_batch("ROLLBACK;");
171            return Err(error);
172        }
173    }
174    if let Err(error) = conn.execute_batch("COMMIT;") {
175        let _ = conn.execute_batch("ROLLBACK;");
176        return Err(error);
177    }
178    Ok(())
179}
180
181fn patch_file_path(asset_uri: &str, logical_path: Option<&str>) -> String {
182    logical_path.unwrap_or(asset_uri).to_string()
183}
184
185fn patch_file_name(asset_uri: &str, logical_path: Option<&str>, name: Option<&str>) -> String {
186    if let Some(name) = name {
187        return name.to_string();
188    }
189
190    let path = logical_path.unwrap_or(asset_uri.strip_prefix("file://").unwrap_or(asset_uri));
191    std::path::Path::new(path)
192        .file_name()
193        .and_then(|value| value.to_str())
194        .unwrap_or(path)
195        .to_string()
196}
197
198#[cfg(test)]
199mod tests {
200    use gen_core::{DoltHashId, HashId};
201    use rusqlite::Connection;
202
203    use super::{
204        DoltPatchStatement, apply_dolt_patch, load_dolt_patch, operation_asset_files_for_logs,
205    };
206    use crate::{
207        assets::{AssetRef, AssetRole, OperationAsset, OperationKind, OperationLog},
208        db::GraphConnection,
209        file_types::FileTypes,
210        history::dolt::commit_all,
211        test_helpers::setup_gen,
212    };
213
214    fn create_base_connection() -> GraphConnection {
215        let conn = GraphConnection(Connection::open_in_memory().expect("should open database"));
216        conn.execute_batch(
217            "CREATE TABLE patch_items (
218                collection_name TEXT NOT NULL,
219                item_id INTEGER NOT NULL,
220                value TEXT NOT NULL,
221                PRIMARY KEY (collection_name, item_id)
222             );
223             INSERT INTO patch_items VALUES ('default', 1, 'before');",
224        )
225        .expect("should create base table");
226        commit_all(&conn, "base").expect("should commit base table");
227        conn
228    }
229
230    fn patch_statement(statement_order: i64, statement: &str) -> DoltPatchStatement {
231        DoltPatchStatement {
232            statement_order,
233            from_commit_hash: DoltHashId::default(),
234            to_commit_hash: DoltHashId::default(),
235            table_name: "patch_children".to_string(),
236            diff_type: "data".to_string(),
237            statement: statement.to_string(),
238        }
239    }
240
241    #[test]
242    fn test_operation_asset_files_for_logs_preserves_missing_checksum() {
243        let context = setup_gen();
244        let conn = context.graph().conn();
245        let log = OperationLog {
246            id: HashId::convert_str("checksumless-log"),
247            operation_kind: OperationKind::AddFile,
248            command: "add remote file".to_string(),
249            created_on: 1,
250        };
251        let asset = AssetRef {
252            id: HashId::convert_str("checksumless-asset"),
253            uri: "s3://private-bucket/reference.fa".to_string(),
254            file_type: FileTypes::Fasta.as_str().to_string(),
255            checksum: None,
256            size: None,
257            role: AssetRole::Input,
258            logical_path: Some("inputs/reference.fa".to_string()),
259            name: Some("reference.fa".to_string()),
260            created_on: 1,
261            upstream_asset_ref_id: None,
262        };
263        OperationLog::create(conn, &log).expect("should create operation log");
264        AssetRef::create(conn, &asset).expect("should create checksumless asset");
265        OperationAsset::create(
266            conn,
267            &OperationAsset {
268                log_id: log.id,
269                asset_ref_id: asset.id,
270                role: AssetRole::Input,
271            },
272        )
273        .expect("should link checksumless asset");
274
275        let files = operation_asset_files_for_logs(conn, &[log.id], None)
276            .expect("should load checksumless operation asset");
277
278        assert_eq!(files.len(), 1);
279        assert_eq!(files[0].asset_uri, asset.uri);
280        assert_eq!(files[0].file_path, "inputs/reference.fa");
281        assert_eq!(files[0].checksum, None);
282    }
283
284    #[test]
285    fn test_dolt_patch_applies_schema_and_data_statements() {
286        let source = create_base_connection();
287        source
288            .execute_batch(
289                "ALTER TABLE patch_items ADD COLUMN note TEXT NOT NULL DEFAULT 'base';
290                 CREATE INDEX patch_items_value_idx ON patch_items(value);
291                 UPDATE patch_items
292                 SET value = 'after', note = 'updated'
293                 WHERE collection_name = 'default' AND item_id = 1;
294                 INSERT INTO patch_items VALUES ('default', 2, 'added', 'new');",
295            )
296            .expect("should change source schema and data");
297        commit_all(&source, "target").expect("should commit target state");
298
299        let patch = load_dolt_patch(&source, "HEAD~1", "HEAD")
300            .expect("should load native Dolt patch statements");
301        assert!(
302            patch
303                .iter()
304                .any(|statement| statement.diff_type == "schema"),
305            "patch should contain schema statements"
306        );
307        assert!(
308            patch.iter().any(|statement| statement.diff_type == "data"),
309            "patch should contain data statements"
310        );
311        assert!(
312            patch
313                .windows(2)
314                .all(|statements| statements[0].statement_order < statements[1].statement_order),
315            "patch statements should preserve DoltLite ordering"
316        );
317
318        let target = create_base_connection();
319        apply_dolt_patch(&target, &patch).expect("should apply native Dolt patch");
320
321        let columns = target
322            .prepare("PRAGMA table_info(patch_items)")
323            .expect("should inspect target schema")
324            .query_map([], |row| row.get::<_, String>("name"))
325            .expect("should query target columns")
326            .collect::<Result<Vec<_>, _>>()
327            .expect("should decode target columns");
328        assert!(columns.iter().any(|column| column == "note"));
329        let index_exists = target
330            .query_row(
331                "SELECT EXISTS(
332                    SELECT 1 FROM sqlite_master
333                    WHERE type = 'index' AND name = 'patch_items_value_idx'
334                )",
335                [],
336                |row| row.get::<_, bool>(0),
337            )
338            .expect("should inspect target indexes");
339        assert!(index_exists, "patch should create the target index");
340        let rows = target
341            .prepare(
342                "SELECT collection_name, item_id, value, note
343                 FROM patch_items ORDER BY collection_name, item_id",
344            )
345            .expect("should query patched rows")
346            .query_map([], |row| {
347                Ok((
348                    row.get::<_, String>(0)?,
349                    row.get::<_, i64>(1)?,
350                    row.get::<_, String>(2)?,
351                    row.get::<_, String>(3)?,
352                ))
353            })
354            .expect("should read patched rows")
355            .collect::<Result<Vec<_>, _>>()
356            .expect("should decode patched rows");
357        assert_eq!(
358            rows,
359            vec![
360                (
361                    "default".to_string(),
362                    1,
363                    "after".to_string(),
364                    "updated".to_string()
365                ),
366                (
367                    "default".to_string(),
368                    2,
369                    "added".to_string(),
370                    "new".to_string()
371                ),
372            ]
373        );
374    }
375
376    #[test]
377    fn test_apply_dolt_patch_defers_and_validates_foreign_keys() {
378        let conn = GraphConnection(Connection::open_in_memory().expect("should open database"));
379        conn.execute_batch(
380            "PRAGMA foreign_keys = ON;
381             CREATE TABLE patch_parents (
382                 id INTEGER PRIMARY KEY
383             );
384             CREATE TABLE patch_children (
385                 id INTEGER PRIMARY KEY,
386                 parent_id INTEGER NOT NULL REFERENCES patch_parents(id)
387             );",
388        )
389        .expect("should create related patch tables");
390
391        let out_of_order_patch = vec![
392            patch_statement(
393                1,
394                "INSERT INTO patch_children (id, parent_id) VALUES (1, 1);",
395            ),
396            patch_statement(2, "INSERT INTO patch_parents (id) VALUES (1);"),
397        ];
398        apply_dolt_patch(&conn, &out_of_order_patch)
399            .expect("should defer foreign keys until the complete patch is applied");
400
401        let invalid_patch = vec![patch_statement(
402            1,
403            "INSERT INTO patch_children (id, parent_id) VALUES (2, 999);",
404        )];
405        apply_dolt_patch(&conn, &invalid_patch)
406            .expect_err("should reject a patch with a foreign key violation");
407
408        let children = conn
409            .query_row("SELECT COUNT(*) FROM patch_children", [], |row| {
410                row.get::<_, i64>(0)
411            })
412            .expect("should count child rows");
413        assert_eq!(
414            children, 1,
415            "the invalid patch should be rolled back completely"
416        );
417        let violations = conn
418            .query_row("SELECT COUNT(*) FROM pragma_foreign_key_check", [], |row| {
419                row.get::<_, i64>(0)
420            })
421            .expect("should check referential integrity");
422        assert_eq!(violations, 0, "the database should remain consistent");
423        let foreign_keys_enabled = conn
424            .query_row("PRAGMA foreign_keys", [], |row| row.get::<_, bool>(0))
425            .expect("should read foreign key enforcement state");
426        assert!(
427            foreign_keys_enabled,
428            "foreign key enforcement should remain enabled"
429        );
430    }
431}