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
24
    pub async fn new(conn: Arc<Database>) -> Result<Self, Box<dyn StdError>> {
56
24
        let model = Model { conn };
57
24
        model.init().await?;
58
24
        Ok(model)
59
24
    }
60
}
61

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

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

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

            
108
192
        let mut count: u64 = 0;
109
192
        let mut list = Vec::new();
110
2394
        while let Some(item) = cursor.try_next().await? {
111
2226
            list.push(item);
112
2226
            if let Some(cursor_max) = opts.cursor_max {
113
2056
                count += 1;
114
2056
                if count >= cursor_max {
115
24
                    return Ok((list, Some(cursor)));
116
2032
                }
117
170
            }
118
        }
119
168
        Ok((list, None))
120
384
    }
121

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

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

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

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

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

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

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

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

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

            
269
/// Transforms model options to the options.
270
168
fn build_find_options<'a, T>(opts: &ListOptions, mut find: Find<'a, T>) -> Find<'a, T>
271
168
where
272
168
    T: Send + Sync,
273
168
{
274
168
    if let Some(offset) = opts.offset {
275
20
        find = find.skip(offset);
276
148
    }
277
168
    if let Some(limit) = opts.limit {
278
80
        if limit > 0 {
279
78
            find = find.limit(limit as i64);
280
78
        }
281
88
    }
282
168
    if let Some(sort_list) = opts.sort.as_ref() {
283
110
        if sort_list.len() > 0 {
284
108
            let mut sort_opts = Document::new();
285
112
            for cond in sort_list.iter() {
286
112
                let key = match cond.key {
287
12
                    SortKey::CreatedAt => "createdAt",
288
8
                    SortKey::ModifiedAt => "modifiedAt",
289
80
                    SortKey::Code => "code",
290
12
                    SortKey::Name => "name",
291
                };
292
112
                if cond.asc {
293
94
                    sort_opts.insert(key.to_string(), 1);
294
94
                } else {
295
18
                    sort_opts.insert(key.to_string(), -1);
296
18
                }
297
            }
298
108
            find = find.sort(sort_opts);
299
2
        }
300
58
    }
301
168
    find
302
168
}
303

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

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