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