summaryrefslogtreecommitdiffstats
path: root/src/bin/client/database.rs
blob: bc8f6f8339ddccdce0508f5368ba4ef4c57ea05b (plain) (blame)
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
use rusqlite::Connection;

pub fn init_db() -> Connection {
    let conn = Connection::open("client.db").unwrap();
    conn.execute(
        "CREATE TABLE IF NOT EXISTS hosts (
            host TEXT PRIMARY KEY,
            last_used DATETIME DEFAULT CURRENT_TIMESTAMP
        )",
        [],
    ).unwrap();
    conn
}

pub fn get_last_host(conn: &Connection) -> Option<String> {
    let mut stmt = conn.prepare("SELECT host FROM hosts ORDER BY last_used DESC LIMIT 1").unwrap();
    let mut rows = stmt.query([]).unwrap();
    if let Ok(Some(row)) = rows.next() {
        row.get(0).ok()
    } else {
        None
    }
}

pub fn save_host(conn: &Connection, host: &str) {
    conn.execute(
        "INSERT OR REPLACE INTO hosts (host, last_used) VALUES (?1, CURRENT_TIMESTAMP)",
        [host],
    ).unwrap();
}