aboutsummaryrefslogtreecommitdiff
path: root/src/db.rs
blob: c67e39e4f7fd4d33e939c1e13b8cb4cbdc860f57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// extern
use anyhow::Result;
use log::{debug, info};
use rusqlite::{Connection, OpenFlags, NO_PARAMS};

// std
use std::fmt;
use std::path::Path;

pub fn open_connection<P>(p: P) -> Result<Connection>
where
    P: AsRef<Path> + fmt::Display,
{
    info!("Opened connection to database");
    Ok(Connection::open_with_flags(
        &p,
        OpenFlags::SQLITE_OPEN_CREATE | OpenFlags::SQLITE_OPEN_READ_WRITE,
    )?)
}

pub fn init_db<P: AsRef<Path> + fmt::Display>(p: P) -> Result<()> {
    debug!("Looking for database at `{}`", p);
    let conn = open_connection(&p)?;
    conn.execute(
        "CREATE TABLE IF NOT EXISTS urls (
            link TEXT PRIMARY KEY,
            shortlink TEXT NOT NULL
        )",
        NO_PARAMS,
    )?;
    info!("SQLite3 database `{}` initialized", &p);
    Ok(())
}