Skip to main content

selene_core/library/collection/
trait_impls.rs

1use std::convert::Infallible;
2
3use lunar_lib::database::{
4    CompareAndSwapTransaction, CustomTransactionError, DatabaseEntry, DatabaseError,
5    TransactionError, Tree,
6};
7
8use crate::{
9    database::{Createable, LibraryDb, collection_tree},
10    library::collection::{Collection, CollectionId},
11};
12
13impl DatabaseEntry for Collection {
14    type Id = CollectionId;
15    type EntryDb = LibraryDb;
16
17    const VERSION_NUMBER: u32 = 1;
18
19    fn tree(db: &Self::EntryDb) -> Tree {
20        collection_tree(db)
21    }
22
23    fn id(&self) -> Self::Id {
24        self.id
25    }
26
27    fn read_only(&self) -> bool {
28        self.read_only
29    }
30}
31
32#[derive(Debug, Clone)]
33pub struct CollectionCreateArgs {
34    name: String,
35}
36
37impl Createable for Collection {
38    type CreateArgs = CollectionCreateArgs;
39    type Err = Infallible;
40
41    fn tx_create(
42        cas_tx: &mut CompareAndSwapTransaction<Self::EntryDb>,
43        args: Self::CreateArgs,
44    ) -> Result<Self, CustomTransactionError<Self::Err>> {
45        let collection = Collection::new_static(args.name).map_err(|err| {
46            TransactionError::Database(DatabaseError::InvalidInput(err.to_string()))
47        })?;
48
49        if cas_tx.tx_get(collection.id())?.is_some() {
50            return Err(TransactionError::Database(DatabaseError::AlreadyInDatabase).into());
51        }
52
53        Ok(collection)
54    }
55}