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
use super::{
    btreemap, ArangoConnection, ArangoQuery, ArangoResponse, Collection, CollectionType,
    CursorExtractor, GetAll, GetByKey, GetByKeys, Insert, Remove, Replace, Truncate, Update,
};
use core::future::Future;
use futures_util::future::TryFutureExt;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::value::Value;
use std::collections::BTreeMap;

#[allow(dead_code)]
impl ArangoQuery {
    #[must_use]
    pub(crate) fn new(query: &str) -> Self {
        Self { query: String::from(query), ..Self::default() }
    }

    #[must_use]
    /// Same as raw, but with &str
    pub fn with_bind_vars(query: &str, bind_vars: BTreeMap<String, Value>) -> Self {
        Self { query: String::from(query), bind_vars, ..Self::default() }
    }

    #[must_use]
    /// ```ignore
    /// let mut bind_vars = std::collections::BTreeMap::new();
    /// bind_vars.insert(
    ///     "@conactcoll".to_owned(),
    ///     serde_json::Value::String(conactcoll.clone()),
    /// );
    /// bind_vars.insert("email".to_owned(), serde_json::Value::String("aaa@bbb.ccc"));
    /// let raw_query = "FOR c IN @@conactcoll FOR b IN @@balancecoll FILTER c.email == @email RETURN b";
    /// let query = ArangoQuery::raw(raw_query.to_owned(), bind_vars);
    /// match query.try_exec::<CreditBalance>(&conn).await {
    ///    Ok(ar) => ar.result,
    ///    Err(_) => vec![],
    ///}
    /// ```
    pub fn raw(query: String, bind_vars: BTreeMap<String, Value>) -> Self {
        ArangoQuery { query, bind_vars, ..Self::default() }
    }

    #[must_use]
    /// Returns results in batches of size `batch_size`
    /// ```ignore
    /// let query = ArangoQuery::raw_batched(raw_query.to_owned(), bind_vars, 100);
    /// ```
    pub fn raw_batched(
        query: String,
        bind_vars: BTreeMap<String, Value>,
        batch_size: usize,
    ) -> Self {
        ArangoQuery { query, bind_vars, batch_size: Some(batch_size) }
    }

    #[must_use]
    /// Converts an existing query to `batched` of size `batch_size`
    pub fn into_batched(self, batch_size: usize) -> Self {
        Self { query: self.query, bind_vars: self.bind_vars, batch_size: Some(batch_size) }
    }

    /// Executes this query using the provided `ArangoConnection`.
    /// Returns `ArangoResponse`
    /// # Errors
    ///
    /// Returns `reqwest::Error`
    /// Note: `reqwest::Error` is temporarily exposed and may change in the future.
    pub fn try_exec<T: Serialize + DeserializeOwned>(
        &self,
        dbc: &ArangoConnection,
    ) -> impl Future<Output = Result<ArangoResponse<T>, reqwest::Error>> {
        let nm = format!("{:?}", self);
        dbc.client
            .post(dbc.cursor().as_str())
            .header("content-type", "application/json")
            .json(self)
            .basic_auth(
                // TODO add this to ArangoConnection as well
                std::env::var("ARANGO_USER_NAME").unwrap_or_default(),
                std::env::var("ARANGO_PASSWORD").ok(),
            )
            .send()
            .and_then(reqwest::Response::json)
            .map_err(move |err| {
                log::debug!("Error during db request: {} Query: {:?}", err, nm);
                err
            })
    }
}

impl CursorExtractor {
    /// TODO: document this
    pub fn next<T: Serialize + DeserializeOwned>(
        &self,
        dbc: &ArangoConnection,
    ) -> impl Future<Output = Result<ArangoResponse<T>, reqwest::Error>> {
        let nm = format!("{:?}", self);
        dbc.client
            .put(&format!["{}/{}", dbc.cursor().as_str(), self.0])
            .basic_auth(
                // TODO add this to ArangoConnection as well
                std::env::var("ARANGO_USER_NAME").unwrap_or_default(),
                std::env::var("ARANGO_PASSWORD").ok(),
            )
            .send()
            .and_then(reqwest::Response::json)
            .map_err(move |err| {
                log::debug!("Error during db request: {} Query: {:?}", err, nm);
                err
            })
    }
}

impl Collection {
    #[must_use]
    /// ```ignore
    /// let coll = Collection::new(coll.as_str(), CollectionType::Document);
    /// ```
    pub fn new(name: &str, collection_type: CollectionType) -> Self {
        Self {
            id: String::new(),
            status: 0,
            is_system: false,
            globally_unique_id: String::from(name),
            name: String::from(name),
            collection_type,
        }
    }
}

impl Insert for Collection {
    /// ```ignore
    /// let query = coll.insert(&data);
    /// ```
    fn insert<Elem: Serialize>(&self, elem: &Elem) -> ArangoQuery {
        ArangoQuery::with_bind_vars(
            "INSERT @value INTO @@collection RETURN NEW",
            btreemap![
                String::from("@collection") => Value::String(self.name.to_owned()),
                String::from("value") => serde_json::to_value(elem).unwrap(),
            ],
        )
    }
}

