aboutsummaryrefslogtreecommitdiffstats
path: root/src/select.rs
blob: fb1b9774f22729a0f0622f8b46711545441beb73 (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
pub fn select<C>(
    dbconn: &rusqlite::Connection,
    table_name: &str,
    record_id: &str,
    exclude_columns: &[C],
) -> Result<yaml_rust::Yaml, crate::Error>
where C: AsRef<str> + PartialEq<String>
{
    select_by_column(
        dbconn,
        table_name,
        &crate::sqlite::table_primary_key_column(dbconn, table_name)?,
        record_id,
        exclude_columns,
    )
}

pub fn select_by_column<C>(
    dbconn: &rusqlite::Connection,
    table_name: &str,
    primary_key_column: &str,
    record_id: &str,
    exclude_columns: &[C],
) -> Result<yaml_rust::Yaml, crate::Error>
where C: AsRef<str> + PartialEq<String>
{
    use crate::yaml::Yaml;

    let mut stmt = dbconn.prepare(
        &format!(
            r#"
                SELECT
                    *
                FROM "{}"
                WHERE "{}" = :pk;
            "#,
            table_name,
            primary_key_column,
        ),
    )?;

    let column_names: Vec<String> = stmt
        .column_names()
        .into_iter()
        .map(String::from)
        .collect();

    let rows = stmt.query_map(
        rusqlite::named_params! {
            ":pk": record_id,
        },
        |row| {
            let mut data = yaml_rust::yaml::Hash::new();

            for (i, column) in column_names.iter().enumerate() {
                // Don't include excluded columns in the resulting hash.
                if exclude_columns.iter().any(|c| c == column) {
                    continue
                }

                let column_name = column.to_owned();
                let column_value: Yaml = row.get(i)?;

                data.insert(
                    yaml_rust::Yaml::String(column_name),
                    column_value.into_inner(),
                );
            }

            Ok(data)
        },
    )?;

    // Only one record is expected.
    let mut records = yaml_rust::yaml::Array::with_capacity(1);

    for row_result in rows {
        records.push(yaml_rust::Yaml::Hash(row_result?));
    }

    match records.len() {
        0 => Ok(yaml_rust::Yaml::Null),
        1 => Ok(records.swap_remove(0)),
        _ => Ok(yaml_rust::Yaml::Array(records)),
    }
}


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

    #[test]
    fn select_extracts_a_database_record_as_yaml() {
        struct TestRecord {
            count: i16,
            description: String,
        }

        let record = TestRecord {
            count: 99,
            description: "This is a test.

With multiple paragraphs.".to_owned(),
        };

        let mut yaml_hash = yaml_rust::yaml::Hash::new();
        yaml_hash.insert(
            yaml_rust::Yaml::String("count".to_owned()),
            yaml_rust::Yaml::Integer(record.count.into()),
        );
        yaml_hash.insert(
            yaml_rust::Yaml::String("description".to_owned()),
            yaml_rust::Yaml::String(record.description.clone()),
        );

        let expected = yaml_rust::Yaml::Hash(yaml_hash);

        let conn = rusqlite::Connection::open_in_memory().unwrap();

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

        {
            let mut stmt = conn.prepare(r#"
                INSERT INTO "test"
                    (count, description)
                VALUES
                    (?, ?);
            "#).unwrap();

            stmt.insert(
                rusqlite::params![record.count, record.description],
            ).unwrap();

            let got = select(&conn, "test", "1").unwrap();

            assert_eq!(expected, got);
        }

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