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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
use crate::document::TypedCouchDocument;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{
    collections::HashMap,
    fmt::{Display, Formatter},
};

/// Sort direction abstraction
#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone)]
pub enum SortDirection {
    #[serde(rename = "desc")]
    Desc,
    #[serde(rename = "asc")]
    Asc,
}

impl From<String> for SortDirection {
    fn from(original: String) -> SortDirection {
        match original.as_ref() {
            "desc" => SortDirection::Desc,
            _ => SortDirection::Asc,
        }
    }
}

/// Sort spec content abstraction
pub type SortSpecContent = HashMap<String, SortDirection>;

/// Sort spec abstraction
#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone)]
#[serde(untagged)]
pub enum SortSpec {
    Simple(String),
    Complex(SortSpecContent),
}

/// Index spec abstraction
#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone)]
#[serde(untagged)]
pub enum IndexSpec {
    DesignDocument(String),
    IndexName((String, String)),
}

/// Find query abstraction
/// Parameters here [/db/_find](https://docs.couchdb.org/en/latest/api/database/find.html)
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct FindQuery {
    pub selector: Value,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub skip: Option<u64>,

    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub sort: Vec<SortSpec>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub fields: Option<Vec<String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub use_index: Option<IndexSpec>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub r: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub bookmark: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub update: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub stable: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub stale: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_stats: Option<bool>,
}

/// Find result abstraction
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
#[serde(bound(deserialize = "T: TypedCouchDocument"))]
pub struct FindResult<T: TypedCouchDocument> {
    pub docs: Option<Vec<T>>,
    pub warning: Option<String>,
    pub error: Option<String>,
    pub reason: Option<String>,
    pub bookmark: Option<String>,
}

//todo: include status on structs

/// Explain result abstraction
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct ExplainResult {
    pub dbname: String,
    pub index: IndexSpec,
    pub selector: Value,
    pub opts: Value,
    pub limit: u32,
    pub skip: u64,
    pub fields: Vec<String>,
    pub range: Value,
}

/// $ne operation
#[derive(Serialize, Deserialize)]
pub struct NotEqual {
    #[serde(rename = "$ne")]
    pub ne: Option<String>,
}

/// Select all Selector
#[derive(Serialize, Deserialize)]
pub struct SelectAll {
    #[serde(rename = "_id")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<NotEqual>,
}

/// Little helper to create a select all query.
impl Default for SelectAll {
    fn default() -> Self {
        SelectAll {
            id: Some(NotEqual { ne: None }),
        }
    }
}

impl SelectAll {
    #[must_use]
    pub fn as_value(&self) -> Value {
        self.into()
    }
}

impl From<&SelectAll> for serde_json::Value {
    fn from(s: &SelectAll) -> Self {
        serde_json::to_value(s).expect("can not convert into json")
    }
}

impl From<serde_json::Value> for SelectAll {
    fn from(value: Value) -> Self {
        serde_json::from_value(value).expect("json Value is not a valid Selector")
    }
}

/// Returns all documents
#[macro_export]
macro_rules! find_all_selector {
    () => {
        FindQuery::find_all().as_value()
    };
}

/// Find query. You can use the builder paradigm to construct these parameters easily:
/// ```
/// use couch_rs::types::find::FindQuery;
/// let _query = FindQuery::find_all().skip(10).limit(10);
/// ```
impl FindQuery {
    #[must_use]
    pub fn new_from_value(query: Value) -> Self {
        query.into()
    }

    // Create a new FindQuery from a valid selector. The selector syntax is documented here:
    // https://docs.couchdb.org/en/latest/api/database/find.html#find-selectors
    #[must_use]
    pub fn new(selector: Value) -> Self {
        FindQuery {
            selector,
            limit: None,
            skip: None,
            sort: vec![],
            fields: None,
            use_index: None,
            r: None,
            bookmark: None,
            update: None,
            stable: None,
            stale: None,
            execution_stats: None,
        }
    }