impl GetAll for Collection {
    /// ```ignore
    /// let query = coll.get_all();
    /// ```
    fn get_all(&self) -> ArangoQuery {
        ArangoQuery::with_bind_vars(
            "FOR item in @@collection RETURN item",
            btreemap![String::from("@collection") => Value::String(self.name.to_owned())],
        )
    }
}

impl GetByKey for Collection {
    /// ```ignore
    /// let query = coll.get_by_key(key);
    /// ```
    fn get_by_key<Key: Serialize>(&self, key: Key) -> ArangoQuery {
        ArangoQuery::with_bind_vars(
            "RETURN DOCUMENT(@@collection, @key)",
            btreemap![
                String::from("@collection") => Value::String(self.name.to_owned()),
                String::from("key") => serde_json::to_value(&key).unwrap()
            ],
        )
    }
}

impl GetByKeys for Collection {
    /// ```ignore
    /// let query = coll.get_by_keys(&["key1","key2"]);
    /// ```
    fn get_by_keys<Key: Serialize>(&self, keys: &[Key]) -> ArangoQuery {
        ArangoQuery::with_bind_vars(
            "RETURN DOCUMENT(@@collection, @keys)",
            btreemap![
                String::from("@collection") => Value::String(self.name.to_owned()),
                String::from("keys") => serde_json::to_value(&keys).unwrap()
            ],
        )
    }
}

impl Replace for Collection {
    /// ```ignore
    /// let query = coll.replace("Paul", &TestUser::new("John Lennon"));
    /// ```
    fn replace<Key: Serialize, Elem: Serialize>(&self, key: Key, elem: Elem) -> ArangoQuery {
        ArangoQuery::with_bind_vars(
            "REPLACE @key WITH @elem IN @@collection RETURN NEW",
            btreemap![
                String::from("@collection") => Value::String(self.name.to_owned()),
                String::from("elem") => serde_json::to_value(&elem).unwrap(),
                String::from("key") => serde_json::to_value(&key).unwrap(),
            ],
        )
    }

    /// ```ignore
    /// let query = coll.replace_with_id("Paul", &Instrument { instrument: String::from("bass") });
    /// ```
    fn replace_with_id<Id: Serialize, Replace: Serialize>(
        &self,
        id: Id,
        replace: Replace,
    ) -> ArangoQuery {
        ArangoQuery::with_bind_vars(
            "LET doc = DOCUMENT(@id) REPLACE doc WITH @replace IN @@collection RETURN NEW",
            btreemap![
                String::from("@collection") => Value::String(self.name.to_owned()),
                String::from("id") => serde_json::to_value(&id).unwrap(),
                String::from("replace") => serde_json::to_value(&replace).unwrap(),
            ],
        )
    }
}

impl Update for Collection {
    /// ```ignore
    /// let query = coll.update("Paul", &Instrument { instrument: String::from("bass") });
    /// ```
    fn update<Key: Serialize, Update: Serialize>(&self, key: Key, update: Update) -> ArangoQuery {
        ArangoQuery::with_bind_vars(
            "UPDATE @key WITH @update IN @@collection RETURN NEW",
            btreemap![
                String::from("@collection") => Value::String(self.name.to_owned()),
                String::from("key") => serde_json::to_value(&key).unwrap(),
                String::from("update") => serde_json::to_value(&update).unwrap(),
            ],
        )
    }

    /// ```ignore
    /// let query = coll.update_with_id("Paul", &Instrument { instrument: String::from("bass") });
    /// ```
    fn update_with_id<Id: Serialize, Update: Serialize>(
        &self,
        id: Id,
        update: Update,
    ) -> ArangoQuery {
        ArangoQuery::with_bind_vars(
            "LET doc = DOCUMENT(@id) UPDATE doc WITH @update IN @@collection RETURN NEW",
            btreemap![
                String::from("@collection") => Value::String(self.name.to_owned()),
                String::from("id") => serde_json::to_value(&id).unwrap(),
                String::from("update") => serde_json::to_value(&update).unwrap(),
            ],
        )
    }
}

impl Remove for Collection {
    /// ```ignore
    /// let query = coll.remove("Paul");
    /// ```
    fn remove<Key: Serialize>(&self, key: Key) -> ArangoQuery {
        ArangoQuery::with_bind_vars(
            "REMOVE @key IN @@collection RETURN OLD",
            btreemap![
                String::from("@collection") => Value::String(self.name.to_owned()),
                String::from("key") => serde_json::to_value(&key).unwrap()
            ],
        )
    }

    /// ```ignore
    /// let query = coll.remove_with_id("Beatles/Paul");
    /// ```
    fn remove_with_id<Id: Serialize>(&self, id: Id) -> ArangoQuery {
        ArangoQuery::with_bind_vars(
            "LET doc = DOCUMENT(@id) REMOVE doc IN @@collection RETURN OLD",
            btreemap![
                String::from("@collection") => Value::String(self.name.to_owned()),
                String::from("id") => serde_json::to_value(&id).unwrap()
            ],
        )
    }
}

impl Truncate for Collection {
    /// ```ignore
    /// let query = coll.truncate();
    /// ```
    fn truncate(&self) -> ArangoQuery {
        ArangoQuery::with_bind_vars(
            "FOR item IN @@collection REMOVE item IN @@collection",
            btreemap![String::from("@collection") => Value::String( self.name.to_owned())],
        )
    }
}