aboutsummaryrefslogtreecommitdiffstats
path: root/src/yaml.rs
blob: d1108f15b59ff97837ac27f7c1c8fe830c847f62 (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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// Copyright (c) 2022  Teddy Wing
//
// This file is part of Yaqlite.
//
// Yaqlite is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Yaqlite is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Yaqlite. If not, see <https://www.gnu.org/licenses/>.

use rusqlite;
use yaml_rust::yaml;

use std::collections::HashSet;


mod sql;
mod write;

pub(crate) use sql::*;

pub use write::*;


/// Insert a YAML document into the given table in the database.
pub fn db_insert(
    doc: &mut yaml::Yaml,
    tx: &rusqlite::Transaction,
    table_name: &str,
    table_columns: &HashSet<String>,
) -> Result<(), crate::Error> {
    with_hash(
        doc,
        &mut |hash| {
            use std::borrow::Cow;

            hash_filter_table_columns(hash, &table_columns);

            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(())
        }
    )
}

/// TODO
pub fn db_update(
    doc: &mut yaml::Yaml,
    tx: &rusqlite::Transaction,
    table_name: &str,
    table_columns: &HashSet<String>,
    primary_key_column: &str,
    record_id: &str,
) -> Result<(), crate::Error> {
    with_hash(
        doc,
        &mut |hash| {
            use std::borrow::Cow;

            hash_filter_table_columns(hash, &table_columns);

            let mut stmt = tx.prepare(
                &format!(
                    r#"
                        UPDATE "{}"
                        SET
                            {}
                        WHERE {} = ?;
                    "#,
                    table_name,

                    // List of:
                    //   "column_name" = ?,
                    //   "column_name" = ?
                    hash.keys()
                        .map(|k| k.as_str())
                        .filter(|k| k.is_some())

                        // Always `Some`.
                        .map(|k| format!(r#""{}" = ?"#, k.unwrap()))
                        .collect::<Vec<String>>()
                        .join(", "),

                    primary_key_column,
                ),
            )?;

            // TODO: convert to &[&dyn ToSql] ?
            // let values = hash.values().map(|v| Yaml(Cow::Borrowed(v)));
            // values.push(primary_key);
            // stmt.execute(rusqlite::params_from_iter(values))?;

            // let values: Vec<&dyn rusqlite::ToSql>;
            //
            // for v in hash.values() {
            //     values.push(&Yaml(Cow::Borrowed(v)));
            // }
            //
            // stmt.execute(values)?;

            // let values: dyn Iterator<Item = &dyn rusqlite::ToSql> = hash.values();
            // values = values.map(|v| Yaml(Cow::Borrowed(v)));
            // values.chain(&[&primary_key]);
            // stmt.execute(rusqlite::params_from_iter(values))?;

            let mut values: Vec<_> = hash.values()
                .map(|v| Yaml(Cow::Borrowed(v)))
                .map(|v| Box::new(v) as Box<dyn rusqlite::ToSql>)
                .collect();
            values.push(Box::new(record_id));
            stmt.execute(rusqlite::params_from_iter(values))?;

            Ok(())
        }
    )
}

/// Parse a YAML document and run a function for all hashes in the document.
fn with_hash<F>(
    doc: &mut yaml::Yaml,
    run: &mut F,
) -> Result<(), crate::Error>
where F: FnMut(&mut yaml::Hash) -> Result<(), crate::Error>
{
    match doc {
        yaml::Yaml::Array(ref mut array) => {
            for yaml_value in array {
                with_hash(yaml_value, run)?;
            }
        }
        yaml::Yaml::Hash(ref mut hash) => {
            run(hash)?;
        }
        _ => {}
    }

    Ok(())
}

/// Remove keys in `table_columns` from `hash`.
fn hash_filter_table_columns(
    hash: &mut yaml::Hash,
    table_columns: &HashSet<String>,
) {
    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);
        }
    }
}