granger 0.1.0

An opinionated Kanban Board for the solo developer
Documentation
use rusqlite::{Connection, Result};
use std::fs;
use std::fs::OpenOptions;
use std::path::PathBuf;

use crate::Env;

pub fn get_granger_data_directory() -> PathBuf {
    let granger_data_directory = dirs::data_dir()
        .expect("Failed to find granger data directory.")
        .join("granger");

    fs::create_dir(&granger_data_directory).ok();

    granger_data_directory
}

pub fn get_path_to_db(env: Env) -> PathBuf {
    let granger_db_directory = get_granger_data_directory();

    let database_for_env: PathBuf = match env {
        Env::Test => granger_db_directory.join("granger-test.db"),
        Env::Prod => granger_db_directory.join("granger.db"),
    };

    OpenOptions::new()
        .create(true)
        .read(true)
        .write(true)
        .open(&database_for_env)
        .expect("Failed to find granger.sql file.");

    database_for_env
}

pub fn get_test_connection() -> Result<Connection, rusqlite::Error> {
    let connection = Connection::open(get_path_to_db(Env::Test))?;

    connection.pragma_update(None, "foreign_keys", true)?;

    Ok(connection)
}

pub fn get_connection() -> Result<Connection, rusqlite::Error> {
    let connection = Connection::open(get_path_to_db(Env::Prod))?;

    connection.pragma_update(None, "foreign_keys", true)?;

    Ok(connection)
}

pub fn initialize(env: Env) -> Result<()> {
    let connection: Connection = match env {
        Env::Test => get_test_connection()?,
        Env::Prod => get_connection()?,
    };

    connection.execute(
        "CREATE TABLE IF NOT EXISTS board (
            id              INTEGER PRIMARY KEY,
            name            TEXT NOT NULL,
            location        TEXT NOT NULL UNIQUE,
            ticket_count    INTEGER DEFAULT 0 NOT NULL
        )",
        [],
    )?;

    connection.execute(
        "CREATE TABLE IF NOT EXISTS ticket (
            id          INTEGER PRIMARY KEY,
            board_id    INTEGER NOT NULL,
            number      INTEGER NOT NULL,
            title       TEXT NOT NULL,
            description TEXT NOT NULL,
            state       TEXT NOT NULL,
            blocked_by  INTEGER,
            FOREIGN KEY (board_id) REFERENCES board (id)
        )",
        [],
    )?;

    Ok(())
}