tcup 0.1.2

The one and only teacup client!
Documentation
use rusqlite::{Connection, Result};

use crate::{
    config::{self, Config},
    errors::TeacupError,
};

// Map general db errors to our teacup type
//
impl From<rusqlite::Error> for TeacupError {
    fn from(err: rusqlite::Error) -> Self {
        TeacupError::DatabaseError(err.to_string())
    }
}

#[derive(Debug)]
pub struct Repo {
    pub location: String,
}

pub fn setup(config: &Config) -> Result<(), TeacupError> {
    // Create the Repos table
    //
    config.connection.execute(
        "
            CREATE TABLE IF NOT EXISTS repos
            ( location TEXT NOT NULL PRIMARY KEY 
            )
            ",
        (),
    )?;
    Ok(())
}

pub fn add(config: &Config, repo: &Repo) -> Result<(), TeacupError> {
    config.connection.execute(
        "
        INSERT INTO repos (location) VALUES (?1)
        ON CONFLICT(location) DO NOTHING
        ",
        (&repo.location,),
    )?;
    Ok(())
}

pub fn rm(config: &Config, repo: &Repo) -> Result<(), TeacupError> {
    config.connection.execute(
        "
        DELETE FROM repos WHERE location = ?1
        ",
        (&repo.location,),
    )?;
    Ok(())
}

pub fn list(config: &Config) -> Result<Vec<Repo>, TeacupError> {
    let mut statement = config.connection.prepare(
        "
        SELECT location FROM repos
        ",
    )?;
    Ok(statement
        .query_map([], |row| {
            Ok(Repo {
                location: row.get(0)?,
            })
        })?
        .collect::<Result<_, _>>()?)
}