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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
use command::{Command, Query};
use command::Command::Load;
use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;
use std::convert::AsRef;
use self::InputType::{Json, ExtInputType};
use util;
use queryable::LoadValues;
use command_query::CommandQuery;
use command_line::CommandLine;
use queryable::Queryable;
use queryable::PostQueryable;
use commandable::Commandable;
use commandable::PostCommandable;
use commandable::DataValues;
use request_cancellable::RequestCancellable;
use request_timeoutable::RequestTimeoutable;

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct LoadCommand {
    command: Command,
    arguments: HashMap<String, String>,
    table: String,
    values: LoadValues,
}

#[derive (Debug)]
pub enum InputTypeError {
    Empty,
}

#[derive (Clone, PartialEq, Eq, Debug)]
pub enum InputType {
    Json,
    /// For future extensibility.
    ExtInputType(String),
}

impl AsRef<str> for InputType {
    fn as_ref(&self) -> &str {
        match *self {
            Json => "json",
            ExtInputType(ref s) => s.as_ref(),
        }
    }
}

impl fmt::Display for InputType {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write_str(match *self {
            Json => "json",
            ExtInputType(ref s) => s.as_ref(),
        })
    }
}

impl FromStr for InputType {
    type Err = InputTypeError;
    fn from_str(s: &str) -> Result<InputType, InputTypeError> {
        if s == "" {
            Err(InputTypeError::Empty)
        } else {
            Ok(match s {
                "json" => Json,
                _ => ExtInputType(s.to_owned()),
            })
        }
    }
}

impl Default for LoadCommand {
    fn default() -> LoadCommand {
        LoadCommand {
            command: Load,
            table: "".to_string(),
            arguments: HashMap::new(),
            values: "".to_string(),
        }
    }
}

impl LoadCommand {
    pub fn new(table: String, data: String) -> LoadCommand {
        LoadCommand {
            table: table,
            values: data,
            ..LoadCommand::default()
        }
    }

    pub fn columns(mut self, columns: Vec<String>) -> LoadCommand {
        let string = util::split_values_vec(columns);
        self.arguments.insert("columns".to_string(), string.to_owned());
        self
    }

    pub fn input_type(mut self, input_type: InputType) -> LoadCommand {
        let input_type_str = format!("{}", input_type);
        self.arguments.insert("input_type".to_string(), input_type_str.to_owned());
        self
    }

    pub fn build(self) -> (Command, Query, LoadValues) {
        let mut query: Query = vec![("table".to_string(), self.table)];
        for (key, value) in &self.arguments {
            query.push((key.to_owned(), value.to_owned()));
        }
        let values = self.values.to_owned();
        (Load, query, values)
    }
}

impl Queryable for LoadCommand {
    fn to_query(self) -> String {
        let (command, query, values) = self.build();
        let mut command = CommandQuery::new(command, query);
        format!("{}&values={}", command.encode(), values)
    }
}

impl PostQueryable for LoadCommand {
    fn to_post_query(self) -> (String, LoadValues) {
        let (command, query, values) = self.build();
        let mut command = CommandQuery::new(command, query);
        (command.encode(), values)
    }
}

impl Commandable for LoadCommand {
    fn to_command(self) -> String {
        let (command, query, values) = self.build();
        let mut command = CommandLine::new(command, query);
        format!("{}\n{}", command.encode(), values)
    }
}

impl PostCommandable for LoadCommand {
    fn to_post_command(self) -> (String, DataValues) {
        let (command, query, values) = self.build();
        let mut command = CommandLine::new(command, query);
        (command.encode(), values)
    }
}

request_cancellable!(LoadCommand);
request_timeoutable!(LoadCommand);

#[cfg(test)]
mod test {
    use super::*;
    use command::Query;
    use command::Command::Load;
    use std::collections::HashMap;
    use std::str::FromStr;
    use queryable::Queryable;
    use queryable::PostQueryable;
    use commandable::Commandable;
    use commandable::PostCommandable;

    #[test]
    fn test_from_str() {
        assert_eq!(InputType::Json, FromStr::from_str("json").unwrap());
        assert_eq!(InputType::ExtInputType("added-type".to_owned()),
                   FromStr::from_str("added-type").unwrap());
        let x: Result<InputType, _> = FromStr::from_str("");
        if let Err(InputTypeError::Empty) = x {
        } else {
            panic!("An empty input type is invalid!")
        }
    }

