aboutsummaryrefslogtreecommitdiffstats
path: root/src/yaml.rs
blob: af7177993701d4cefc5b3ad08ab7b494f9dbb93d (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
use rusqlite;
use yaml_rust::yaml;

use std::collections::HashSet;


mod sql;
mod write;

pub(crate) use sql::*;

pub use write::*;


// TODO: Separate functions to get a list of YAML hashes, and insert hashes into
// the database.
pub fn extract(
    doc: &mut yaml::Yaml,
    tx: &rusqlite::Transaction,
    table_name: &str,
    table_columns: &HashSet<String>,
) -> Result<(), crate::Error> {
    match doc {
        yaml::Yaml::Array(ref mut array) => {
            for yaml_value in array {
                extract(yaml_value, tx, table_name, table_columns)?;
            }
        }
        yaml::Yaml::Hash(ref mut hash) => {
            use std::borrow::Cow;

            let keys: Vec<yaml::Yaml> = hash.keys().map(|k| k.clone()).collect();
            let columns_as_yaml: Vec<yaml::Yaml> = table_columns.iter()
                .map(|c| yaml::Yaml::from_str(c))
                .collect();

            for key in keys.iter() {
                if !columns_as_yaml.contains(key) {
                    hash.remove(key);
                }
            }

            let mut stmt = tx.prepare(
                &format!(
                    r#"
                        INSERT INTO "{}"
                            ({})
                        VALUES
                            ({});
                    "#,
                    table_name,

                    // Wrap column names in quotes.
                    hash.keys()
                        .map(|k| k.as_str())
                        .filter(|k| k.is_some())

                        // Always `Some`.
                        .map(|k| format!(r#""{}""#, k.unwrap()))
                        .collect::<Vec<String>>()
                        .join(", "),
                    format!("{}?", "?, ".repeat(hash.len() - 1)),
                )
            )?;

            let values = hash.values().map(|v| Yaml(Cow::Borrowed(v)));
            stmt.insert(rusqlite::params_from_iter(values))?;
        }
        _ => {}
    }

    Ok(())
}