aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib.rs
blob: b858602dc29aacb1d59886ac264903f7aa19bf8b (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
pub mod sqlite;
pub mod yaml;


pub fn insert(
    dbconn: &mut rusqlite::Connection,
    table_name: &str,
    data: &mut [yaml_rust::Yaml],
) {
    let table_columns = crate::sqlite::get_column_names(&dbconn, table_name);

    for mut doc in data {
        let tx = dbconn.transaction().unwrap();

        crate::yaml::extract(&mut doc, &tx, &table_name, &table_columns);

        tx.commit().unwrap();
    }
}


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

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

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

        #[derive(Debug, PartialEq)]
        struct TestRecord {
            id: i8,
            count: i16,
            weight: f32,
            description: String,
        }

        let description = r#"This is a test.

    Another paragraph
    with a flowed line."#;

        let expected = TestRecord {
            id: 1,
            count: 99,
            weight: 3.14,
            description: r#"This is a test.
Another paragraph with a flowed line."#.to_owned(),
        };

        let yaml_str = format!(
r#"- description: >-
    {}
  count: {}
  weight: {}
"#,
            description,
            expected.count,
            expected.weight,
        );

        let mut data = yaml_rust::YamlLoader::load_from_str(&yaml_str).unwrap();

        insert(&mut conn, "test", &mut data);

        {
            let mut stmt = conn.prepare(r#"
                SELECT
                    id, count, weight, description
                FROM "test"
                LIMIT 1;
            "#).unwrap();

            let got = stmt.query_row(
                [],
                |row| {
                    Ok(
                        TestRecord {
                            id: row.get(0).unwrap(),
                            count: row.get(1).unwrap(),
                            weight: row.get(2).unwrap(),
                            description: row.get(3).unwrap(),
                        }
                    )
                }
            ).unwrap();

            assert_eq!(expected, got);
        }

        conn.close().unwrap();
    }

    #[test]
    fn ignores_yaml_fields_that_are_not_column_names() {
    }
}