    #[test]
    fn test_fmt() {
        assert_eq!("json".to_owned(), format!("{}", InputType::Json));
        assert_eq!("added-type".to_owned(),
                   format!("{}", InputType::ExtInputType("added-type".to_owned())));
    }

    #[test]
    fn test_as_str() {
        assert_eq!(InputType::Json.as_ref(), "json");
        assert_eq!(InputType::ExtInputType("added-type".to_owned()).as_ref(),
                   "added-type");
    }

    const DATA: &'static str = r#"[
{"_key":"http://example.org/","title":"This is test record 1!"},
]"#;

    #[test]
    fn test_new() {
        let vanilla_load = LoadCommand::new("test".to_string(), DATA.to_string());
        let expected = LoadCommand {
            command: Load,
            table: "test".to_string(),
            arguments: HashMap::new(),
            values: DATA.to_string(),
        };
        assert_eq!(expected, vanilla_load);
    }

    #[test]
    fn test_columns() {
        let load = LoadCommand::new("test".to_string(), DATA.to_string())
            .columns(vec!["_key".to_string(), "title".to_string()]);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("columns".to_string(), "_key,title".to_string());
        let expected = LoadCommand {
            command: Load,
            table: "test".to_string(),
            arguments: arg,
            values: DATA.to_string(),
        };
        assert_eq!(expected, load);
    }

    #[test]
    fn test_input_type() {
        let load = LoadCommand::new("test".to_string(), DATA.to_string())
            .input_type(InputType::Json);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("input_type".to_string(), "json".to_string());
        let expected = LoadCommand {
            command: Load,
            table: "test".to_string(),
            arguments: arg,
            values: DATA.to_string(),
        };
        assert_eq!(expected, load);
    }

    #[test]
    fn test_build() {
        let load = LoadCommand::new("test".to_string(), DATA.to_string())
            .columns(vec!["_key".to_string(), "title".to_string()])
            .build();
        let expected_query: Query = vec![("table".to_string(), "test".to_string()),
                                         ("columns".to_string(), "_key,title".to_string())];
        let expected = (Load, expected_query, DATA.to_string());
        assert_eq!(expected, load);
    }

    #[test]
    fn test_queryable() {
        let load_data: &'static str = r#"[
{"_key":"http://example.org/","title":"This is test record 1!"},
]"#;
        let query = LoadCommand::new("test".to_string(), load_data.to_string())
            .input_type(InputType::Json)
            .to_query();
        let url_encoded = "/d/load?table=test&input_type=json&values=[\n{\"_key\":\"http:\
                           //example.org/\",\"title\":\"This is test record 1!\"},\n]";
        assert_eq!(url_encoded.to_string(), query);
    }

    #[test]
    fn test_post_queryable() {
        let load_data: &'static str = r#"[
{"_key":"http://example.org/","title":"This is test record 1!"},
]"#;
        let (query, values) = LoadCommand::new("test".to_string(), load_data.to_string())
            .input_type(InputType::Json)
            .to_post_query();
        let url_encoded = "/d/load?table=test&input_type=json";
        assert_eq!(url_encoded.to_string(), query);
        assert_eq!(load_data.to_string(), values);
    }

    #[test]
    fn test_commandable() {
        let load_data: &'static str = r#"[
{"_key":"http://example.org/","title":"This is test record 1!"},
]"#;
        let query = LoadCommand::new("test".to_string(), load_data.to_string())
            .input_type(InputType::Json)
            .to_command();
        let cli_encoded = "load --table test --input_type \
                           json\n[\n{\"_key\":\"http://example.org/\",\"title\":\"This is test \
                           record 1!\"},\n]";
        assert_eq!(cli_encoded.to_string(), query);
    }

    #[test]
    fn test_post_commandable() {
        let load_data: &'static str = r#"[
{"_key":"http://example.org/","title":"This is test record 1!"},
]"#;
        let (query, values) = LoadCommand::new("test".to_string(), load_data.to_string())
            .input_type(InputType::Json)
            .to_post_command();
        let cli_encoded = "load --table test --input_type json";
        assert_eq!(cli_encoded.to_string(), query);
        assert_eq!(load_data.to_string(), values);
    }
}