1
use std::{error::Error as StdError, sync::Arc};
2

            
3
use async_trait::async_trait;
4
use futures::TryStreamExt;
5
use mongodb::{
6
    action::Find,
7
    bson::{self, doc, DateTime, Document, Regex},
8
    Cursor as MongoDbCursor, Database,
9
};
10
use serde::{Deserialize, Serialize};
11

            
12
use super::super::application::{
13
    Application, ApplicationModel, Cursor, ListOptions, ListQueryCond, QueryCond, SortKey,
14
    UpdateQueryCond, Updates,
15
};
16

            
17
/// Model instance.
18
pub struct Model {
19
    /// The associated database connection.
20
    conn: Arc<Database>,
21
}
22

            
23
/// Cursor instance.
24
struct DbCursor {
25
    /// The associated collection cursor.
26
    cursor: MongoDbCursor<Schema>,
27
    /// (Useless) only for Cursor trait implementation.
28
    offset: u64,
29
}
30

            
31
/// MongoDB schema.
32
#[derive(Deserialize, Serialize)]
33
struct Schema {
34
    #[serde(rename = "applicationId")]
35
    application_id: String,
36
    code: String,
37
    #[serde(rename = "unitId")]
38
    unit_id: String,
39
    #[serde(rename = "unitCode")]
40
    unit_code: String,
41
    #[serde(rename = "createdAt")]
42
    created_at: DateTime,
43
    #[serde(rename = "modifiedAt")]
44
    modified_at: DateTime,
45
    #[serde(rename = "hostUri")]
46
    host_uri: String,
47
    name: String,
48
    info: Document,
49
}
50

            
51
const COL_NAME: &'static str = "application";
52

            
53
impl Model {
54
    /// To create the model instance with a database connection.
55
12
    pub async fn new(conn: Arc<Database>) -> Result<Self, Box<dyn StdError>> {
56
12
        let model = Model { conn };
57
12
        model.init().await?;
58
12
        Ok(model)
59
12
    }
60
}
61

            
62
#[async_trait]
63
impl ApplicationModel for Model {
64
19
    async fn init(&self) -> Result<(), Box<dyn StdError>> {
65
19
        let indexes = vec![
66
19
            doc! {"name": "applicationId_1", "key": {"applicationId": 1}, "unique": true},
67
19
            doc! {"name": "unitId_1_code_1", "key": {"unitId": 1, "code": 1}, "unique": true},
68
19
            doc! {"name": "code_1", "key": {"code": 1}},
69
19
            doc! {"name": "unitId_1", "key": {"unitId": 1}},
70
19
            doc! {"name": "createdAt_1", "key": {"createdAt": 1}},
71
19
            doc! {"name": "modifiedAt_1", "key": {"modifiedAt": 1}},
72
19
            doc! {"name": "name_1", "key": {"name": 1}},
73
19
        ];
74
19
        let command = doc! {
75
19
            "createIndexes": COL_NAME,
76
19
            "indexes": indexes,
77
19
        };
78
19
        self.conn.run_command(command).await?;
79
19
        Ok(())
80
38
    }
81

            
82
30
    async fn count(&self, cond: &ListQueryCond) -> Result<u64, Box<dyn StdError>> {
83
30
        let filter = get_list_query_filter(cond);
84
30
        let count = self
85
30
            .conn
86
30
            .collection::<Schema>(COL_NAME)
87
30
            .count_documents(filter)
88
30
            .await?;
89
30
        Ok(count)
90
60
    }
91

            
92
    async fn list(
93
        &self,
94
        opts: &ListOptions,
95
        cursor: Option<Box<dyn Cursor>>,
96
96
    ) -> Result<(Vec<Application>, Option<Box<dyn Cursor>>), Box<dyn StdError>> {
97
96
        let mut cursor = match cursor {
98
            None => {
99
84
                let filter = get_list_query_filter(opts.cond);
100
84
                Box::new(DbCursor::new(
101
84
                    build_find_options(opts, self.conn.collection::<Schema>(COL_NAME).find(filter))
102
84
                        .await?,
103
                ))
104
            }
105
12
            Some(cursor) => cursor,
106
        };
107

            
108
96
        let mut count: u64 = 0;
109
96
        let mut list = Vec::new();
110
1197
        while let Some(item) = cursor.try_next().await? {
111
1113
            list.push(item);
112
1113
            if let Some(cursor_max) = opts.cursor_max {
113
1028
                count += 1;
114
1028
                if count >= cursor_max {
115
12
                    return Ok((list, Some(cursor)));
116
1016
                }
117
85
            }
118
        }
119
84
        Ok((list, None))
120
192
    }
121

            
122
216
    async fn get(&self, cond: &QueryCond) -> Result<Option<Application>, Box<dyn StdError>> {
123
216
        let filter = get_query_filter(cond);
124
216
        let mut cursor = self
125
216
            .conn
126
216
            .collection::<Schema>(COL_NAME)
127
216
            .find(filter)
128
216
            .await?;
129
216
        if let Some(item) = cursor.try_next().await? {
130
            return Ok(Some(Application {
131
183
                application_id: item.application_id,
132
183
                code: item.code,
133
183
                unit_id: item.unit_id,
134
183
                unit_code: item.unit_code,
135
183
                created_at: item.created_at.into(),
136
183
                modified_at: item.modified_at.into(),
137
183
                host_uri: item.host_uri,
138
183
                name: item.name,
139
183
                info: bson::from_document(item.info)?,
140
            }));
141
33
        }
142
33
        Ok(None)
143
432
    }
144

            
145
780
    async fn add(&self, application: &Application) -> Result<(), Box<dyn StdError>> {
146
780
        let item = Schema {
147
780
            application_id: application.application_id.clone(),
148
780
            code: application.code.clone(),
149
780
            unit_id: application.unit_id.clone(),
150
780
            unit_code: application.unit_code.clone(),
151
780
            created_at: application.created_at.into(),
152
780
            modified_at: application.modified_at.into(),
153
780
            host_uri: application.host_uri.clone(),
154
780
            name: application.name.clone(),
155
780
            info: bson::to_document(&application.info)?,
156
        };
157
780
        self.conn
158
780
            .collection::<Schema>(COL_NAME)
159
780
            .insert_one(item)
160
780
            .await?;
161
776
        Ok(())
162
1560
    }
163

            
164
17
    async fn del(&self, cond: &QueryCond) -> Result<(), Box<dyn StdError>> {
165
17
        let filter = get_query_filter(cond);
166
17
        self.conn
167
17
            .collection::<Schema>(COL_NAME)
168
17
            .delete_many(filter)
169
17
            .await?;
170
17
        Ok(())
171
34
    }
172

            
173
    async fn update(
174
        &self,
175
        cond: &UpdateQueryCond,
176
        updates: &Updates,
177
9
    ) -> Result<(), Box<dyn StdError>> {
178
9
        let filter = get_update_query_filter(cond);
179
9
        if let Some(updates) = get_update_doc(updates) {
180
8
            self.conn
181
8
                .collection::<Schema>(COL_NAME)
182
8
                .update_one(filter, updates)
183
8
                .await?;
184
1
        }
185
9
        return Ok(());
186
18
    }
187
}
188

            
189
impl DbCursor {
190
    /// To create the cursor instance with a collection cursor.
191
84
    pub fn new(cursor: MongoDbCursor<Schema>) -> Self {
192
84
        DbCursor { cursor, offset: 0 }
193
84
    }
194
}
195

            
196
#[async_trait]
197
impl Cursor for DbCursor {
198
1197
    async fn try_next(&mut self) -> Result<Option<Application>, Box<dyn StdError>> {
199
1197
        if let Some(item) = self.cursor.try_next().await? {
200
1113
            self.offset += 1;
201
1113
            return Ok(Some(Application {
202
1113
                application_id: item.application_id,
203
1113
                code: item.code,
204
1113
                unit_id: item.unit_id,
205
1113
                unit_code: item.unit_code,
206
1113
                created_at: item.created_at.into(),
207
1113
                modified_at: item.modified_at.into(),
208
1113
                host_uri: item.host_uri,
209
1113
                name: item.name,
210
1113
                info: bson::from_document(item.info)?,
211
            }));
212
84
        }
213
84
        Ok(None)
214
2394
    }
215

            
216
4
    fn offset(&self) -> u64 {
217
4
        self.offset
218
4
    }
219
}
220

            
221
/// Transforms query conditions to the MongoDB document.
222
233
fn get_query_filter(cond: &QueryCond) -> Document {
223
233
    let mut filter = Document::new();
224
233
    if let Some(value) = cond.unit_id {
225
23
        filter.insert("unitId", value);
226
210
    }
227
233
    if let Some(value) = cond.application_id {
228
216
        filter.insert("applicationId", value);
229
216
    }
230
233
    if let Some(value) = cond.code {
231
9
        filter.insert("code", value);
232
224
    }
233
233
    filter
234
233
}
235

            
236
/// Transforms query conditions to the MongoDB document.
237
114
fn get_list_query_filter(cond: &ListQueryCond) -> Document {
238
114
    let mut filter = Document::new();
239
114
    if let Some(value) = cond.unit_id {
240
50
        filter.insert("unitId", value);
241
64
    }
242
114
    if let Some(value) = cond.application_id {
243
6
        filter.insert("applicationId", value);
244
108
    }
245
114
    if let Some(value) = cond.code {
246
16
        filter.insert("code", value);
247
98
    }
248
114
    if let Some(value) = cond.code_contains {
249
19
        filter.insert(
250
19
            "code",
251
19
            Regex {
252
19
                pattern: value.to_string(),
253
19
                options: "i".to_string(),
254
19
            },
255
19
        );
256
95
    }
257
114
    if let Some(value) = cond.name_contains {
258
8
        filter.insert(
259
8
            "name",
260
8
            Regex {
261
8
                pattern: value.to_string(),
262
8
                options: "i".to_string(),
263
8
            },
264
8
        );
265
106
    }
266
114
    filter
267
114
}
268

            
269
/// Transforms model options to the options.
270
84
fn build_find_options<'a, T>(opts: &ListOptions, mut find: Find<'a, T>) -> Find<'a, T>
271
84
where
272
84
    T: Send + Sync,
