Skip to main content

post_archiver/importer/
tag.rs

1use std::hash::Hash;
2
3use rusqlite::params;
4
5use crate::{
6    error::Result,
7    manager::{PostArchiverConnection, PostArchiverManager},
8    PlatformId, TagId,
9};
10
11impl<T> PostArchiverManager<T>
12where
13    T: PostArchiverConnection,
14{
15    /// Import a tag into the archive.
16    ///
17    /// If the tag already exists, it returns the existing ID.
18    ///
19    /// # Errors
20    ///
21    /// Returns `Error` if there was an error accessing the database.
22    pub fn import_tag(&self, tag: UnsyncTag) -> Result<TagId> {
23        // find
24        if let Some(id) = self.find_tag(&tag.name, tag.platform)? {
25            return Ok(id);
26        }
27
28        // insert
29        let mut ins_stmt = self
30            .conn()
31            .prepare_cached("INSERT INTO tags (name, platform) VALUES (?, ?) RETURNING id")?;
32        Ok(ins_stmt.query_row(params![tag.name, tag.platform], |row| row.get(0))?)
33    }
34
35    /// Import multiple tags into the archive.
36    ///
37    /// If a tag already exists, it returns the existing ID.
38    ///
39    /// # Errors
40    ///
41    /// Returns `Error` if there was an error accessing the database.
42    pub fn import_tags(&self, tags: impl IntoIterator<Item = UnsyncTag>) -> Result<Vec<TagId>> {
43        tags.into_iter()
44            .map(|tag| self.import_tag(tag))
45            .collect::<Result<Vec<TagId>>>()
46    }
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Hash)]
50pub struct UnsyncTag {
51    pub name: String,
52    pub platform: Option<PlatformId>,
53}