aboutsummaryrefslogtreecommitdiffstats
path: root/src/sqlite.rs
blob: c274b630679385e524afd912f1d6489290811182 (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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use rusqlite;

use std::collections::HashMap;


#[derive(Debug)]
pub struct Zero;


pub fn get_column_names(
    dbconn: &rusqlite::Connection,
    table_name: &str,
// TODO: Use a HashSet instead
) -> Result<HashMap<String, Zero>, crate::Error> {
    let mut column_names = HashMap::new();

    let mut stmt = dbconn.prepare(
        &format!(
            r#"
                SELECT "name"
                FROM pragma_table_info("{}");
            "#,
            table_name,
        ),
    )?;

    let rows = stmt.query_map(
        [],
        |row| row.get(0),
    )?;

    for row_result in rows {
        let row = row_result?;

        column_names.insert(row, Zero{});
    }

    Ok(column_names)
}


/// Get the name of the given table's primary key.
pub fn table_primary_key_column(
    dbconn: &rusqlite::Connection,
    table_name: &str,
) -> Result<String, crate::Error> {
    let mut stmt = dbconn.prepare(r#"
        SELECT "name"
        FROM pragma_table_info(:table)
        WHERE "pk" != 0;'
    "#)?;

    let pk_column: String = stmt.query_row(
        &[(":table", table_name)],
        |row| row.get(0),
    )?;

    Ok(pk_column)
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn table_primary_key_column_gets_primary_key_name() {
        let conn = rusqlite::Connection::open_in_memory().unwrap();

        conn.execute(
            r#"
                CREATE TABLE "test" (
                    id INTEGER PRIMARY KEY,
                    count INTEGER
                );
            "#,
            []
        ).unwrap();

        let column_name = table_primary_key_column(&conn, "test").unwrap();

        assert_eq!("id", column_name);

        conn.close().unwrap();
    }
}