273
84
{
274
84
    if let Some(offset) = opts.offset {
275
10
        find = find.skip(offset);
276
74
    }
277
84
    if let Some(limit) = opts.limit {
278
40
        if limit > 0 {
279
39
            find = find.limit(limit as i64);
280
39
        }
281
44
    }
282
84
    if let Some(sort_list) = opts.sort.as_ref() {
283
55
        if sort_list.len() > 0 {
284
54
            let mut sort_opts = Document::new();
285
56
            for cond in sort_list.iter() {
286
56
                let key = match cond.key {
287
6
                    SortKey::CreatedAt => "createdAt",
288
4
                    SortKey::ModifiedAt => "modifiedAt",
289
40
                    SortKey::Code => "code",
290
6
                    SortKey::Name => "name",
291
                };
292
56
                if cond.asc {
293
47
                    sort_opts.insert(key.to_string(), 1);
294
47
                } else {
295
9
                    sort_opts.insert(key.to_string(), -1);
296
9
                }
297
            }
298
54
            find = find.sort(sort_opts);
299
1
        }
300
29
    }
301
84
    find
302
84
}
303

            
304
/// Transforms query conditions to the MongoDB document.
305
9
fn get_update_query_filter(cond: &UpdateQueryCond) -> Document {
306
9
    doc! {"applicationId": cond.application_id}
307
9
}
308

            
309
/// Transforms the model object to the MongoDB document.
310
9
fn get_update_doc(updates: &Updates) -> Option<Document> {
311
9
    let mut count = 0;
312
9
    let mut document = Document::new();
313
9
    if let Some(value) = updates.modified_at.as_ref() {
314
8
        document.insert(
315
8
            "modifiedAt",
316
8
            DateTime::from_millis(value.timestamp_millis()),
317
8
        );
318
8
        count += 1;
319
8
    }
320
9
    if let Some(value) = updates.host_uri {
321
4
        document.insert("hostUri", value);
322
4
        count += 1;
323
5
    }
324
9
    if let Some(value) = updates.name {
325
6
        document.insert("name", value);
326
6
        count += 1;
327
6
    }
328
9
    if let Some(value) = updates.info {
329
6
        document.insert(
330
6
            "info",
331
6
            match bson::to_document(value) {
332
                Err(_) => return None,
333
6
                Ok(doc) => doc,
334
6
            },
335
6
        );
336
6
        count += 1;
337
3
    }
338
9
    if count == 0 {
339
1
        return None;
340
8
    }
341
8
    Some(doc! {"$set": document})
342
9
}