    #[must_use]
    pub fn find_all() -> Self {
        Self::new(SelectAll::default().as_value())
    }

    #[must_use]
    pub fn as_value(&self) -> Value {
        self.into()
    }

    #[must_use]
    pub fn limit(mut self, limit: u64) -> Self {
        self.limit = Some(limit);
        self
    }

    #[must_use]
    pub fn skip(mut self, skip: u64) -> Self {
        self.skip = Some(skip);
        self
    }

    #[must_use]
    pub fn sort(mut self, sort: Vec<SortSpec>) -> Self {
        self.sort = sort;
        self
    }

    #[must_use]
    pub fn fields(mut self, fields: Vec<String>) -> Self {
        self.fields = Some(fields);
        self
    }

    #[must_use]
    pub fn use_index(mut self, use_index: IndexSpec) -> Self {
        self.use_index = Some(use_index);
        self
    }

    #[must_use]
    pub fn r(mut self, r: i32) -> Self {
        self.r = Some(r);
        self
    }

    #[must_use]
    pub fn bookmark(mut self, bookmark: &str) -> Self {
        self.bookmark = Some(bookmark.to_string());
        self
    }

    #[must_use]
    pub fn update(mut self, update: bool) -> Self {
        self.update = Some(update);
        self
    }

    #[must_use]
    pub fn stable(mut self, stable: bool) -> Self {
        self.stable = Some(stable);
        self
    }

    #[must_use]
    pub fn stale(mut self, stale: &str) -> Self {
        self.stale = Some(stale.to_string());
        self
    }

    #[must_use]
    pub fn execution_stats(mut self, execution_stats: bool) -> Self {
        self.execution_stats = Some(execution_stats);
        self
    }
}

impl From<FindQuery> for serde_json::Value {
    fn from(q: FindQuery) -> Self {
        serde_json::to_value(q).expect("can not convert into json")
    }
}

impl From<&FindQuery> for serde_json::Value {
    fn from(q: &FindQuery) -> Self {
        serde_json::to_value(q).expect("can not convert into json")
    }
}

impl From<serde_json::Value> for FindQuery {
    fn from(value: Value) -> Self {
        serde_json::from_value(value).expect("json Value is not a valid FindQuery")
    }
}

impl Display for FindQuery {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let json: Value = self.into();
        f.write_str(&json.to_string())
    }
}

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

    #[test]
    fn test_convert_to_value() {
        let mut sort = HashMap::new();
        sort.insert("first_name".to_string(), SortDirection::Desc);

        let mut query = FindQuery::find_all();
        query.limit = Some(10);
        query.skip = Some(20);
        query.sort = vec![SortSpec::Complex(sort)];
        let json = query.to_string();
        assert_eq!(
            r#"{"limit":10,"selector":{"_id":{"$ne":null}},"skip":20,"sort":[{"first_name":"desc"}]}"#,
            json
        );
    }

    #[test]
    fn test_default_select_all() {
        let selector = FindQuery::find_all().as_value().to_string();
        assert_eq!(selector, r#"{"selector":{"_id":{"$ne":null}}}"#);
    }

    #[test]
    fn test_from_json() {
        let query = FindQuery::new_from_value(json!({
            "selector": {
                "thing": true
            },
            "limit": 1,
            "sort": [{
                "thing": "desc"
            }]
        }));

        let selector = query.selector.to_string();
        assert_eq!(selector, r#"{"thing":true}"#);
        assert_eq!(query.limit, Some(1));
        assert_eq!(query.sort.len(), 1);
        let first_sort = query.sort.first().unwrap();
        if let SortSpec::Complex(spec) = first_sort {
            assert!(spec.contains_key("thing"));
            let direction = spec.get("thing").unwrap();
            assert_eq!(direction, &SortDirection::Desc);
        } else {
            panic!("unexpected sort spec");
        }
    }
}