Skip to main content

gen_models/
operations.rs

1use std::{
2    collections::HashMap,
3    convert::TryInto,
4    io::{self, BufReader},
5    path::{Path, PathBuf},
6    rc::Rc,
7    string::ToString,
8};
9
10use gen_core::{HashId, Workspace, calculate_hash, traits::Capnp};
11use gen_graph::{OperationGraph, all_simple_paths};
12use itertools::Itertools;
13use petgraph::{Direction, graphmap::UnGraphMap};
14use rusqlite::{Result as SQLResult, Row, params, types::Value};
15use serde::{Deserialize, Serialize};
16use sha2::{Digest, Sha256};
17use thiserror::Error;
18
19use crate::{
20    assets::{AssetUri, LocalAssetUri},
21    changesets::{
22        ChangesetModels, DatabaseChangeset, get_changeset_dependencies_from_path,
23        get_changeset_from_path, write_changeset,
24    },
25    db::{DbContext, OperationsConnection},
26    errors::{
27        AddFilesOperationError, FileAdditionError, FileStoreError, OperationError, RemoteError,
28    },
29    file_types::FileTypes,
30    files::GenDatabase,
31    gen_models_capnp::operation,
32    metadata,
33    session_operations::DependencyModels,
34    traits::*,
35};
36
37#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, Serialize, Deserialize)]
38pub struct Operation {
39    pub hash: HashId,
40    pub parent_hash: Option<HashId>,
41    pub change_type: String,
42    pub created_on: i64,
43}
44
45impl<'a> Capnp<'a> for Operation {
46    type Builder = operation::Builder<'a>;
47    type Reader = operation::Reader<'a>;
48
49    fn write_capnp(&self, builder: &mut Self::Builder) {
50        builder.set_hash(&self.hash.0).unwrap();
51        match &self.parent_hash {
52            None => {
53                builder.reborrow().get_parent_hash().set_none(());
54            }
55            Some(n) => {
56                builder.reborrow().get_parent_hash().set_some(&n.0).unwrap();
57            }
58        }
59        builder.set_change_type(&self.change_type);
60        builder.set_created_on(self.created_on);
61    }
62
63    fn read_capnp(reader: Self::Reader) -> Self {
64        let hash = reader
65            .get_hash()
66            .unwrap()
67            .as_slice()
68            .unwrap()
69            .try_into()
70            .unwrap();
71        let parent_hash = match reader.get_parent_hash().which().unwrap() {
72            operation::parent_hash::None(()) => None,
73            operation::parent_hash::Some(n) => {
74                Some(n.unwrap().as_slice().unwrap().try_into().unwrap())
75            }
76        };
77        let change_type = reader.get_change_type().unwrap().to_string().unwrap();
78        let created_on = reader.get_created_on();
79
80        Operation {
81            hash,
82            parent_hash,
83            change_type,
84            created_on,
85        }
86    }
87}
88
89#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
90pub struct HashRange {
91    pub from: Option<HashId>,
92    pub to: Option<HashId>,
93}
94
95#[derive(Debug, Error)]
96pub enum HashParseError {
97    #[error("No current branch is checked out.")]
98    NoCurrentBranch,
99    #[error("Branch '{0}' not found.")]
100    BranchNotFound(String),
101    #[error("Branch '{0}' has no operations.")]
102    EmptyBranch(String),
103    #[error("Reference '{0}' is not a valid HEAD shorthand.")]
104    InvalidHead(String),
105    #[error("HEAD offset {0} is out of range for the current branch.")]
106    HeadOffsetOutOfRange(usize),
107    #[error("Reference '{0}' did not match any operation.")]
108    OperationNotFound(String),
109    #[error("Reference '{0}' matches multiple operations.")]
110    OperationAmbiguous(String),
111}
112
113impl Operation {
114    #[cfg_attr(
115        all(debug_assertions, feature = "profiling"),
116        tracing::instrument(skip(conn, change_type, hash))
117    )]
118    pub fn create(
119        conn: &OperationsConnection,
120        change_type: &str,
121        hash: &HashId,
122    ) -> SQLResult<Operation> {
123        let current_op = OperationState::get_operation(conn);
124        let current_branch_id =
125            OperationState::get_current_branch(conn).expect("No branch is checked out.");
126
127        let timestamp = chrono::Utc::now().timestamp_nanos_opt().unwrap();
128        let query = "INSERT INTO operations (hash, change_type, parent_hash, created_on) VALUES (?1, ?2, ?3, ?4);";
129        let mut stmt = conn.prepare(query).unwrap();
130        stmt.execute(params![hash, change_type, current_op, timestamp])?;
131        let operation = Operation {
132            hash: *hash,
133            parent_hash: current_op,
134            change_type: change_type.to_string(),
135            created_on: timestamp,
136        };
137        // TODO: error condition here where we can write to disk but transaction fails
138        OperationState::set_operation(conn, &operation.hash);
139        Branch::set_current_operation(conn, current_branch_id, &operation.hash);
140        Ok(operation)
141    }
142
143    pub fn create_without_tracking(
144        conn: &OperationsConnection,
145        hash: &HashId,
146        change_type: &str,
147        parent_hash: Option<HashId>,
148        created_on: Option<i64>,
149    ) -> SQLResult<Operation> {
150        let timestamp = created_on.unwrap_or(chrono::Utc::now().timestamp_nanos_opt().unwrap());
151        let query = "INSERT INTO operations (hash, change_type, parent_hash, created_on) VALUES (?1, ?2, ?3, ?4);";
152        let mut stmt = conn.prepare(query).unwrap();
153        stmt.execute(params![hash, change_type, parent_hash, timestamp])?;
154        let operation = Operation {
155            hash: *hash,
156            parent_hash,
157            change_type: change_type.to_string(),
158            created_on: timestamp,
159        };
160        Ok(operation)
161    }
162
163    #[cfg_attr(
164        all(debug_assertions, feature = "profiling"),
165        tracing::instrument(skip(
166            workspace,
167            conn,
168            operation_hash,
169            file_addition,
170            filename,
171            file_path
172        ))
173    )]
174    pub fn add_file(
175        workspace: &Workspace,
176        conn: &OperationsConnection,
177        operation_hash: &HashId,
178        file_addition: &FileAddition,
179        filename: &str,
180        file_path: &str,
181    ) -> Result<(), FileAdditionError> {
182        let file_path =
183            OperationFile::storage_file_path(workspace, file_path, &file_addition.checksum)?;
184        let query = "INSERT INTO operation_files (operation_hash, file_addition_id, filename, file_path) VALUES (?1, ?2, ?3, ?4)";
185        let mut stmt = conn.prepare(query)?;
186        stmt.execute(params![
187            operation_hash,
188            file_addition.id,
189            filename,
190            file_path
191        ])?;
192        Ok(())
193    }
194
195    #[cfg_attr(
196        all(debug_assertions, feature = "profiling"),
197        tracing::instrument(skip(conn, operation_hash, db_uuid))
198    )]
199    pub fn add_database(
200        conn: &OperationsConnection,
201        operation_hash: &HashId,
202        db_uuid: &str,
203    ) -> SQLResult<()> {
204        let query =
205            "INSERT INTO operation_databases (operation_hash, database_uuid) VALUES (?1, ?2)";
206        let mut stmt = conn.prepare(query).unwrap();
207        stmt.execute(params![operation_hash, db_uuid])?;
208        Ok(())
209    }
210
211    pub fn get_upstream(conn: &OperationsConnection, operation_hash: &HashId) -> Vec<HashId> {
212        let query = "WITH RECURSIVE r_operations(operation_hash, depth) AS ( \
213        select ?1, 0 UNION \
214        select parent_hash, depth + 1 from r_operations join operations ON hash=operation_hash \
215        ) SELECT operation_hash, depth from r_operations where operation_hash is not null order by depth desc;";
216        let mut stmt = conn.prepare(query).unwrap();
217        stmt.query_map([operation_hash], |row| row.get(0))
218            .unwrap()
219            .map(|id| id.unwrap())
220            .collect::<Vec<HashId>>()
221    }
222
223    pub fn get_operation_graph(conn: &OperationsConnection) -> OperationGraph {
224        let mut graph = OperationGraph::new();
225        let operations = Operation::query(conn, "select * from operations;", rusqlite::params![]);
226        for op in operations.iter() {
227            graph.add_node(op.hash);
228            if let Some(v) = op.parent_hash {
229                graph.add_node(v);
230                graph.add_edge(v, op.hash, ());
231            }
232        }
233        graph
234    }
235
236    pub fn get_path_between(
237        conn: &OperationsConnection,
238        source_node: HashId,
239        target_node: HashId,
240    ) -> Vec<(HashId, Direction, HashId)> {
241        let directed_graph = Operation::get_operation_graph(conn);
242        let mut undirected_graph: UnGraphMap<HashId, ()> = Default::default();
243
244        for node in directed_graph.nodes() {
245            undirected_graph.add_node(node);
246        }
247        for (source, target, _weight) in directed_graph.all_edges() {
248            undirected_graph.add_edge(source, target, ());
249        }
250        let mut patch_path: Vec<(HashId, Direction, HashId)> = vec![];
251        for path in all_simple_paths(&undirected_graph, source_node, target_node) {
252            let mut last_node = source_node;
253            for node in &path[1..] {
254                if *node != source_node {
255                    for (_edge_src, edge_target, _edge_weight) in
256                        directed_graph.edges_directed(last_node, Direction::Outgoing)
257                    {
258                        if edge_target == *node {
259                            patch_path.push((last_node, Direction::Outgoing, *node));
260                            break;
261                        }
262                    }
263                    for (edge_src, _edge_target, _edge_weight) in
264                        directed_graph.edges_directed(last_node, Direction::Incoming)
265                    {
266                        if edge_src == *node {
267                            patch_path.push((last_node, Direction::Incoming, *node));
268                            break;
269                        }
270                    }
271                }
272                last_node = *node;
273            }
274        }
275        patch_path
276    }
277
278    pub fn search_hash(
279        conn: &OperationsConnection,
280        op_hash: &str,
281    ) -> Result<Operation, HashParseError> {
282        let matches = Operation::search_hashes(conn, op_hash);
283        match matches.len() {
284            0 => Err(HashParseError::OperationNotFound(op_hash.to_string())),
285            1 => Ok(matches[0].clone()),
286            _ => Err(HashParseError::OperationAmbiguous(op_hash.to_string())),
287        }
288    }
289
290    pub fn search_hashes(conn: &OperationsConnection, op_hash: &str) -> Vec<Operation> {
291        Operation::query(
292            conn,
293            "select * from operations where hex(hash) LIKE ?1",
294            params![format!("{op_hash}%")],
295        )
296    }
297
298    pub fn get_changeset_path(&self, workspace: &Workspace) -> PathBuf {
299        workspace.changeset_path(&self.hash).join("changeset")
300    }
301
302    pub fn get_changeset_dependencies_path(&self, workspace: &Workspace) -> PathBuf {
303        workspace.changeset_path(&self.hash).join("dependencies")
304    }
305
306    pub fn get_changeset(&self, workspace: &Workspace) -> DatabaseChangeset {
307        let path = self.get_changeset_path(workspace);
308        get_changeset_from_path(path)
309    }
310
311    pub fn get_changeset_dependencies(&self, workspace: &Workspace) -> DependencyModels {
312        let path = self.get_changeset_dependencies_path(workspace);
313        get_changeset_dependencies_from_path(path)
314    }
315}
316
317pub fn parse_hash(conn: &OperationsConnection, input: &str) -> Result<HashRange, HashParseError> {
318    if input.contains("..") {
319        let mut it = input.split("..");
320        let from_ref = it.next().unwrap_or_default();
321        let to_ref = it.next().unwrap_or_default();
322        return Ok(HashRange {
323            from: Some(resolve_reference(conn, from_ref)?),
324            to: Some(resolve_reference(conn, to_ref)?),
325        });
326    }
327
328    Ok(HashRange {
329        from: None,
330        to: Some(resolve_reference(conn, input)?),
331    })
332}
333
334fn resolve_reference(
335    conn: &OperationsConnection,
336    reference: &str,
337) -> Result<HashId, HashParseError> {
338    if reference.starts_with("HEAD") {
339        return resolve_head(conn, reference);
340    }
341
342    if let Some(branch) = Branch::get_by_name(conn, reference) {
343        if let Some(hash) = branch.current_operation_hash {
344            return Ok(hash);
345        }
346        return Err(HashParseError::EmptyBranch(branch.name));
347    }
348
349    let operation = Operation::search_hash(conn, reference)?;
350    Ok(operation.hash)
351}
352
353fn resolve_head(conn: &OperationsConnection, reference: &str) -> Result<HashId, HashParseError> {
354    let branch_id =
355        OperationState::get_current_branch(conn).ok_or(HashParseError::NoCurrentBranch)?;
356    let branch = Branch::get_by_id(conn, branch_id)
357        .ok_or_else(|| HashParseError::BranchNotFound(branch_id.to_string()))?;
358    let operations = Branch::get_operations(conn, branch.id);
359    if operations.is_empty() {
360        return Err(HashParseError::EmptyBranch(branch.name));
361    }
362    if reference == "HEAD" {
363        return Ok(operations.last().unwrap().hash);
364    }
365    if let Some(offset) = reference.strip_prefix("HEAD~") {
366        let offset: usize = offset
367            .parse()
368            .map_err(|_| HashParseError::InvalidHead(reference.to_string()))?;
369        let head_index = operations.len() - 1;
370        let target_index = head_index
371            .checked_sub(offset)
372            .ok_or(HashParseError::HeadOffsetOutOfRange(offset))?;
373        return Ok(operations[target_index].hash);
374    }
375
376    Err(HashParseError::InvalidHead(reference.to_string()))
377}
378
379impl Query for Operation {
380    type Model = Operation;
381
382    const PRIMARY_KEY: &'static str = "hash";
383    const TABLE_NAME: &'static str = "operations";
384
385    fn process_row(row: &Row) -> Self::Model {
386        Operation {
387            hash: row.get(0).unwrap(),
388            parent_hash: row.get(1).unwrap(),
389            change_type: row.get(2).unwrap(),
390            created_on: row.get(3).unwrap(),
391        }
392    }
393}
394
395pub struct OperationFile {
396    pub filename: String,
397    pub file_path: String,
398    pub file_type: FileTypes,
399    pub checksum_override: Option<HashId>,
400}
401
402#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
403pub struct OperationFileInfo {
404    pub id: HashId,
405    pub filename: String,
406    pub file_path: String,
407    pub asset_uri: String,
408    pub file_type: FileTypes,
409    pub checksum: HashId,
410}
411
412impl OperationFileInfo {
413    fn from_parts(file_addition: FileAddition, filename: String, file_path: String) -> Self {
414        Self {
415            id: file_addition.id,
416            file_path,
417            filename,
418            asset_uri: file_addition.asset_uri,
419            file_type: file_addition.file_type,
420            checksum: file_addition.checksum,
421        }
422    }
423
424    pub fn hashed_filename(&self) -> String {
425        <dyn AssetUri>::from_uri(&self.asset_uri).hashed_filename(&self.checksum)
426    }
427}
428
429impl OperationFile {
430    pub fn new(file_path: impl Into<String>) -> Self {
431        let file_path = file_path.into();
432        let file_type = FileTypes::infer_from_path(&file_path);
433        let filename = Path::new(&file_path)
434            .file_name()
435            .and_then(|name| name.to_str())
436            .unwrap_or(&file_path)
437            .to_string();
438        Self {
439            filename,
440            file_path,
441            file_type,
442            checksum_override: None,
443        }
444    }
445
446    pub fn set_file_type(mut self, file_type: FileTypes) -> Self {
447        self.file_type = file_type;
448        self
449    }
450
451    pub fn set_checksum_override(mut self, checksum: HashId) -> Self {
452        self.checksum_override = Some(checksum);
453        self
454    }
455
456    pub fn storage_file_path(
457        workspace: &Workspace,
458        path_or_uri: &str,
459        checksum: &HashId,
460    ) -> Result<String, FileAdditionError> {
461        if LocalAssetUri::is_local_path_or_file_uri(path_or_uri) {
462            LocalAssetUri::operation_file_path(workspace, path_or_uri, checksum)
463        } else {
464            Ok(path_or_uri.to_string())
465        }
466    }
467
468    pub fn get_files_for_operation(
469        conn: &OperationsConnection,
470        operation_hash: &HashId,
471    ) -> Result<Vec<OperationFileInfo>, FileAdditionError> {
472        let query = "select fa.*, of.filename, of.file_path from file_additions fa join operation_files of on (fa.id = of.file_addition_id) where of.operation_hash = ?1";
473        let mut stmt = conn.prepare(query)?;
474        stmt.query_map(params![operation_hash], |row| {
475            Ok(OperationFileInfo::from_parts(
476                FileAddition::process_row(row),
477                row.get(4)?,
478                row.get(5)?,
479            ))
480        })?
481        .collect::<Result<Vec<_>, _>>()
482        .map_err(FileAdditionError::DatabaseError)
483    }
484
485    pub fn query_by_operations(
486        conn: &OperationsConnection,
487        operations: &[HashId],
488    ) -> Result<HashMap<HashId, Vec<OperationFileInfo>>, FileAdditionError> {
489        let query = "select fa.*, of.filename, of.file_path, of.operation_hash from file_additions fa join operation_files of on (fa.id = of.file_addition_id) where of.operation_hash in rarray(?1)";
490        let mut stmt = conn.prepare(query)?;
491        let rows = stmt.query_map(
492            params![Rc::new(
493                operations
494                    .iter()
495                    .map(|h| Value::from(*h))
496                    .collect::<Vec<Value>>()
497            )],
498            |row| {
499                Ok((
500                    OperationFileInfo::from_parts(
501                        FileAddition::process_row(row),
502                        row.get(4)?,
503                        row.get(5)?,
504                    ),
505                    row.get::<_, HashId>(6)?,
506                ))
507            },
508        )?;
509        rows.into_iter()
510            .try_fold(HashMap::new(), |mut acc: HashMap<_, Vec<_>>, row| {
511                let (item, hash) = row?;
512                acc.entry(hash).or_default().push(item);
513                Ok(acc)
514            })
515            .map_err(FileAdditionError::DatabaseError)
516    }
517}
518
519pub struct OperationInfo {
520    pub files: Vec<OperationFile>,
521    pub description: String,
522}
523
524pub fn add_files_operation(
525    context: &DbContext,
526    files: &[String],
527    message: Option<&str>,
528) -> Result<Operation, AddFilesOperationError> {
529    let workspace = context.workspace();
530    let operation_conn = context.operations().conn();
531    let graph_conn = context.graph().conn();
532    let db_uuid = metadata::get_db_uuid(graph_conn);
533
534    let file_additions = files
535        .iter()
536        .map(|path| {
537            let file_type = FileTypes::infer_from_path(path);
538            let file_addition =
539                FileAddition::get_or_create(workspace, operation_conn, path, file_type, None)?;
540            let operation_file_path =
541                OperationFile::storage_file_path(workspace, path, &file_addition.checksum)?;
542            Ok::<(FileAddition, String, String), FileAdditionError>((
543                file_addition,
544                OperationFile::new(path.clone()).filename,
545                operation_file_path,
546            ))
547        })
548        .collect::<Result<Vec<_>, _>>()?;
549
550    let unique_file_additions = file_additions
551        .into_iter()
552        .unique_by(|(file_addition, filename, file_path)| {
553            (file_addition.id, filename.clone(), file_path.clone())
554        })
555        .collect::<Vec<_>>();
556
557    let operation_hash = HashId(calculate_hash(
558        &unique_file_additions
559            .iter()
560            .map(|(file_addition, filename, file_path)| {
561                format!("{}:{filename}:{file_path}", file_addition.id)
562            })
563            .sorted()
564            .join(":"),
565    ));
566
567    let operation = match Operation::create(operation_conn, "add-file", &operation_hash) {
568        Ok(operation) => operation,
569        Err(rusqlite::Error::SqliteFailure(err, _details))
570            if err.code == rusqlite::ErrorCode::ConstraintViolation =>
571        {
572            return Err(AddFilesOperationError::OperationError(
573                OperationError::NoChanges,
574            ));
575        }
576        Err(err) => return Err(err.into()),
577    };
578
579    for (file_addition, filename, file_path) in &unique_file_additions {
580        Operation::add_file(
581            workspace,
582            operation_conn,
583            &operation.hash,
584            file_addition,
585            filename,
586            file_path,
587        )?;
588    }
589
590    Operation::add_database(operation_conn, &operation.hash, &db_uuid)?;
591
592    let summary = message.map(str::to_string).unwrap_or_else(|| {
593        if files.len() == 1 {
594            format!("Add file {}", files[0])
595        } else {
596            format!("Add {} files", files.len())
597        }
598    });
599    OperationSummary::create(operation_conn, &operation.hash, &summary);
600
601    let gen_db = GenDatabase::get_by_uuid(operation_conn, &db_uuid)?;
602    write_changeset(
603        workspace,
604        &operation,
605        DatabaseChangeset {
606            db_path: gen_db.path,
607            changes: ChangesetModels::default(),
608        },
609        &DependencyModels::default(),
610    );
611
612    for file_addition in unique_file_additions
613        .into_iter()
614        .map(|(file_addition, _filename, _file_path)| file_addition)
615        .unique_by(|file_addition| file_addition.id)
616    {
617        file_addition.store_file(workspace)?;
618    }
619
620    Ok(operation)
621}
622
623pub fn calculate_file_checksum<P: AsRef<Path>>(file_path: P) -> Result<HashId, std::io::Error> {
624    let file = std::fs::File::open(file_path)?;
625    let reader = BufReader::new(file);
626    calculate_reader_checksum(reader)
627}
628
629pub fn calculate_reader_checksum<R: std::io::Read>(reader: R) -> Result<HashId, std::io::Error> {
630    let hash_bytes = calculate_stream_hash(reader)?;
631    Ok(HashId(hash_bytes))
632}
633
634fn calculate_stream_hash<R: std::io::Read>(mut reader: R) -> Result<[u8; 32], std::io::Error> {
635    let mut hasher = Sha256::new();
636    io::copy(&mut reader, &mut hasher)?;
637    let result = hasher.finalize();
638    let mut hash_array = [0u8; 32];
639    hash_array.copy_from_slice(&result);
640    Ok(hash_array)
641}
642
643#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
644pub struct FileAddition {
645    pub id: HashId,
646    pub asset_uri: String,
647    pub file_type: FileTypes,
648    pub checksum: HashId,
649}
650
651impl Query for FileAddition {
652    type Model = FileAddition;
653
654    const TABLE_NAME: &'static str = "file_additions";
655
656    fn process_row(row: &Row) -> Self::Model {
657        Self::Model {
658            id: row.get(0).unwrap(),
659            asset_uri: row.get(1).unwrap(),
660            file_type: row.get(2).unwrap(),
661            checksum: row.get(3).unwrap(),
662        }
663    }
664}
665
666impl FileAddition {
667    pub fn file_path(&self) -> &str {
668        self.asset_uri
669            .strip_prefix(LocalAssetUri::SCHEME)
670            .unwrap_or(&self.asset_uri)
671    }
672
673    #[cfg_attr(
674        all(debug_assertions, feature = "profiling"),
675        tracing::instrument(skip(workspace, conn, file_path, file_type, checksum_override))
676    )]
677    pub fn get_or_create(
678        workspace: &Workspace,
679        conn: &OperationsConnection,
680        file_path: &str,
681        file_type: FileTypes,
682        checksum_override: Option<HashId>,
683    ) -> Result<FileAddition, FileAdditionError> {
684        let asset_uri = <dyn AssetUri>::new(workspace, file_path);
685        let checksum = asset_uri.checksum(workspace, checksum_override)?;
686        let stored_asset_uri = asset_uri.stored_asset_uri(workspace, &checksum)?;
687        asset_uri.ensure_asset(workspace, &checksum)?;
688
689        let id = LocalAssetUri::generate_file_addition_id(&checksum, &stored_asset_uri);
690
691        let query = "INSERT INTO file_additions (id, asset_uri, file_type, checksum) VALUES (?1, ?2, ?3, ?4);";
692        let mut stmt = conn.prepare(query).unwrap();
693
694        let addition = FileAddition {
695            id,
696            asset_uri: stored_asset_uri.clone(),
697            file_type,
698            checksum,
699        };
700
701        match stmt.execute((&id, &stored_asset_uri, file_type, &checksum)) {
702            Ok(_) => Ok(addition),
703            Err(err) => match &err {
704                rusqlite::Error::SqliteFailure(suberr, _details) => {
705                    if suberr.code == rusqlite::ErrorCode::ConstraintViolation {
706                        Ok(addition)
707                    } else {
708                        Err(FileAdditionError::DatabaseError(err))
709                    }
710                }
711                _ => Err(FileAdditionError::DatabaseError(err)),
712            },
713        }
714    }
715
716    pub fn get_files_for_operation(
717        conn: &OperationsConnection,
718        operation_hash: &HashId,
719    ) -> Vec<FileAddition> {
720        let query = "select fa.* from file_additions fa left join operation_files of on (fa.id = of.file_addition_id) where of.operation_hash = ?1";
721        let mut stmt = conn.prepare(query).unwrap();
722        let rows = stmt
723            .query_map(params![operation_hash], |row| {
724                Ok(FileAddition::process_row(row))
725            })
726            .unwrap();
727        rows.map(|row| row.unwrap()).collect()
728    }
729
730    pub fn query_by_operations(
731        conn: &OperationsConnection,
732        operations: &[HashId],
733    ) -> Result<HashMap<HashId, Vec<FileAddition>>, FileAdditionError> {
734        let query = "select fa.*, of.operation_hash from file_additions fa left join operation_files of on (fa.id = of.file_addition_id) where of.operation_hash in rarray(?1)";
735        let mut stmt = conn.prepare(query).unwrap();
736        let rows = stmt
737            .query_map(
738                params![Rc::new(
739                    operations
740                        .iter()
741                        .map(|h| Value::from(*h))
742                        .collect::<Vec<Value>>()
743                )],
744                |row| Ok((FileAddition::process_row(row), row.get::<_, HashId>(4)?)),
745            )
746            .unwrap();
747        rows.into_iter()
748            .try_fold(HashMap::new(), |mut acc: HashMap<_, Vec<_>>, row| {
749                let (item, hash) = row?;
750                acc.entry(hash).or_default().push(item);
751                Ok(acc)
752            })
753    }
754
755    #[cfg_attr(
756        all(debug_assertions, feature = "profiling"),
757        tracing::instrument(skip(self, workspace))
758    )]
759    pub fn store_file(&self, workspace: &Workspace) -> Result<(), FileStoreError> {
760        let asset_uri = <dyn AssetUri>::new(workspace, &self.asset_uri);
761        asset_uri.store_file(self, workspace)
762    }
763
764    pub fn hashed_filename(self) -> String {
765        <dyn AssetUri>::from_uri(&self.asset_uri).hashed_filename(&self.checksum)
766    }
767}
768
769#[derive(Debug, Error)]
770pub enum OperationSummaryError {
771    #[error("Database error: {0}")]
772    DatabaseError(#[from] rusqlite::Error),
773}
774
775#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
776pub struct OperationSummary {
777    pub id: i64,
778    pub operation_hash: HashId,
779    pub summary: String,
780}
781
782impl Query for OperationSummary {
783    type Model = OperationSummary;
784
785    const TABLE_NAME: &'static str = "operation_summaries";
786
787    fn process_row(row: &Row) -> Self::Model {
788        Self::Model {
789            id: row.get(0).unwrap(),
790            operation_hash: row.get(1).unwrap(),
791            summary: row.get(2).unwrap(),
792        }
793    }
794}
795
796impl OperationSummary {
797    #[cfg_attr(
798        all(debug_assertions, feature = "profiling"),
799        tracing::instrument(skip(conn, operation_hash, summary))
800    )]
801    pub fn create(
802        conn: &OperationsConnection,
803        operation_hash: &HashId,
804        summary: &str,
805    ) -> OperationSummary {
806        let query = "INSERT INTO operation_summaries (operation_hash, summary) VALUES (?1, ?2) RETURNING (id)";
807        let mut stmt = conn.prepare(query).unwrap();
808        let mut rows = stmt
809            .query_map(params![operation_hash, summary], |row| {
810                Ok(OperationSummary {
811                    id: row.get(0)?,
812                    operation_hash: *operation_hash,
813                    summary: summary.to_string(),
814                })
815            })
816            .unwrap();
817        rows.next().unwrap().unwrap()
818    }
819
820    pub fn set_message(conn: &OperationsConnection, id: i64, message: &str) -> SQLResult<()> {
821        let query = "UPDATE operation_summaries SET summary = ?2 where id = ?1";
822        let mut stmt = conn.prepare(query).unwrap();
823        stmt.execute(params![id, message])?;
824        Ok(())
825    }
826
827    pub fn query_by_operations(
828        conn: &OperationsConnection,
829        operations: &[HashId],
830    ) -> Result<HashMap<HashId, Vec<Self>>, OperationSummaryError> {
831        let query = "select * from operation_summaries where operation_hash in rarray(?1)";
832        let mut stmt = conn.prepare(query).unwrap();
833        let rows = stmt
834            .query_map(
835                params![Rc::new(
836                    operations
837                        .iter()
838                        .map(|h| Value::from(*h))
839                        .collect::<Vec<Value>>()
840                )],
841                |row| Ok(Self::process_row(row)),
842            )
843            .unwrap();
844        rows.into_iter()
845            .try_fold(HashMap::new(), |mut acc: HashMap<_, Vec<_>>, row| {
846                let item = row?;
847                acc.entry(item.operation_hash).or_default().push(item);
848                Ok(acc)
849            })
850    }
851}
852
853impl<'a> Capnp<'a> for FileAddition {
854    type Builder = crate::gen_models_capnp::file_addition::Builder<'a>;
855    type Reader = crate::gen_models_capnp::file_addition::Reader<'a>;
856
857    fn write_capnp(&self, builder: &mut Self::Builder) {
858        builder.set_id(&self.id.0).unwrap();
859        builder.set_asset_uri(&self.asset_uri);
860        builder.set_file_type(self.file_type.into());
861        builder.set_checksum(&self.checksum.0).unwrap();
862    }
863
864    fn read_capnp(reader: Self::Reader) -> Self {
865        Self {
866            id: reader
867                .get_id()
868                .unwrap()
869                .as_slice()
870                .unwrap()
871                .try_into()
872                .unwrap(),
873            asset_uri: reader.get_asset_uri().unwrap().to_string().unwrap(),
874            file_type: reader.get_file_type().unwrap().into(),
875            checksum: reader
876                .get_checksum()
877                .unwrap()
878                .as_slice()
879                .unwrap()
880                .try_into()
881                .unwrap(),
882        }
883    }
884}
885
886impl<'a> Capnp<'a> for OperationSummary {
887    type Builder = crate::gen_models_capnp::operation_summary::Builder<'a>;
888    type Reader = crate::gen_models_capnp::operation_summary::Reader<'a>;
889
890    fn write_capnp(&self, builder: &mut Self::Builder) {
891        builder.set_id(self.id);
892        builder.set_operation_hash(&self.operation_hash.0).unwrap();
893        builder.set_summary(&self.summary);
894    }
895
896    fn read_capnp(reader: Self::Reader) -> Self {
897        Self {
898            id: reader.get_id(),
899            operation_hash: reader
900                .get_operation_hash()
901                .unwrap()
902                .as_slice()
903                .unwrap()
904                .try_into()
905                .unwrap(),
906            summary: reader.get_summary().unwrap().to_string().unwrap(),
907        }
908    }
909}
910
911#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
912pub struct Remote {
913    pub name: String,
914    pub url: String,
915}
916
917impl Query for Remote {
918    type Model = Remote;
919
920    const TABLE_NAME: &'static str = "remotes";
921
922    fn process_row(row: &Row) -> Self::Model {
923        Remote {
924            name: row.get(0).unwrap(),
925            url: row.get(1).unwrap(),
926        }
927    }
928}
929
930impl Remote {
931    /// Validate remote name - no spaces or special characters except hyphens and underscores
932    pub fn validate_name(name: &str) -> Result<(), RemoteError> {
933        if name.is_empty() {
934            return Err(RemoteError::EmptyName);
935        }
936
937        if name
938            .chars()
939            .any(|c| !c.is_alphanumeric() && c != '-' && c != '_')
940        {
941            return Err(RemoteError::InvalidNameCharacters);
942        }
943
944        Ok(())
945    }
946
947    /// Validate URL format
948    pub fn validate_url(url: &str) -> Result<(), RemoteError> {
949        if url.is_empty() {
950            return Err(RemoteError::EmptyUrl);
951        }
952
953        // Check if it looks like a URL with a scheme
954        if url.contains("://") {
955            match url::Url::parse(url) {
956                Ok(parsed_url) => {
957                    // Only allow http, https, and ssh schemes
958                    match parsed_url.scheme() {
959                        "http" | "https" | "ssh" | "file" => Ok(()),
960                        _ => Err(RemoteError::UnsupportedUrlScheme),
961                    }
962                }
963                Err(_) => Err(RemoteError::InvalidUrl("Invalid URL format".to_string())),
964            }
965        } else if url.starts_with('/') || url.contains(':') {
966            // Assume it's a file path or SSH-style path (like user@host:path)
967            Ok(())
968        } else {
969            Err(RemoteError::UnsupportedUrlScheme)
970        }
971    }
972
973    /// Create a new remote with the given name and URL
974    /// Validates input and handles constraint violations gracefully
975    pub fn create(
976        conn: &OperationsConnection,
977        name: &str,
978        url: &str,
979    ) -> Result<Remote, RemoteError> {
980        // Validate input
981        Self::validate_name(name)?;
982        Self::validate_url(url)?;
983
984        let query = "INSERT INTO remotes (name, url) VALUES (?1, ?2)";
985        let mut stmt = conn.prepare(query)?;
986
987        match stmt.execute(params![name, url]) {
988            Ok(_) => Ok(Remote {
989                name: name.to_string(),
990                url: url.to_string(),
991            }),
992            Err(rusqlite::Error::SqliteFailure(err, _))
993                if err.code == rusqlite::ErrorCode::ConstraintViolation =>
994            {
995                Err(RemoteError::RemoteAlreadyExists(name.to_string()))
996            }
997            Err(e) => Err(RemoteError::DatabaseError(e)),
998        }
999    }
1000
1001    /// Get a remote by name
1002    pub fn get_by_name(conn: &OperationsConnection, name: &str) -> Result<Remote, RemoteError> {
1003        let query = "SELECT name, url FROM remotes WHERE name = ?1";
1004        match Remote::get(conn, query, params![name]) {
1005            Ok(remote) => Ok(remote),
1006            Err(rusqlite::Error::QueryReturnedNoRows) => {
1007                Err(RemoteError::RemoteNotFound(name.to_string()))
1008            }
1009            Err(e) => Err(RemoteError::DatabaseError(e)),
1010        }
1011    }
1012
1013    /// Get a remote by name, returning None if not found (for backward compatibility)
1014    pub fn get_by_name_optional(conn: &OperationsConnection, name: &str) -> Option<Remote> {
1015        Self::get_by_name(conn, name).ok()
1016    }
1017
1018    /// List all remotes
1019    pub fn list_all(conn: &OperationsConnection) -> Vec<Remote> {
1020        Remote::query(
1021            conn,
1022            "SELECT name, url FROM remotes ORDER BY name",
1023            params![],
1024        )
1025    }
1026
1027    /// Delete a remote by name
1028    pub fn delete(conn: &OperationsConnection, name: &str) -> Result<(), RemoteError> {
1029        // Check if remote exists first
1030        Self::get_by_name(conn, name)?;
1031
1032        let query = "DELETE FROM remotes WHERE name = ?1";
1033        let mut stmt = conn.prepare(query)?;
1034        stmt.execute(params![name])?;
1035        Ok(())
1036    }
1037
1038    /// Check if a remote exists
1039    pub fn exists(conn: &OperationsConnection, name: &str) -> bool {
1040        Self::get_by_name_optional(conn, name).is_some()
1041    }
1042}
1043
1044#[derive(Clone, Debug)]
1045pub struct Branch {
1046    pub id: i64,
1047    pub name: String,
1048    pub current_operation_hash: Option<HashId>,
1049    pub remote_name: Option<String>,
1050}
1051
1052#[derive(Debug, PartialEq, Error)]
1053pub enum BranchError {
1054    #[error("Cannot delete branch: {0}")]
1055    CannotDelete(String),
1056    #[error("SQL Error: {0}")]
1057    SQLError(String),
1058    #[error("SQLite Error: {0}")]
1059    SqliteError(#[from] rusqlite::Error),
1060    #[error("Duplicate entry: {0}")]
1061    Duplicate(String),
1062    #[error("Couldn't create branch: {0}")]
1063    CannotCreate(String),
1064}
1065
1066impl Query for Branch {
1067    type Model = Branch;
1068
1069    const TABLE_NAME: &'static str = "branches";
1070
1071    fn process_row(row: &Row) -> Self::Model {
1072        Branch {
1073            id: row.get(0).unwrap(),
1074            name: row.get(1).unwrap(),
1075            current_operation_hash: row.get(2).unwrap(),
1076            remote_name: row.get(3).unwrap(),
1077        }
1078    }
1079}
1080
1081impl Branch {
1082    pub fn get_or_create(
1083        conn: &OperationsConnection,
1084        branch_name: &str,
1085    ) -> Result<Branch, BranchError> {
1086        match Branch::create_with_remote(conn, branch_name, None) {
1087            Ok(res) => Ok(res),
1088            Err(BranchError::Duplicate(_)) => match Branch::get_by_name(conn, branch_name) {
1089                Some(branch) => Ok(branch),
1090                None => Err(BranchError::CannotCreate(
1091                    "Failed to create branch".to_string(),
1092                )),
1093            },
1094            Err(e) => Err(e),
1095        }
1096    }
1097
1098    pub fn create_with_remote(
1099        conn: &OperationsConnection,
1100        branch_name: &str,
1101        remote_name: Option<&str>,
1102    ) -> Result<Branch, BranchError> {
1103        let current_operation_hash = OperationState::get_operation(conn);
1104        let mut stmt = match conn.prepare_cached("insert into branch (name, current_operation_hash, remote_name) values (?1, ?2, ?3) returning (id);") {
1105	    Ok(stmt) => stmt,
1106	    Err(e) => return Err(BranchError::SqliteError(e)),
1107	};
1108
1109        let results: Result<_, _> =
1110            stmt.query_map((branch_name, current_operation_hash, remote_name), |row| {
1111                Ok(Branch {
1112                    id: row.get(0)?,
1113                    name: branch_name.to_string(),
1114                    current_operation_hash,
1115                    remote_name: remote_name.map(|s| s.to_string()),
1116                })
1117            });
1118        match results {
1119            Ok(mut results) => match results.next() {
1120                Some(Ok(branch)) => Ok(branch),
1121                Some(Err(rusqlite::Error::SqliteFailure(err, _)))
1122                    if err.code == rusqlite::ErrorCode::ConstraintViolation =>
1123                {
1124                    Err(BranchError::Duplicate(branch_name.to_string()))
1125                }
1126                Some(Err(e)) => Err(BranchError::SqliteError(e)),
1127                None => Err(BranchError::CannotCreate(
1128                    "Failed to create branch".to_string(),
1129                )),
1130            },
1131            Err(e) => Err(BranchError::SqliteError(e)),
1132        }
1133    }
1134
1135    pub fn delete(conn: &OperationsConnection, branch_id: i64) -> Result<(), BranchError> {
1136        if let Some(current_branch) = OperationState::get_current_branch(conn)
1137            && current_branch == branch_id
1138        {
1139            return Err(BranchError::CannotDelete(
1140                "Unable to delete the branch that is currently active.".to_string(),
1141            ));
1142        }
1143        conn.execute("delete from branch where id = ?1", (branch_id,))?;
1144        Ok(())
1145    }
1146
1147    pub fn all(conn: &OperationsConnection) -> Vec<Branch> {
1148        Branch::query(conn, "select * from branch;", params![])
1149    }
1150
1151    pub fn get_by_name(conn: &OperationsConnection, branch_name: &str) -> Option<Branch> {
1152        let mut branch: Option<Branch> = None;
1153        let results = Branch::query(
1154            conn,
1155            "select * from branch where name = ?1",
1156            params![branch_name],
1157        );
1158        for result in results.iter() {
1159            branch = Some(result.clone());
1160        }
1161        branch
1162    }
1163
1164    pub fn get_by_id(conn: &OperationsConnection, branch_id: i64) -> Option<Branch> {
1165        let mut branch: Option<Branch> = None;
1166        for result in Branch::query(
1167            conn,
1168            "select * from branch where id = ?1",
1169            params![Value::from(branch_id)],
1170        )
1171        .iter()
1172        {
1173            branch = Some(result.clone());
1174        }
1175        branch
1176    }
1177
1178    pub fn set_current_operation(
1179        conn: &OperationsConnection,
1180        branch_id: i64,
1181        operation_hash: &HashId,
1182    ) {
1183        conn.execute(
1184            "UPDATE branch set current_operation_hash = ?2 where id = ?1",
1185            params![branch_id, operation_hash],
1186        )
1187        .unwrap();
1188    }
1189
1190    pub fn get_operations(conn: &OperationsConnection, branch_id: i64) -> Vec<Operation> {
1191        let branch = Branch::get_by_id(conn, branch_id)
1192            .unwrap_or_else(|| panic!("No branch with id {branch_id}."));
1193        if let Some(hash) = branch.current_operation_hash {
1194            let hashes = Operation::get_upstream(conn, &hash);
1195            hashes
1196                .iter()
1197                .map(|hash| Operation::get_by_id(conn, hash).unwrap())
1198                .collect::<Vec<Operation>>()
1199        } else {
1200            vec![]
1201        }
1202    }
1203
1204    /// Associate a branch with a remote
1205    pub fn set_remote(
1206        conn: &OperationsConnection,
1207        branch_id: i64,
1208        remote_name: Option<&str>,
1209    ) -> SQLResult<()> {
1210        let query = "UPDATE branch SET remote_name = ?1 WHERE id = ?2";
1211        let mut stmt = conn.prepare(query)?;
1212        stmt.execute(params![remote_name, branch_id])?;
1213        Ok(())
1214    }
1215
1216    /// Associate a branch with a remote with validation
1217    pub fn set_remote_validated(
1218        conn: &OperationsConnection,
1219        branch_id: i64,
1220        remote_name: Option<&str>,
1221    ) -> Result<(), RemoteError> {
1222        // If setting a remote name, validate that it exists
1223        if let Some(name) = remote_name {
1224            Remote::get_by_name(conn, name)?;
1225        }
1226
1227        let query = "UPDATE branch SET remote_name = ?1 WHERE id = ?2";
1228        let mut stmt = conn.prepare(query)?;
1229        stmt.execute(params![remote_name, branch_id])?;
1230        Ok(())
1231    }
1232
1233    /// Get the remote associated with a branch
1234    pub fn get_remote(conn: &OperationsConnection, branch_id: i64) -> Option<String> {
1235        let query = "SELECT remote_name FROM branch WHERE id = ?1";
1236        let mut stmt = conn.prepare(query).ok()?;
1237        let mut rows = stmt
1238            .query_map(params![branch_id], |row| row.get::<_, Option<String>>(0))
1239            .ok()?;
1240
1241        if let Some(Ok(remote_name)) = rows.next() {
1242            remote_name
1243        } else {
1244            None
1245        }
1246    }
1247}
1248
1249#[derive(Clone, Debug, Serialize, Deserialize)]
1250pub struct Defaults {
1251    pub id: i64,
1252    pub db_name: Option<String>,
1253    pub collection_name: Option<String>,
1254    pub remote_name: Option<String>,
1255}
1256
1257impl Query for Defaults {
1258    type Model = Defaults;
1259
1260    const TABLE_NAME: &'static str = "defaults";
1261
1262    fn process_row(row: &Row) -> Self::Model {
1263        Defaults {
1264            id: row.get(0).unwrap(),
1265            db_name: row.get(1).unwrap(),
1266            collection_name: row.get(2).unwrap(),
1267            remote_name: row.get(3).unwrap(),
1268        }
1269    }
1270}
1271
1272impl Defaults {
1273    /// Set the default remote by name
1274    pub fn set_default_remote(
1275        conn: &OperationsConnection,
1276        remote_name: Option<&str>,
1277    ) -> Result<(), RemoteError> {
1278        // If setting a remote name, validate that it exists
1279        if let Some(name) = remote_name {
1280            Remote::get_by_name(conn, name)?;
1281        }
1282
1283        let query = "UPDATE defaults SET remote_name = ?1 WHERE id = 1";
1284        let mut stmt = conn.prepare(query)?;
1285        stmt.execute(params![remote_name])?;
1286        Ok(())
1287    }
1288
1289    pub fn set_default_remote_compat(
1290        conn: &OperationsConnection,
1291        remote_name: Option<&str>,
1292    ) -> SQLResult<()> {
1293        let query = "UPDATE defaults SET remote_name = ?1 WHERE id = 1";
1294        let mut stmt = conn.prepare(query)?;
1295        stmt.execute(params![remote_name])?;
1296        Ok(())
1297    }
1298
1299    /// Get the default remote name
1300    pub fn get_default_remote(conn: &OperationsConnection) -> Option<String> {
1301        let query = "SELECT remote_name FROM defaults WHERE id = 1";
1302        let mut stmt = conn.prepare(query).ok()?;
1303        let mut rows = stmt
1304            .query_map(params![], |row| row.get::<_, Option<String>>(0))
1305            .ok()?;
1306
1307        if let Some(Ok(remote_name)) = rows.next() {
1308            remote_name
1309        } else {
1310            None
1311        }
1312    }
1313
1314    /// Helper method to get the default remote URL by resolving the remote name
1315    pub fn get_default_remote_url(conn: &OperationsConnection) -> Option<String> {
1316        if let Some(remote_name) = Self::get_default_remote(conn) {
1317            if let Some(remote) = Remote::get_by_name_optional(conn, &remote_name) {
1318                Some(remote.url)
1319            } else {
1320                None
1321            }
1322        } else {
1323            None
1324        }
1325    }
1326
1327    /// Get the defaults record
1328    pub fn get(conn: &OperationsConnection) -> Option<Defaults> {
1329        let query = "SELECT id, db_name, collection_name, remote_name FROM defaults WHERE id = 1";
1330        Self::get_single(conn, query, params![]).ok()
1331    }
1332
1333    /// Helper method to get a single defaults record using the Query trait
1334    fn get_single(
1335        conn: &OperationsConnection,
1336        query: &str,
1337        params: &[&dyn rusqlite::ToSql],
1338    ) -> SQLResult<Defaults> {
1339        let mut stmt = conn.prepare(query)?;
1340        let mut rows = stmt.query_map(params, |row| Ok(Self::process_row(row)))?;
1341
1342        if let Some(row) = rows.next() {
1343            row
1344        } else {
1345            Err(rusqlite::Error::QueryReturnedNoRows)
1346        }
1347    }
1348}
1349
1350pub struct OperationState {}
1351
1352impl OperationState {
1353    #[cfg_attr(
1354        all(debug_assertions, feature = "profiling"),
1355        tracing::instrument(skip(conn, op_hash))
1356    )]
1357    pub fn set_operation(conn: &OperationsConnection, op_hash: &HashId) {
1358        let mut stmt = conn
1359            .prepare(
1360                "INSERT INTO operation_state (id, operation_hash)
1361          VALUES (1, ?1)
1362          ON CONFLICT (id) DO
1363          UPDATE SET operation_hash=excluded.operation_hash;",
1364            )
1365            .unwrap();
1366        stmt.execute([op_hash]).unwrap();
1367        let branch_id = OperationState::get_current_branch(conn).expect("No current branch set.");
1368        Branch::set_current_operation(conn, branch_id, op_hash);
1369    }
1370
1371    pub fn get_operation(conn: &OperationsConnection) -> Option<HashId> {
1372        let mut hash: Option<HashId> = None;
1373        let mut stmt = conn
1374            .prepare("SELECT operation_hash from operation_state where id = 1;")
1375            .unwrap();
1376        let rows = stmt.query_map((), |row| row.get(0)).unwrap();
1377        for row in rows {
1378            hash = row.unwrap();
1379        }
1380        hash
1381    }
1382
1383    pub fn set_branch(conn: &OperationsConnection, branch_name: &str) {
1384        let branch = Branch::get_by_name(conn, branch_name)
1385            .unwrap_or_else(|| panic!("No branch named {branch_name}."));
1386        let mut stmt = conn
1387            .prepare(
1388                "INSERT INTO operation_state (id, branch_id)
1389          VALUES (1, ?1)
1390          ON CONFLICT (id) DO
1391          UPDATE SET branch_id=excluded.branch_id;",
1392            )
1393            .unwrap();
1394        stmt.execute(params![branch.id]).unwrap();
1395        if let Some(current_branch_id) = OperationState::get_current_branch(conn) {
1396            if current_branch_id != branch.id {
1397                panic!("Failed to set branch to {branch_name}");
1398            }
1399        } else {
1400            panic!("Failed to set branch.");
1401        }
1402    }
1403
1404    pub fn get_current_branch(conn: &OperationsConnection) -> Option<i64> {
1405        let mut id: Option<i64> = None;
1406        let mut stmt = conn
1407            .prepare("SELECT branch_id from operation_state where id = 1;")
1408            .unwrap();
1409        let rows = stmt.query_map((), |row| row.get(0)).unwrap();
1410        for row in rows {
1411            id = row.unwrap();
1412        }
1413        id
1414    }
1415}
1416
1417#[cfg(test)]
1418mod tests {
1419    use std::{
1420        collections::HashSet,
1421        fs,
1422        io::{Cursor, Write},
1423    };
1424
1425    use tempfile::NamedTempFile;
1426
1427    use super::*;
1428    use crate::{
1429        files::GenDatabase,
1430        test_helpers::{create_operation, setup_gen},
1431    };
1432
1433    #[cfg(test)]
1434    mod defaults {
1435        use super::*;
1436
1437        #[test]
1438        fn test_writes_operation_hash() {
1439            let context = setup_gen();
1440            let op_conn = context.operations().conn();
1441
1442            let operation =
1443                Operation::create(op_conn, "test", &HashId::convert_str("some-hash")).unwrap();
1444            OperationState::set_operation(op_conn, &operation.hash);
1445            assert_eq!(
1446                OperationState::get_operation(op_conn).unwrap(),
1447                operation.hash
1448            );
1449        }
1450
1451        #[test]
1452        fn test_default_remote_functionality() {
1453            let context = setup_gen();
1454            let op_conn = context.operations().conn();
1455
1456            // Create test remotes
1457            Remote::create(op_conn, "origin", "https://example.com/repo.gen").unwrap();
1458            Remote::create(op_conn, "upstream", "https://upstream.com/repo.gen").unwrap();
1459
1460            // Test getting default remote when none is set
1461            assert_eq!(Defaults::get_default_remote(op_conn), None);
1462            assert_eq!(Defaults::get_default_remote_url(op_conn), None);
1463
1464            // Test setting default remote
1465            Defaults::set_default_remote(op_conn, Some("origin")).unwrap();
1466            assert_eq!(
1467                Defaults::get_default_remote(op_conn),
1468                Some("origin".to_string())
1469            );
1470            assert_eq!(
1471                Defaults::get_default_remote_url(op_conn),
1472                Some("https://example.com/repo.gen".to_string())
1473            );
1474
1475            // Test changing default remote
1476            Defaults::set_default_remote(op_conn, Some("upstream")).unwrap();
1477            assert_eq!(
1478                Defaults::get_default_remote(op_conn),
1479                Some("upstream".to_string())
1480            );
1481            assert_eq!(
1482                Defaults::get_default_remote_url(op_conn),
1483                Some("https://upstream.com/repo.gen".to_string())
1484            );
1485
1486            // Test clearing default remote
1487            Defaults::set_default_remote(op_conn, None).unwrap();
1488            assert_eq!(Defaults::get_default_remote(op_conn), None);
1489            assert_eq!(Defaults::get_default_remote_url(op_conn), None);
1490
1491            // Test getting URL for non-existent remote (using the compat method to bypass validation)
1492            Defaults::set_default_remote_compat(op_conn, Some("nonexistent")).unwrap();
1493            assert_eq!(
1494                Defaults::get_default_remote(op_conn),
1495                Some("nonexistent".to_string())
1496            );
1497            assert_eq!(Defaults::get_default_remote_url(op_conn), None);
1498        }
1499
1500        #[test]
1501        fn test_defaults_get() {
1502            let context = setup_gen();
1503            let op_conn = context.operations().conn();
1504
1505            // Test getting defaults record
1506            let defaults = Defaults::get(op_conn).unwrap();
1507            assert_eq!(defaults.id, 1);
1508            assert_eq!(defaults.db_name, None);
1509            assert_eq!(defaults.collection_name, None);
1510            assert_eq!(defaults.remote_name, None);
1511
1512            // Set a default remote and test again (using compat method to bypass validation)
1513            Defaults::set_default_remote_compat(op_conn, Some("test-remote")).unwrap();
1514            let defaults = Defaults::get(op_conn).unwrap();
1515            assert_eq!(defaults.remote_name, Some("test-remote".to_string()));
1516        }
1517    }
1518
1519    #[cfg(test)]
1520    mod remote {
1521        use super::*;
1522
1523        #[test]
1524        fn test_validate_remote_name() {
1525            // Valid names
1526            assert!(Remote::validate_name("origin").is_ok());
1527            assert!(Remote::validate_name("my-remote").is_ok());
1528            assert!(Remote::validate_name("remote_1").is_ok());
1529            assert!(Remote::validate_name("test123").is_ok());
1530
1531            // Invalid names
1532            assert!(Remote::validate_name("").is_err());
1533            assert!(Remote::validate_name("remote with spaces").is_err());
1534            assert!(Remote::validate_name("remote@special").is_err());
1535            assert!(Remote::validate_name("remote.dot").is_err());
1536        }
1537
1538        #[test]
1539        fn test_validate_url() {
1540            // Valid URLs
1541            assert!(Remote::validate_url("https://genhub.bio/user/repo.gen").is_ok());
1542            assert!(Remote::validate_url("http://example.com/repo").is_ok());
1543            assert!(Remote::validate_url("ssh://git@genhub.bio/user/repo.gen").is_ok());
1544            assert!(Remote::validate_url("/path/to/local/repo").is_ok());
1545            assert!(Remote::validate_url("user@host:path/to/repo").is_ok());
1546
1547            // Invalid URLs
1548            assert!(Remote::validate_url("").is_err());
1549            assert!(Remote::validate_url("not-a-url").is_err());
1550
1551            assert!(Remote::validate_url("ftp://invalid-protocol.com").is_err());
1552        }
1553    }
1554
1555    mod branch {
1556        use super::*;
1557
1558        #[test]
1559        fn test_branch_set_remote_valid() {
1560            let context = setup_gen();
1561            let op_conn = context.operations().conn();
1562
1563            // Get database UUID and setup database
1564
1565            // Create test remotes
1566            Remote::create(op_conn, "origin", "https://genhub.bio/user/repo.gen").unwrap();
1567
1568            // Create test branch
1569            let branch = Branch::get_or_create(op_conn, "test_branch").unwrap();
1570
1571            // Initially, branch should have no remote
1572            assert_eq!(Branch::get_remote(op_conn, branch.id), None);
1573
1574            // Set remote
1575            let result = Branch::set_remote(op_conn, branch.id, Some("origin"));
1576            assert!(result.is_ok());
1577
1578            // Verify remote was set
1579            assert_eq!(
1580                Branch::get_remote(op_conn, branch.id),
1581                Some("origin".to_string())
1582            );
1583        }
1584
1585        #[test]
1586        fn test_branch_set_remote_nonexistent() {
1587            let context = setup_gen();
1588            let op_conn = context.operations().conn();
1589
1590            // Get database UUID and setup database
1591
1592            // Create test branch
1593            let branch = Branch::get_or_create(op_conn, "test_branch").unwrap();
1594
1595            // Try to set a remote that doesn't exist - should fail due to foreign key constraint
1596            let result = Branch::set_remote(op_conn, branch.id, Some("nonexistent"));
1597            assert!(result.is_err());
1598
1599            // Verify branch still has no remote
1600            assert_eq!(Branch::get_remote(op_conn, branch.id), None);
1601        }
1602
1603        #[test]
1604        fn test_branch_clear_remote() {
1605            let context = setup_gen();
1606            let op_conn = context.operations().conn();
1607
1608            // Get database UUID and setup database
1609
1610            // Create test remotes
1611            Remote::create(op_conn, "origin", "https://genhub.bio/user/repo.gen").unwrap();
1612
1613            // Create test branch
1614            let branch = Branch::get_or_create(op_conn, "test_branch").unwrap();
1615
1616            // Set a remote first
1617            Branch::set_remote(op_conn, branch.id, Some("origin")).unwrap();
1618            assert_eq!(
1619                Branch::get_remote(op_conn, branch.id),
1620                Some("origin".to_string())
1621            );
1622
1623            // Clear the remote
1624            Branch::set_remote(op_conn, branch.id, None).unwrap();
1625            assert_eq!(Branch::get_remote(op_conn, branch.id), None);
1626        }
1627
1628        #[test]
1629        fn test_branch_remote_cascade_on_remote_delete() {
1630            let context = setup_gen();
1631            let op_conn = context.operations().conn();
1632
1633            // Get database UUID and setup database
1634
1635            // Create test remotes
1636            Remote::create(op_conn, "origin", "https://genhub.bio/user/repo.gen").unwrap();
1637
1638            // Create a branch and associate it with a remote
1639            let branch = Branch::get_or_create(op_conn, "test_branch_cascade").unwrap();
1640            Branch::set_remote(op_conn, branch.id, Some("origin")).unwrap();
1641
1642            // Verify the association
1643            assert_eq!(
1644                Branch::get_remote(op_conn, branch.id),
1645                Some("origin".to_string())
1646            );
1647
1648            // Delete the remote
1649            Remote::delete(op_conn, "origin").unwrap();
1650
1651            // Verify the branch remote association was set to null
1652            assert_eq!(Branch::get_remote(op_conn, branch.id), None);
1653
1654            // Verify the branch still exists
1655            let branch_from_db = Branch::get_by_id(op_conn, branch.id);
1656            assert!(branch_from_db.is_some());
1657            assert_eq!(branch_from_db.unwrap().remote_name, None);
1658        }
1659    }
1660
1661    mod parse_hash {
1662        use super::*;
1663
1664        #[test]
1665        fn test_parse_hash_head_and_range() {
1666            let context = setup_gen();
1667            let op_conn = context.operations().conn();
1668
1669            let branch = Branch::get_or_create(op_conn, "main").unwrap();
1670            OperationState::set_branch(op_conn, &branch.name);
1671
1672            let op_1 =
1673                Operation::create(op_conn, "add", &HashId::convert_str("op-1-abc-123")).unwrap();
1674            let op_2 =
1675                Operation::create(op_conn, "add", &HashId::convert_str("op-2-abc-123")).unwrap();
1676
1677            let head = parse_hash(op_conn, "HEAD").unwrap();
1678            assert_eq!(
1679                head,
1680                HashRange {
1681                    from: None,
1682                    to: Some(op_2.hash),
1683                }
1684            );
1685
1686            let range = parse_hash(op_conn, "HEAD~1..HEAD").unwrap();
1687            assert_eq!(
1688                range,
1689                HashRange {
1690                    from: Some(op_1.hash),
1691                    to: Some(op_2.hash),
1692                }
1693            );
1694        }
1695
1696        #[test]
1697        fn test_parse_hash_branch_and_partial() {
1698            let context = setup_gen();
1699            let op_conn = context.operations().conn();
1700
1701            let branch = Branch::get_or_create(op_conn, "main").unwrap();
1702            OperationState::set_branch(op_conn, &branch.name);
1703
1704            let op_1 =
1705                Operation::create(op_conn, "add", &HashId::convert_str("op-1-xyz-123")).unwrap();
1706            let op_2 =
1707                Operation::create(op_conn, "add", &HashId::convert_str("op-2-xyz-123")).unwrap();
1708
1709            let branch_ref = parse_hash(op_conn, "main").unwrap();
1710            assert_eq!(
1711                branch_ref,
1712                HashRange {
1713                    from: None,
1714                    to: Some(op_2.hash),
1715                }
1716            );
1717
1718            let partial = format!("{}", op_1.hash);
1719            let prefix = &partial[..6];
1720            let resolved = parse_hash(op_conn, prefix).unwrap();
1721            assert_eq!(
1722                resolved,
1723                HashRange {
1724                    from: None,
1725                    to: Some(op_1.hash),
1726                }
1727            );
1728        }
1729
1730        #[test]
1731        fn test_parse_hash_head_offset_out_of_range() {
1732            let context = setup_gen();
1733            let op_conn = context.operations().conn();
1734
1735            let branch = Branch::get_or_create(op_conn, "main").unwrap();
1736            OperationState::set_branch(op_conn, &branch.name);
1737
1738            let _op = Operation::create(op_conn, "add", &HashId::convert_str("op-1")).unwrap();
1739            let result = parse_hash(op_conn, "HEAD~1");
1740            assert!(matches!(
1741                result,
1742                Err(HashParseError::HeadOffsetOutOfRange(1))
1743            ));
1744        }
1745    }
1746
1747    mod search_hash {
1748        use super::*;
1749
1750        #[test]
1751        fn test_search_hashes_returns_matches() {
1752            let context = setup_gen();
1753            let op_conn = context.operations().conn();
1754
1755            let branch = Branch::get_or_create(op_conn, "main").unwrap();
1756            OperationState::set_branch(op_conn, &branch.name);
1757
1758            let _op_1 = Operation::create(
1759                op_conn,
1760                "add",
1761                &HashId::pad_str(
1762                    "abc0000000000000000000000000000000000000000000000000000000000001",
1763                ),
1764            )
1765            .unwrap();
1766            let _op_2 = Operation::create(
1767                op_conn,
1768                "add",
1769                &HashId::pad_str(
1770                    "abc0000000000000000000000000000000000000000000000000000000000002",
1771                ),
1772            )
1773            .unwrap();
1774            let _op_3 = Operation::create(
1775                op_conn,
1776                "add",
1777                &HashId::pad_str(
1778                    "def0000000000000000000000000000000000000000000000000000000000003",
1779                ),
1780            )
1781            .unwrap();
1782
1783            let matches = Operation::search_hashes(op_conn, "abc");
1784            assert_eq!(matches.len(), 2);
1785        }
1786
1787        #[test]
1788        fn test_search_hash_resolves_and_errors() {
1789            let context = setup_gen();
1790            let op_conn = context.operations().conn();
1791
1792            let branch = Branch::get_or_create(op_conn, "main").unwrap();
1793            OperationState::set_branch(op_conn, &branch.name);
1794
1795            let op_unique = Operation::create(
1796                op_conn,
1797                "add",
1798                &HashId::pad_str(
1799                    "def0000000000000000000000000000000000000000000000000000000000001",
1800                ),
1801            )
1802            .unwrap();
1803            let _op_ambiguous = Operation::create(
1804                op_conn,
1805                "add",
1806                &HashId::pad_str(
1807                    "abc0000000000000000000000000000000000000000000000000000000000001",
1808                ),
1809            )
1810            .unwrap();
1811            let _op_ambiguous_2 = Operation::create(
1812                op_conn,
1813                "add",
1814                &HashId::pad_str(
1815                    "abc0000000000000000000000000000000000000000000000000000000000002",
1816                ),
1817            )
1818            .unwrap();
1819
1820            let resolved = Operation::search_hash(op_conn, "def").unwrap();
1821            assert_eq!(resolved.hash, op_unique.hash);
1822
1823            let ambiguous = Operation::search_hash(op_conn, "abc");
1824            assert!(matches!(
1825                ambiguous,
1826                Err(HashParseError::OperationAmbiguous(_))
1827            ));
1828        }
1829    }
1830
1831    mod resolve_reference {
1832        use super::*;
1833
1834        #[test]
1835        fn test_resolve_reference_branch_and_hash() {
1836            let context = setup_gen();
1837            let op_conn = context.operations().conn();
1838
1839            let branch = Branch::get_or_create(op_conn, "main").unwrap();
1840            OperationState::set_branch(op_conn, &branch.name);
1841
1842            let op_unique = Operation::create(
1843                op_conn,
1844                "add",
1845                &HashId::pad_str(
1846                    "def0000000000000000000000000000000000000000000000000000000000001",
1847                ),
1848            )
1849            .unwrap();
1850
1851            let branch_hash = resolve_reference(op_conn, "main").unwrap();
1852            assert_eq!(branch_hash, op_unique.hash);
1853
1854            let hash_ref = resolve_reference(op_conn, "def").unwrap();
1855            assert_eq!(hash_ref, op_unique.hash);
1856        }
1857
1858        #[test]
1859        fn test_resolve_reference_ambiguous() {
1860            let context = setup_gen();
1861            let op_conn = context.operations().conn();
1862
1863            let branch = Branch::get_or_create(op_conn, "main").unwrap();
1864            OperationState::set_branch(op_conn, &branch.name);
1865
1866            let _op_1 = Operation::create(
1867                op_conn,
1868                "add",
1869                &HashId::pad_str(
1870                    "abc0000000000000000000000000000000000000000000000000000000000001",
1871                ),
1872            )
1873            .unwrap();
1874            let _op_2 = Operation::create(
1875                op_conn,
1876                "add",
1877                &HashId::pad_str(
1878                    "abc0000000000000000000000000000000000000000000000000000000000002",
1879                ),
1880            )
1881            .unwrap();
1882
1883            let result = resolve_reference(op_conn, "abc");
1884            assert!(matches!(result, Err(HashParseError::OperationAmbiguous(_))));
1885        }
1886    }
1887
1888    mod resolve_head {
1889        use super::*;
1890
1891        #[test]
1892        fn test_resolve_head_variants() {
1893            let context = setup_gen();
1894            let op_conn = context.operations().conn();
1895
1896            let branch = Branch::get_or_create(op_conn, "main").unwrap();
1897            OperationState::set_branch(op_conn, &branch.name);
1898
1899            let op_1 = Operation::create(op_conn, "add", &HashId::convert_str("op-1")).unwrap();
1900            let op_2 = Operation::create(op_conn, "add", &HashId::convert_str("op-2")).unwrap();
1901
1902            let head = resolve_head(op_conn, "HEAD").unwrap();
1903            assert_eq!(head, op_2.hash);
1904
1905            let head_prev = resolve_head(op_conn, "HEAD~1").unwrap();
1906            assert_eq!(head_prev, op_1.hash);
1907        }
1908
1909        #[test]
1910        fn test_resolve_head_invalid() {
1911            let context = setup_gen();
1912            let op_conn = context.operations().conn();
1913
1914            let branch = Branch::get_or_create(op_conn, "main").unwrap();
1915            OperationState::set_branch(op_conn, &branch.name);
1916
1917            let _op = Operation::create(op_conn, "add", &HashId::convert_str("op-1")).unwrap();
1918            let result = resolve_head(op_conn, "HEAD~2");
1919            assert!(matches!(
1920                result,
1921                Err(HashParseError::HeadOffsetOutOfRange(2))
1922            ));
1923        }
1924    }
1925
1926    #[test]
1927    fn test_create_operation_adds_database() {
1928        let context = setup_gen();
1929        let conn = context.graph().conn();
1930        let op_conn = context.operations().conn();
1931        let db_uuid = crate::metadata::get_db_uuid(conn);
1932        let gen_db = GenDatabase::create(op_conn, &db_uuid, "foo.db", "/foo.db").unwrap();
1933
1934        let op = create_operation(
1935            &context,
1936            "something.fa",
1937            FileTypes::Fasta,
1938            "foo",
1939            HashId::convert_str("op-1"),
1940        );
1941
1942        let databases = GenDatabase::query_by_operations(op_conn, &[op.hash]).unwrap();
1943        assert_eq!(databases[&op.hash], vec![gen_db]);
1944    }
1945
1946    #[test]
1947    fn test_gets_operations_of_branch() {
1948        let context = setup_gen();
1949        let conn = context.graph().conn();
1950        let op_conn = context.operations().conn();
1951
1952        let db_uuid = crate::metadata::get_db_uuid(conn);
1953        crate::files::GenDatabase::create(op_conn, &db_uuid, "test_db", "test_db_path").unwrap();
1954
1955        create_operation(
1956            &context,
1957            "test.fasta",
1958            FileTypes::Fasta,
1959            "foo",
1960            HashId::convert_str("op-1"),
1961        );
1962        // operations will be made in ascending order.
1963        // The branch topology is as follows. () indicate where a branch starts
1964        //
1965        //                     -> 4 -> 5
1966        //                   /
1967        //         -> 2 -> 3 (branch-1-sub-1)
1968        //        /
1969        //      branch-1
1970        //    /
1971        //   1 (main, branch-1, branch-2)
1972        //    \
1973        //    branch-2
1974        //       \
1975        //        -> 6 -> 7 (branch-2-midpoint-1) -> 8 (branch-2-sub-1)
1976        //                 \                           \
1977        //                   -> 12 -> 13                9 -> 10 -> 11
1978        //
1979        //
1980        //
1981        //
1982        create_operation(
1983            &context,
1984            "test.fasta",
1985            FileTypes::Fasta,
1986            "foo",
1987            HashId::convert_str("op-2"),
1988        );
1989        create_operation(
1990            &context,
1991            "test.fasta",
1992            FileTypes::Fasta,
1993            "foo",
1994            HashId::convert_str("op-3"),
1995        );
1996        create_operation(
1997            &context,
1998            "test.fasta",
1999            FileTypes::Fasta,
2000            "foo",
2001            HashId::convert_str("op-4"),
2002        );
2003        create_operation(
2004            &context,
2005            "test.fasta",
2006            FileTypes::Fasta,
2007            "foo",
2008            HashId::convert_str("op-5"),
2009        );
2010        OperationState::set_operation(op_conn, &HashId::convert_str("op-1"));
2011        create_operation(
2012            &context,
2013            "test.fasta",
2014            FileTypes::Fasta,
2015            "foo",
2016            HashId::convert_str("op-6"),
2017        );
2018        let _branch_2_midpoint = create_operation(
2019            &context,
2020            "test.fasta",
2021            FileTypes::Fasta,
2022            "foo",
2023            HashId::convert_str("op-7"),
2024        );
2025        create_operation(
2026            &context,
2027            "test.fasta",
2028            FileTypes::Fasta,
2029            "foo",
2030            HashId::convert_str("op-8"),
2031        );
2032        create_operation(
2033            &context,
2034            "test.fasta",
2035            FileTypes::Fasta,
2036            "foo",
2037            HashId::convert_str("op-9"),
2038        );
2039        create_operation(
2040            &context,
2041            "test.fasta",
2042            FileTypes::Fasta,
2043            "foo",
2044            HashId::convert_str("op-10"),
2045        );
2046        create_operation(
2047            &context,
2048            "test.fasta",
2049            FileTypes::Fasta,
2050            "foo",
2051            HashId::convert_str("op-11"),
2052        );
2053        OperationState::set_operation(op_conn, &HashId::convert_str("op-7"));
2054        create_operation(
2055            &context,
2056            "test.fasta",
2057            FileTypes::Fasta,
2058            "foo",
2059            HashId::convert_str("op-12"),
2060        );
2061        create_operation(
2062            &context,
2063            "test.fasta",
2064            FileTypes::Fasta,
2065            "foo",
2066            HashId::convert_str("op-13"),
2067        );
2068
2069        OperationState::set_operation(op_conn, &HashId::convert_str("op-3"));
2070        let branch_1 = Branch::get_or_create(op_conn, "branch-1").unwrap();
2071        OperationState::set_operation(op_conn, &HashId::convert_str("op-8"));
2072        let branch_2 = Branch::get_or_create(op_conn, "branch-2").unwrap();
2073        OperationState::set_operation(op_conn, &HashId::convert_str("op-5"));
2074        let branch_1_sub_1 = Branch::get_or_create(op_conn, "branch-1-sub-1").unwrap();
2075        OperationState::set_operation(op_conn, &HashId::convert_str("op-11"));
2076        let branch_2_sub_1 = Branch::get_or_create(op_conn, "branch-2-sub-1").unwrap();
2077        OperationState::set_operation(op_conn, &HashId::convert_str("op-13"));
2078        let branch_2_midpoint_1 = Branch::get_or_create(op_conn, "branch-2-midpoint-1").unwrap();
2079
2080        let ops = Branch::get_operations(op_conn, branch_2_midpoint_1.id)
2081            .iter()
2082            .map(|f| f.hash)
2083            .collect::<Vec<_>>();
2084        assert_eq!(
2085            ops,
2086            vec![
2087                HashId::convert_str("op-1"),
2088                HashId::convert_str("op-6"),
2089                HashId::convert_str("op-7"),
2090                HashId::convert_str("op-12"),
2091                HashId::convert_str("op-13")
2092            ]
2093        );
2094
2095        let ops = Branch::get_operations(op_conn, branch_1.id)
2096            .iter()
2097            .map(|f| f.hash)
2098            .collect::<Vec<_>>();
2099        assert_eq!(
2100            ops,
2101            vec![
2102                HashId::convert_str("op-1"),
2103                HashId::convert_str("op-2"),
2104                HashId::convert_str("op-3")
2105            ]
2106        );
2107
2108        let ops = Branch::get_operations(op_conn, branch_2.id)
2109            .iter()
2110            .map(|f| f.hash)
2111            .collect::<Vec<_>>();
2112        assert_eq!(
2113            ops,
2114            vec![
2115                HashId::convert_str("op-1"),
2116                HashId::convert_str("op-6"),
2117                HashId::convert_str("op-7"),
2118                HashId::convert_str("op-8")
2119            ]
2120        );
2121
2122        let ops = Branch::get_operations(op_conn, branch_1_sub_1.id)
2123            .iter()
2124            .map(|f| f.hash)
2125            .collect::<Vec<_>>();
2126        assert_eq!(
2127            ops,
2128            vec![
2129                HashId::convert_str("op-1"),
2130                HashId::convert_str("op-2"),
2131                HashId::convert_str("op-3"),
2132                HashId::convert_str("op-4"),
2133                HashId::convert_str("op-5")
2134            ]
2135        );
2136
2137        let ops = Branch::get_operations(op_conn, branch_2_sub_1.id)
2138            .iter()
2139            .map(|f: &Operation| f.hash)
2140            .collect::<Vec<_>>();
2141        assert_eq!(
2142            ops,
2143            vec![
2144                HashId::convert_str("op-1"),
2145                HashId::convert_str("op-6"),
2146                HashId::convert_str("op-7"),
2147                HashId::convert_str("op-8"),
2148                HashId::convert_str("op-9"),
2149                HashId::convert_str("op-10"),
2150                HashId::convert_str("op-11")
2151            ]
2152        );
2153    }
2154
2155    #[test]
2156    fn test_graph_representation() {
2157        let context = setup_gen();
2158        let op_conn = context.operations().conn();
2159
2160        // operations will be made in ascending order.
2161        // The branch topology is as follows. () indicate where a branch starts
2162        //
2163        //
2164        //
2165        //    branch-3   /-> 7
2166        //    main      1 -> 2 -> 3
2167        //    branch-1             \-> 4 -> 5
2168        //    branch-2                  \-> 6
2169
2170        let mut expected_graph = OperationGraph::new();
2171        expected_graph.add_edge(HashId::convert_str("op-1"), HashId::convert_str("op-2"), ());
2172        expected_graph.add_edge(HashId::convert_str("op-2"), HashId::convert_str("op-3"), ());
2173        expected_graph.add_edge(HashId::convert_str("op-3"), HashId::convert_str("op-4"), ());
2174        expected_graph.add_edge(HashId::convert_str("op-4"), HashId::convert_str("op-5"), ());
2175        expected_graph.add_edge(HashId::convert_str("op-4"), HashId::convert_str("op-6"), ());
2176        expected_graph.add_edge(HashId::convert_str("op-1"), HashId::convert_str("op-7"), ());
2177
2178        let _ = Operation::create(op_conn, "vcf_addition", &HashId::convert_str("op-1")).unwrap();
2179        let _ = Operation::create(op_conn, "vcf_addition", &HashId::convert_str("op-2")).unwrap();
2180        let _ = Operation::create(op_conn, "vcf_addition", &HashId::convert_str("op-3")).unwrap();
2181        Branch::get_or_create(op_conn, "branch-1").unwrap();
2182        OperationState::set_branch(op_conn, "branch-1");
2183        let _ = Operation::create(op_conn, "vcf_addition", &HashId::convert_str("op-4")).unwrap();
2184        let _ = Operation::create(op_conn, "vcf_addition", &HashId::convert_str("op-5")).unwrap();
2185        OperationState::set_operation(op_conn, &HashId::convert_str("op-4"));
2186        Branch::get_or_create(op_conn, "branch-2").unwrap();
2187        OperationState::set_branch(op_conn, "branch-2");
2188        let _ = Operation::create(op_conn, "vcf_addition", &HashId::convert_str("op-6")).unwrap();
2189        OperationState::set_operation(op_conn, &HashId::convert_str("op-1"));
2190        Branch::get_or_create(op_conn, "branch-3").unwrap();
2191        OperationState::set_branch(op_conn, "branch-3");
2192        let _ = Operation::create(op_conn, "vcf_addition", &HashId::convert_str("op-7")).unwrap();
2193        let graph = Operation::get_operation_graph(op_conn);
2194
2195        assert_eq!(
2196            graph.nodes().collect::<HashSet<_>>(),
2197            expected_graph.nodes().collect::<HashSet<_>>()
2198        );
2199        assert_eq!(
2200            graph.all_edges().collect::<HashSet<_>>(),
2201            expected_graph.all_edges().collect::<HashSet<_>>()
2202        );
2203    }
2204
2205    #[test]
2206    fn test_path_between() {
2207        let context = setup_gen();
2208        let conn = context.graph().conn();
2209        let op_conn = context.operations().conn();
2210
2211        let db_uuid = crate::metadata::get_db_uuid(conn);
2212        crate::files::GenDatabase::create(op_conn, &db_uuid, "test_db", "test_db_path").unwrap();
2213
2214        // operations will be made in ascending order.
2215        // The branch topology is as follows. () indicate where a branch starts
2216        //
2217        //
2218        //
2219        //    branch-3   /-> 7
2220        //    main      1 -> 2 -> 3
2221        //    branch-1             \-> 4 -> 5
2222        //    branch-2                  \-> 6
2223
2224        create_operation(
2225            &context,
2226            "test.fasta",
2227            FileTypes::Fasta,
2228            "foo",
2229            HashId::convert_str("op-1"),
2230        );
2231        create_operation(
2232            &context,
2233            "test.fasta",
2234            FileTypes::Fasta,
2235            "foo",
2236            HashId::convert_str("op-2"),
2237        );
2238        create_operation(
2239            &context,
2240            "test.fasta",
2241            FileTypes::Fasta,
2242            "foo",
2243            HashId::convert_str("op-3"),
2244        );
2245        Branch::get_or_create(op_conn, "branch-1").unwrap();
2246        OperationState::set_branch(op_conn, "branch-1");
2247        create_operation(
2248            &context,
2249            "test.fasta",
2250            FileTypes::Fasta,
2251            "foo",
2252            HashId::convert_str("op-4"),
2253        );
2254        create_operation(
2255            &context,
2256            "test.fasta",
2257            FileTypes::Fasta,
2258            "foo",
2259            HashId::convert_str("op-5"),
2260        );
2261        OperationState::set_operation(op_conn, &HashId::convert_str("op-4"));
2262        Branch::get_or_create(op_conn, "branch-2").unwrap();
2263        OperationState::set_branch(op_conn, "branch-2");
2264        create_operation(
2265            &context,
2266            "test.fasta",
2267            FileTypes::Fasta,
2268            "foo",
2269            HashId::convert_str("op-6"),
2270        );
2271        OperationState::set_operation(op_conn, &HashId::convert_str("op-1"));
2272        Branch::get_or_create(op_conn, "branch-3").unwrap();
2273        OperationState::set_branch(op_conn, "branch-3");
2274        create_operation(
2275            &context,
2276            "test.fasta",
2277            FileTypes::Fasta,
2278            "foo",
2279            HashId::convert_str("op-7"),
2280        );
2281        assert_eq!(
2282            Operation::get_path_between(
2283                op_conn,
2284                HashId::convert_str("op-1"),
2285                HashId::convert_str("op-6")
2286            ),
2287            vec![
2288                (
2289                    HashId::convert_str("op-1"),
2290                    Direction::Outgoing,
2291                    HashId::convert_str("op-2")
2292                ),
2293                (
2294                    HashId::convert_str("op-2"),
2295                    Direction::Outgoing,
2296                    HashId::convert_str("op-3")
2297                ),
2298                (
2299                    HashId::convert_str("op-3"),
2300                    Direction::Outgoing,
2301                    HashId::convert_str("op-4")
2302                ),
2303                (
2304                    HashId::convert_str("op-4"),
2305                    Direction::Outgoing,
2306                    HashId::convert_str("op-6")
2307                ),
2308            ]
2309        );
2310
2311        assert_eq!(
2312            Operation::get_path_between(
2313                op_conn,
2314                HashId::convert_str("op-7"),
2315                HashId::convert_str("op-1")
2316            ),
2317            vec![(
2318                HashId::convert_str("op-7"),
2319                Direction::Incoming,
2320                HashId::convert_str("op-1")
2321            ),]
2322        );
2323
2324        assert_eq!(
2325            Operation::get_path_between(
2326                op_conn,
2327                HashId::convert_str("op-3"),
2328                HashId::convert_str("op-7")
2329            ),
2330            vec![
2331                (
2332                    HashId::convert_str("op-3"),
2333                    Direction::Incoming,
2334                    HashId::convert_str("op-2")
2335                ),
2336                (
2337                    HashId::convert_str("op-2"),
2338                    Direction::Incoming,
2339                    HashId::convert_str("op-1")
2340                ),
2341                (
2342                    HashId::convert_str("op-1"),
2343                    Direction::Outgoing,
2344                    HashId::convert_str("op-7")
2345                ),
2346            ]
2347        );
2348    }
2349
2350    #[test]
2351    fn test_remote_create() {
2352        let context = setup_gen();
2353        let op_conn = context.operations().conn();
2354
2355        // Test successful remote creation
2356        let remote = Remote::create(op_conn, "origin", "https://example.com/repo.gen").unwrap();
2357        assert_eq!(remote.name, "origin");
2358        assert_eq!(remote.url, "https://example.com/repo.gen");
2359
2360        // Test duplicate name constraint violation
2361        let result = Remote::create(op_conn, "origin", "https://different.com/repo.gen");
2362        assert!(result.is_err());
2363    }
2364
2365    #[test]
2366    fn test_remote_get_by_name() {
2367        let context = setup_gen();
2368        let op_conn = context.operations().conn();
2369
2370        // Test getting non-existent remote
2371        let result = Remote::get_by_name_optional(op_conn, "nonexistent");
2372        assert!(result.is_none());
2373
2374        // Create a remote and test retrieval
2375        Remote::create(op_conn, "upstream", "https://upstream.com/repo.gen").unwrap();
2376        let result = Remote::get_by_name_optional(op_conn, "upstream");
2377        assert!(result.is_some());
2378        let remote = result.unwrap();
2379        assert_eq!(remote.name, "upstream");
2380        assert_eq!(remote.url, "https://upstream.com/repo.gen");
2381    }
2382
2383    #[test]
2384    fn test_remote_list_all() {
2385        let context = setup_gen();
2386        let op_conn = context.operations().conn();
2387
2388        // Test empty list
2389        let remotes = Remote::list_all(op_conn);
2390        assert!(remotes.is_empty());
2391
2392        // Create multiple remotes
2393        Remote::create(op_conn, "origin", "https://origin.com/repo.gen").unwrap();
2394        Remote::create(op_conn, "upstream", "https://upstream.com/repo.gen").unwrap();
2395        Remote::create(op_conn, "fork", "https://fork.com/repo.gen").unwrap();
2396
2397        // Test list returns all remotes in alphabetical order
2398        let remotes = Remote::list_all(op_conn);
2399        assert_eq!(remotes.len(), 3);
2400        assert_eq!(remotes[0].name, "fork");
2401        assert_eq!(remotes[1].name, "origin");
2402        assert_eq!(remotes[2].name, "upstream");
2403    }
2404
2405    #[test]
2406    fn test_remote_delete() {
2407        let context = setup_gen();
2408        let op_conn = context.operations().conn();
2409
2410        // Create a remote
2411        Remote::create(op_conn, "temp", "https://temp.com/repo.gen").unwrap();
2412
2413        // Verify it exists
2414        let remote = Remote::get_by_name_optional(op_conn, "temp");
2415        assert!(remote.is_some());
2416
2417        // Delete the remote
2418        let result = Remote::delete(op_conn, "temp");
2419        assert!(result.is_ok());
2420
2421        // Verify it's gone
2422        let remote = Remote::get_by_name_optional(op_conn, "temp");
2423        assert!(remote.is_none());
2424
2425        // Test deleting non-existent remote (should return error)
2426        let result = Remote::delete(op_conn, "nonexistent");
2427        assert!(result.is_err());
2428    }
2429
2430    #[test]
2431    fn test_remote_delete_with_branch_associations() {
2432        let context = setup_gen();
2433        let op_conn = context.operations().conn();
2434
2435        // Create a remote
2436        Remote::create(op_conn, "test_remote", "https://test.com/repo.gen").unwrap();
2437
2438        // Create a branch and associate it with the remote
2439        let branch = Branch::get_or_create(op_conn, "test_branch").unwrap();
2440
2441        // Set the remote association (this would be done by the Branch::set_remote method when implemented)
2442        op_conn
2443            .execute(
2444                "UPDATE branch SET remote_name = ?1 WHERE id = ?2",
2445                params!["test_remote", branch.id],
2446            )
2447            .unwrap();
2448
2449        // Verify the association exists
2450        let remote_name: Option<String> = op_conn
2451            .query_row(
2452                "SELECT remote_name FROM branch WHERE id = ?1",
2453                params![branch.id],
2454                |row| row.get(0),
2455            )
2456            .unwrap();
2457        assert_eq!(remote_name, Some("test_remote".to_string()));
2458
2459        // Delete the remote - this should succeed and automatically set branch remote_name to NULL
2460        let result = Remote::delete(op_conn, "test_remote");
2461        assert!(result.is_ok());
2462
2463        // Verify the branch association was automatically cleared by the foreign key constraint
2464        let remote_name_after_delete: Option<String> = op_conn
2465            .query_row(
2466                "SELECT remote_name FROM branch WHERE id = ?1",
2467                params![branch.id],
2468                |row| row.get(0),
2469            )
2470            .unwrap();
2471        assert_eq!(remote_name_after_delete, None);
2472
2473        // Verify the remote was actually deleted
2474        let remote = Remote::get_by_name_optional(op_conn, "test_remote");
2475        assert!(remote.is_none());
2476    }
2477
2478    #[test]
2479    fn test_branch_set_remote() {
2480        let context = setup_gen();
2481        let op_conn = context.operations().conn();
2482
2483        // Create a remote
2484        Remote::create(op_conn, "origin", "https://example.com/repo.gen").unwrap();
2485
2486        // Create a branch
2487        let branch = Branch::get_or_create(op_conn, "test_branch").unwrap();
2488
2489        // Initially, branch should have no remote
2490        let remote = Branch::get_remote(op_conn, branch.id);
2491        assert_eq!(remote, None);
2492
2493        // Set the remote association
2494        Branch::set_remote(op_conn, branch.id, Some("origin")).unwrap();
2495
2496        // Verify the association was set
2497        let remote = Branch::get_remote(op_conn, branch.id);
2498        assert_eq!(remote, Some("origin".to_string()));
2499
2500        // Clear the remote association
2501        Branch::set_remote(op_conn, branch.id, None).unwrap();
2502
2503        // Verify the association was cleared
2504        let remote = Branch::get_remote(op_conn, branch.id);
2505        assert_eq!(remote, None);
2506    }
2507
2508    #[test]
2509    fn test_branch_get_remote() {
2510        let context = setup_gen();
2511        let op_conn = context.operations().conn();
2512
2513        // Create remotes
2514        Remote::create(op_conn, "origin", "https://example.com/repo.gen").unwrap();
2515        Remote::create(op_conn, "upstream", "https://upstream.com/repo.gen").unwrap();
2516
2517        // Create branches
2518        let branch1 = Branch::get_or_create(op_conn, "branch1").unwrap();
2519        let branch2 = Branch::get_or_create(op_conn, "branch2").unwrap();
2520
2521        // Set different remotes for each branch
2522        Branch::set_remote(op_conn, branch1.id, Some("origin")).unwrap();
2523        Branch::set_remote(op_conn, branch2.id, Some("upstream")).unwrap();
2524
2525        // Verify each branch has the correct remote
2526        assert_eq!(
2527            Branch::get_remote(op_conn, branch1.id),
2528            Some("origin".to_string())
2529        );
2530        assert_eq!(
2531            Branch::get_remote(op_conn, branch2.id),
2532            Some("upstream".to_string())
2533        );
2534
2535        // Test non-existent branch
2536        assert_eq!(Branch::get_remote(op_conn, 99999), None);
2537    }
2538
2539    #[test]
2540    fn test_branch_create_with_remote() {
2541        let context = setup_gen();
2542        let op_conn = context.operations().conn();
2543
2544        // Create a remote
2545        Remote::create(op_conn, "origin", "https://example.com/repo.gen").unwrap();
2546
2547        // Create a branch with remote association
2548        let branch = Branch::create_with_remote(op_conn, "test_branch", Some("origin")).unwrap();
2549
2550        // Verify the branch was created with the remote association
2551        assert_eq!(branch.remote_name, Some("origin".to_string()));
2552        assert_eq!(
2553            Branch::get_remote(op_conn, branch.id),
2554            Some("origin".to_string())
2555        );
2556
2557        // Create a branch without remote association
2558        let branch2 = Branch::create_with_remote(op_conn, "test_branch2", None).unwrap();
2559        assert_eq!(branch2.remote_name, None);
2560        assert_eq!(Branch::get_remote(op_conn, branch2.id), None);
2561    }
2562
2563    #[test]
2564    fn test_branch_process_row_with_remote() {
2565        let context = setup_gen();
2566        let op_conn = context.operations().conn();
2567
2568        // Create a remote
2569        Remote::create(op_conn, "origin", "https://example.com/repo.gen").unwrap();
2570
2571        // Create a branch with remote
2572        let branch = Branch::create_with_remote(op_conn, "test_branch", Some("origin")).unwrap();
2573
2574        // Query the branch back to test process_row
2575        let branches = Branch::query(
2576            op_conn,
2577            "SELECT * FROM branch WHERE id = ?1",
2578            params![branch.id],
2579        );
2580        assert_eq!(branches.len(), 1);
2581
2582        let queried_branch = &branches[0];
2583        assert_eq!(queried_branch.id, branch.id);
2584        assert_eq!(queried_branch.name, "test_branch");
2585        assert_eq!(queried_branch.remote_name, Some("origin".to_string()));
2586    }
2587
2588    #[test]
2589    fn test_branch_set_remote_foreign_key_constraint() {
2590        let context = setup_gen();
2591        let op_conn = context.operations().conn();
2592
2593        // Create a branch
2594        let branch = Branch::get_or_create(op_conn, "test_branch").unwrap();
2595
2596        // Try to set a remote that doesn't exist - this should fail due to foreign key constraint
2597        let result = Branch::set_remote(op_conn, branch.id, Some("nonexistent_remote"));
2598        assert!(result.is_err());
2599
2600        // Verify the branch still has no remote
2601        let remote = Branch::get_remote(op_conn, branch.id);
2602        assert_eq!(remote, None);
2603    }
2604
2605    #[test]
2606    fn operation_capnp_serialization() {
2607        use capnp::message::TypedBuilder;
2608
2609        let model = Operation {
2610            hash: HashId::convert_str("test"),
2611            parent_hash: Some(HashId::convert_str("parent")),
2612            change_type: "foo".to_string(),
2613            created_on: 0,
2614        };
2615
2616        let mut message = TypedBuilder::<operation::Owned>::new_default();
2617        let mut root = message.init_root();
2618        model.write_capnp(&mut root);
2619
2620        let deserialized = Operation::read_capnp(root.into_reader());
2621        assert_eq!(model, deserialized);
2622    }
2623
2624    #[test]
2625    fn operation_capnp_serialization_no_parent() {
2626        use capnp::message::TypedBuilder;
2627
2628        let model = Operation {
2629            hash: HashId::convert_str("test"),
2630            parent_hash: None,
2631            change_type: "foo".to_string(),
2632            created_on: 1,
2633        };
2634
2635        let mut message = TypedBuilder::<operation::Owned>::new_default();
2636        let mut root = message.init_root();
2637        model.write_capnp(&mut root);
2638
2639        let deserialized = Operation::read_capnp(root.into_reader());
2640        assert_eq!(model, deserialized);
2641    }
2642
2643    #[test]
2644    fn file_addition_capnp_serialization() {
2645        use capnp::message::TypedBuilder;
2646
2647        let file_addition = FileAddition {
2648            id: HashId([42u8; 32]),
2649            asset_uri: "file://test/path.fasta".to_string(),
2650            file_type: FileTypes::Fasta,
2651            checksum: HashId([24u8; 32]),
2652        };
2653
2654        let mut message =
2655            TypedBuilder::<crate::gen_models_capnp::file_addition::Owned>::new_default();
2656        let mut root = message.init_root();
2657        file_addition.write_capnp(&mut root);
2658
2659        let deserialized = FileAddition::read_capnp(root.into_reader());
2660        assert_eq!(file_addition, deserialized);
2661    }
2662
2663    #[test]
2664    fn operation_summary_capnp_serialization() {
2665        use capnp::message::TypedBuilder;
2666
2667        let operation_summary = OperationSummary {
2668            id: 123,
2669            operation_hash: HashId::convert_str("op-hash-123"),
2670            summary: "Added new sequences from FASTA file".to_string(),
2671        };
2672
2673        let mut message =
2674            TypedBuilder::<crate::gen_models_capnp::operation_summary::Owned>::new_default();
2675        let mut root = message.init_root();
2676        operation_summary.write_capnp(&mut root);
2677
2678        let deserialized = OperationSummary::read_capnp(root.into_reader());
2679        assert_eq!(operation_summary, deserialized);
2680    }
2681
2682    #[test]
2683    fn test_calculate_stream_hash() {
2684        let content = b"Hello, World!";
2685        let cursor = Cursor::new(content);
2686        let hash = calculate_stream_hash(cursor).unwrap();
2687
2688        assert_eq!(hash.len(), 32);
2689
2690        // Test consistency - same content should produce same hash
2691        let cursor2 = Cursor::new(content);
2692        let hash2 = calculate_stream_hash(cursor2).unwrap();
2693        assert_eq!(hash, hash2);
2694
2695        // Test different content produces different hash
2696        let different_content = b"Hello, World!!";
2697        let cursor3 = Cursor::new(different_content);
2698        let hash3 = calculate_stream_hash(cursor3).unwrap();
2699        assert_ne!(hash, hash3);
2700    }
2701
2702    #[test]
2703    fn test_calculate_file_checksum() {
2704        let mut temp_file = NamedTempFile::new().unwrap();
2705        let content = b"Test file content for checksum calculation";
2706        temp_file.write_all(content).unwrap();
2707        temp_file.flush().unwrap();
2708
2709        let checksum = calculate_file_checksum(temp_file.path()).unwrap();
2710
2711        assert_eq!(checksum.0.len(), 32);
2712
2713        // Test consistency - same file should produce same checksum
2714        let checksum2 = calculate_file_checksum(temp_file.path()).unwrap();
2715        assert_eq!(checksum, checksum2);
2716
2717        // Test with different file content
2718        let mut temp_file2 = NamedTempFile::new().unwrap();
2719        let different_content = b"Different test file content";
2720        temp_file2.write_all(different_content).unwrap();
2721        temp_file2.flush().unwrap();
2722
2723        let checksum3 = calculate_file_checksum(temp_file2.path()).unwrap();
2724        assert_ne!(checksum, checksum3);
2725    }
2726
2727    #[test]
2728    fn test_calculate_file_checksum_nonexistent_file() {
2729        let result = calculate_file_checksum("/nonexistent/file/path");
2730        assert!(result.is_err());
2731        assert!(matches!(
2732            result.unwrap_err().kind(),
2733            std::io::ErrorKind::NotFound
2734        ));
2735    }
2736
2737    #[test]
2738    fn test_operation_file_new_infers_file_type_from_path() {
2739        let operation_file = OperationFile::new("fixtures/sample.gb");
2740
2741        assert_eq!(operation_file.filename, "sample.gb");
2742        assert_eq!(operation_file.file_path, "fixtures/sample.gb");
2743        assert_eq!(operation_file.file_type, FileTypes::GenBank);
2744        assert_eq!(operation_file.checksum_override, None);
2745    }
2746
2747    #[test]
2748    fn test_operation_file_storage_path_normalizes_absolute_repo_path() {
2749        let context = setup_gen();
2750        let repo_root = context.workspace().repo_root().unwrap();
2751        let absolute_path = repo_root.join("nested").join("sample.fa");
2752
2753        fs::create_dir_all(absolute_path.parent().unwrap()).unwrap();
2754        fs::write(&absolute_path, b"sample").unwrap();
2755
2756        let checksum = calculate_file_checksum(&absolute_path).unwrap();
2757        let storage_path = OperationFile::storage_file_path(
2758            context.workspace(),
2759            &absolute_path.to_string_lossy(),
2760            &checksum,
2761        )
2762        .unwrap();
2763
2764        assert_eq!(storage_path, "nested/sample.fa");
2765    }
2766
2767    #[test]
2768    fn operation_add_file_keeps_compression_suffix_for_asset_path() {
2769        let context = setup_gen();
2770        let operation_conn = context.operations().conn();
2771        let fixture_path =
2772            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/simple.fa.bgz");
2773        let outside_dir = tempfile::tempdir().unwrap();
2774        let outside_path = outside_dir.path().join("simple.fa.bgz");
2775        fs::copy(&fixture_path, &outside_path).unwrap();
2776        let outside_path_string = outside_path.to_string_lossy().to_string();
2777
2778        let file_addition = FileAddition::get_or_create(
2779            context.workspace(),
2780            operation_conn,
2781            &outside_path_string,
2782            FileTypes::Fasta,
2783            None,
2784        )
2785        .unwrap();
2786        let operation_hash = HashId(calculate_hash("compressed-file-operation"));
2787        let operation = Operation::create_without_tracking(
2788            operation_conn,
2789            &operation_hash,
2790            "add-file",
2791            None,
2792            None,
2793        )
2794        .unwrap();
2795
2796        Operation::add_file(
2797            context.workspace(),
2798            operation_conn,
2799            &operation.hash,
2800            &file_addition,
2801            "simple.fa.bgz",
2802            &outside_path_string,
2803        )
2804        .unwrap();
2805
2806        let operation_files =
2807            OperationFile::get_files_for_operation(operation_conn, &operation.hash).unwrap();
2808
2809        assert_eq!(operation_files[0].filename, "simple.fa.bgz");
2810        assert_eq!(
2811            operation_files[0].file_path,
2812            format!(".gen/assets/{}.fa.bgz", file_addition.checksum),
2813        );
2814        assert_eq!(
2815            operation_files[0].asset_uri,
2816            LocalAssetUri::asset_uri(&format!(".gen/assets/{}.fa.bgz", file_addition.checksum)),
2817        );
2818    }
2819
2820    #[test]
2821    fn test_file_addition_get_or_create() {
2822        let context = setup_gen();
2823        let op_conn = context.operations().conn();
2824        let repo_root = context.workspace().repo_root().unwrap();
2825
2826        let file1_path = repo_root.join("test_file.txt");
2827        fs::write(&file1_path, b"Test file content").unwrap();
2828        let file1_path_str = file1_path.to_string_lossy().to_string();
2829        let fa1 = FileAddition::get_or_create(
2830            context.workspace(),
2831            op_conn,
2832            &file1_path_str,
2833            FileTypes::Fasta,
2834            None,
2835        )
2836        .expect("Failed to create FileAddition");
2837
2838        let checksum = calculate_file_checksum(&file1_path_str).unwrap();
2839        let expected_asset_path = format!(".gen/assets/{checksum}.txt");
2840        assert_eq!(
2841            fa1.asset_uri,
2842            LocalAssetUri::asset_uri(&expected_asset_path)
2843        );
2844        assert_eq!(fa1.file_path(), expected_asset_path);
2845
2846        let relative1_id = LocalAssetUri::generate_file_addition_id(
2847            &checksum,
2848            &LocalAssetUri::asset_uri(&expected_asset_path),
2849        );
2850
2851        assert_eq!(fa1.id, relative1_id);
2852        assert!(
2853            context
2854                .workspace()
2855                .asset_dir()
2856                .unwrap()
2857                .join(fa1.clone().hashed_filename())
2858                .exists()
2859        );
2860
2861        // Second call with same file should return the same FileAddition
2862        let fa2 = FileAddition::get_or_create(
2863            context.workspace(),
2864            op_conn,
2865            &file1_path_str,
2866            FileTypes::Fasta,
2867            None,
2868        )
2869        .expect("Failed to get existing FileAddition");
2870
2871        assert_eq!(fa1, fa2);
2872
2873        let file2_path = repo_root.join("nested").join("file2.txt");
2874        fs::create_dir_all(file2_path.parent().unwrap()).unwrap();
2875        fs::write(&file2_path, b"Test file content").unwrap();
2876        let file2_path_str = file2_path.to_string_lossy().to_string();
2877
2878        let fa3 = FileAddition::get_or_create(
2879            context.workspace(),
2880            op_conn,
2881            &file2_path_str,
2882            FileTypes::Fasta,
2883            None,
2884        )
2885        .expect("Failed to create different FileAddition");
2886
2887        assert_eq!(fa1.id, fa3.id);
2888
2889        fs::write(&file1_path, b"new content").unwrap();
2890        let fa1_new = FileAddition::get_or_create(
2891            context.workspace(),
2892            op_conn,
2893            &file1_path_str,
2894            FileTypes::Fasta,
2895            None,
2896        )
2897        .expect("Failed to create FileAddition");
2898
2899        assert_ne!(fa1.id, fa1_new.id);
2900
2901        let mut outside_file = tempfile::NamedTempFile::new().unwrap();
2902        outside_file.write_all(b"Outside repo file").unwrap();
2903        outside_file.flush().unwrap();
2904        let outside_path = outside_file.path().to_string_lossy().to_string();
2905        let outside_checksum = calculate_file_checksum(outside_file.path()).unwrap();
2906        let outside_suffix = LocalAssetUri::new(&outside_file.path().to_string_lossy())
2907            .suffix()
2908            .unwrap();
2909        let outside_asset_path = format!(".gen/assets/{outside_checksum}.{outside_suffix}");
2910
2911        let outside = FileAddition::get_or_create(
2912            context.workspace(),
2913            op_conn,
2914            &outside_path,
2915            FileTypes::Fasta,
2916            None,
2917        )
2918        .expect("Failed to create external FileAddition");
2919
2920        assert_eq!(
2921            outside.asset_uri,
2922            LocalAssetUri::asset_uri(&outside_asset_path)
2923        );
2924        assert_eq!(outside.file_path(), outside_asset_path);
2925        assert!(
2926            context
2927                .workspace()
2928                .asset_dir()
2929                .unwrap()
2930                .join(outside.clone().hashed_filename())
2931                .exists()
2932        );
2933    }
2934
2935    #[test]
2936    fn test_file_addition_get_or_create_http_uri() {
2937        let context = setup_gen();
2938        let op_conn = context.operations().conn();
2939        let asset_uri = "https://example.com/assets/reference.fa";
2940
2941        let addition = FileAddition::get_or_create(
2942            context.workspace(),
2943            op_conn,
2944            asset_uri,
2945            FileTypes::Fasta,
2946            None,
2947        )
2948        .expect("Failed to create HTTP FileAddition");
2949
2950        assert_eq!(addition.asset_uri, asset_uri);
2951        assert_eq!(addition.file_path(), asset_uri);
2952        assert!(
2953            fs::read_dir(context.workspace().asset_dir().unwrap())
2954                .unwrap()
2955                .next()
2956                .is_none()
2957        );
2958    }
2959
2960    #[test]
2961    fn test_file_addition_get_or_create_remote_uri() {
2962        let context = setup_gen();
2963        let op_conn = context.operations().conn();
2964        let asset_uri = "s3://bucket/reference.fa";
2965
2966        let addition = FileAddition::get_or_create(
2967            context.workspace(),
2968            op_conn,
2969            asset_uri,
2970            FileTypes::Fasta,
2971            None,
2972        )
2973        .expect("Failed to create remote FileAddition");
2974
2975        assert_eq!(addition.asset_uri, asset_uri);
2976        assert_eq!(addition.file_path(), asset_uri);
2977    }
2978
2979    #[test]
2980    fn test_add_files_operation_stores_shared_unmodified_asset_once_across_operations() {
2981        let context = setup_gen();
2982        let graph_conn = context.graph().conn();
2983        let operation_conn = context.operations().conn();
2984        let workspace = context.workspace();
2985
2986        let db_uuid = metadata::get_db_uuid(graph_conn);
2987        GenDatabase::create(operation_conn, &db_uuid, "default", "default.db").unwrap();
2988        Branch::get_or_create(operation_conn, "main").unwrap();
2989        OperationState::set_branch(operation_conn, "main");
2990
2991        let repo_root = workspace.repo_root().unwrap();
2992        fs::write(repo_root.join("shared.txt"), "shared contents").unwrap();
2993        fs::write(repo_root.join("unique.txt"), "unique contents").unwrap();
2994
2995        let operation_1 =
2996            add_files_operation(&context, &["shared.txt".to_string()], Some("first")).unwrap();
2997        let operation_2 = add_files_operation(
2998            &context,
2999            &["shared.txt".to_string(), "unique.txt".to_string()],
3000            Some("second"),
3001        )
3002        .unwrap();
3003
3004        let operation_1_files =
3005            OperationFile::get_files_for_operation(operation_conn, &operation_1.hash).unwrap();
3006        let operation_2_files =
3007            OperationFile::get_files_for_operation(operation_conn, &operation_2.hash).unwrap();
3008
3009        let shared_file_1 = operation_1_files
3010            .iter()
3011            .find(|file| file.file_path == "shared.txt")
3012            .unwrap();
3013        let shared_file_2 = operation_2_files
3014            .iter()
3015            .find(|file| file.file_path == "shared.txt")
3016            .unwrap();
3017
3018        assert_eq!(shared_file_1.id, shared_file_2.id);
3019
3020        let assets_dir = workspace.asset_dir().unwrap();
3021        let asset_names = fs::read_dir(&assets_dir)
3022            .unwrap()
3023            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
3024            .collect::<Vec<_>>();
3025
3026        assert_eq!(asset_names.len(), 2);
3027        assert!(asset_names.contains(&shared_file_1.clone().hashed_filename()));
3028        assert!(
3029            asset_names.contains(
3030                &operation_2_files
3031                    .iter()
3032                    .find(|file| file.file_path == "unique.txt")
3033                    .unwrap()
3034                    .clone()
3035                    .hashed_filename()
3036            )
3037        );
3038    }
3039
3040    #[test]
3041    fn test_add_files_operation_tracks_distinct_filenames_for_same_asset()
3042    -> Result<(), Box<dyn std::error::Error>> {
3043        let context = setup_gen();
3044        let graph_conn = context.graph().conn();
3045        let operation_conn = context.operations().conn();
3046
3047        let db_uuid = metadata::get_db_uuid(graph_conn);
3048        GenDatabase::create(operation_conn, &db_uuid, "default", "default.db")?;
3049        Branch::get_or_create(operation_conn, "main")?;
3050        OperationState::set_branch(operation_conn, "main");
3051
3052        let outside_dir = tempfile::tempdir()?;
3053        let alpha_path = outside_dir.path().join("alpha.fa");
3054        let beta_path = outside_dir.path().join("beta.fa");
3055        fs::write(&alpha_path, "shared contents")?;
3056        fs::write(&beta_path, "shared contents")?;
3057
3058        let operation = add_files_operation(
3059            &context,
3060            &[
3061                alpha_path.to_string_lossy().to_string(),
3062                beta_path.to_string_lossy().to_string(),
3063            ],
3064            Some("same asset, different filenames"),
3065        )
3066        .map_err(|err| -> Box<dyn std::error::Error> { Box::new(err) })?;
3067
3068        let mut operation_files =
3069            OperationFile::get_files_for_operation(operation_conn, &operation.hash)
3070                .map_err(|err| -> Box<dyn std::error::Error> { Box::new(err) })?;
3071        operation_files.sort_by(|a, b| a.filename.cmp(&b.filename));
3072
3073        assert_eq!(
3074            operation_files
3075                .iter()
3076                .map(|file| file.filename.clone())
3077                .collect::<Vec<_>>(),
3078            vec!["alpha.fa".to_string(), "beta.fa".to_string()],
3079        );
3080        assert_eq!(operation_files[0].id, operation_files[1].id);
3081        assert_eq!(operation_files[0].checksum, operation_files[1].checksum);
3082        Ok(())
3083    }
3084
3085    #[test]
3086    fn test_operation_file_query_by_operations_includes_filename_and_asset_metadata()
3087    -> Result<(), Box<dyn std::error::Error>> {
3088        let context = setup_gen();
3089        let graph_conn = context.graph().conn();
3090        let operation_conn = context.operations().conn();
3091
3092        let db_uuid = metadata::get_db_uuid(graph_conn);
3093        GenDatabase::create(operation_conn, &db_uuid, "default", "default.db")?;
3094        Branch::get_or_create(operation_conn, "main")?;
3095        OperationState::set_branch(operation_conn, "main");
3096
3097        let outside_dir = tempfile::tempdir()?;
3098        let alpha_path = outside_dir.path().join("alpha.fa");
3099        let beta_path = outside_dir.path().join("beta.fa");
3100        fs::write(&alpha_path, "shared contents")?;
3101        fs::write(&beta_path, "shared contents")?;
3102
3103        let operation_1 =
3104            add_files_operation(&context, &[alpha_path.to_string_lossy().to_string()], None)
3105                .map_err(|err| -> Box<dyn std::error::Error> { Box::new(err) })?;
3106        let operation_2 =
3107            add_files_operation(&context, &[beta_path.to_string_lossy().to_string()], None)
3108                .map_err(|err| -> Box<dyn std::error::Error> { Box::new(err) })?;
3109
3110        let files_by_operation = OperationFile::query_by_operations(
3111            operation_conn,
3112            &[operation_1.hash, operation_2.hash],
3113        )
3114        .map_err(|err| -> Box<dyn std::error::Error> { Box::new(err) })?;
3115
3116        let alpha = files_by_operation
3117            .get(&operation_1.hash)
3118            .ok_or_else(|| "missing first operation files".to_string())?;
3119        let beta = files_by_operation
3120            .get(&operation_2.hash)
3121            .ok_or_else(|| "missing second operation files".to_string())?;
3122
3123        assert_eq!(alpha[0].filename, "alpha.fa");
3124        assert!(alpha[0].file_path.ends_with(".fa"));
3125        assert_eq!(beta[0].filename, "beta.fa");
3126        assert!(beta[0].file_path.ends_with(".fa"));
3127        assert!(alpha[0].asset_uri.ends_with(".fa"));
3128        assert!(beta[0].asset_uri.ends_with(".fa"));
3129        assert_eq!(alpha[0].file_path, beta[0].file_path);
3130        assert_eq!(alpha[0].id, beta[0].id);
3131        assert_eq!(alpha[0].checksum, beta[0].checksum);
3132        Ok(())
3133    }
3134}