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::unit::{
13
    Cursor, ListOptions, ListQueryCond, QueryCond, SortKey, Unit, UnitModel, UpdateQueryCond,
14
    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
15350
#[derive(Deserialize, Serialize)]
33
struct Schema {
34
    #[serde(rename = "unitId")]
35
    unit_id: String,
36
    code: String,
37
    #[serde(rename = "createdAt")]
38
    created_at: DateTime,
39
    #[serde(rename = "modifiedAt")]
40
    modified_at: DateTime,
41
    #[serde(rename = "ownerId")]
42
    owner_id: String,
43
    #[serde(rename = "memberIds")]
44
    member_ids: Vec<String>,
45
    name: String,
46
    info: Document,
47
}
48

            
49
const COL_NAME: &'static str = "unit";
50

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

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

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

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

            
106
83
        let mut count: u64 = 0;
107
83
        let mut list = Vec::new();
108
1061
        while let Some(item) = cursor.try_next().await? {
109
989
            list.push(item);
110
989
            if let Some(cursor_max) = opts.cursor_max {
111
905
                count += 1;
112
905
                if count >= cursor_max {
113
11
                    return Ok((list, Some(cursor)));
114
894
                }
115
84
            }
116
        }
117
72
        Ok((list, None))
118
166
    }
119

            
120
668
    async fn get(&self, cond: &QueryCond) -> Result<Option<Unit>, Box<dyn StdError>> {
121
668
        let filter = get_query_filter(cond);
122
668
        let mut cursor = self
123
668
            .conn
124
668
            .collection::<Schema>(COL_NAME)
125
668
            .find(filter)
126
1336
            .await?;
127
668
        if let Some(item) = cursor.try_next().await? {
128
            return Ok(Some(Unit {
129
546
                unit_id: item.unit_id,
130
546
                code: item.code,
131
546
                created_at: item.created_at.into(),
132
546
                modified_at: item.modified_at.into(),
133
546
                owner_id: item.owner_id,
134
546
                member_ids: item.member_ids,
135
546
                name: item.name,
136
546
                info: bson::from_document(item.info)?,
137
            }));
138
122
        }
139
122
        Ok(None)
140
1336
    }
141

            
142
697
    async fn add(&self, unit: &Unit) -> Result<(), Box<dyn StdError>> {
143
697
        let item = Schema {
144
697
            unit_id: unit.unit_id.clone(),
145
697
            code: unit.code.clone(),
146
697
            created_at: unit.created_at.into(),
147
697
            modified_at: unit.modified_at.into(),
148
697
            owner_id: unit.owner_id.clone(),
149
697
            member_ids: unit.member_ids.clone(),
150
697
            name: unit.name.clone(),
151
697
            info: bson::to_document(&unit.info)?,
152
        };
153
697
        self.conn
154
697
            .collection::<Schema>(COL_NAME)
155
697
            .insert_one(item)
156
1396
            .await?;
157
695
        Ok(())
158
1394
    }
159

            
160
12
    async fn del(&self, cond: &QueryCond) -> Result<(), Box<dyn StdError>> {
161
12
        let filter = get_query_filter(cond);
162
12
        self.conn
163
12
            .collection::<Schema>(COL_NAME)
164
12
            .delete_many(filter)
165
24
            .await?;
166
12
        Ok(())
167
24
    }
168

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

            
185
impl DbCursor {
186
    /// To create the cursor instance with a collection cursor.
187
72
    pub fn new(cursor: MongoDbCursor<Schema>) -> Self {
188
72
        DbCursor { cursor, offset: 0 }
189
72
    }
190
}
191

            
192
#[async_trait]
193
impl Cursor for DbCursor {
194
1061
    async fn try_next(&mut self) -> Result<Option<Unit>, Box<dyn StdError>> {
195
1061
        if let Some(item) = self.cursor.try_next().await? {
196
989
            self.offset += 1;
197
989
            return Ok(Some(Unit {
198
989
                unit_id: item.unit_id,
199
989
                code: item.code,
200
989
                created_at: item.created_at.into(),
201
989
                modified_at: item.modified_at.into(),
202
989
                owner_id: item.owner_id,
203
989
                member_ids: item.member_ids,
204
989
                name: item.name,
205
989
                info: bson::from_document(item.info)?,
206
            }));
207
72
        }
208
72
        Ok(None)
209
2122
    }
210

            
211
4
    fn offset(&self) -> u64 {
212
4
        self.offset
213
4
    }
214
}
215

            
216
/// Transforms query conditions to the MongoDB document.
217
680
fn get_query_filter(cond: &QueryCond) -> Document {
218
680
    let mut filter = Document::new();
219
680
    if let Some(value) = cond.unit_id {
220
666
        filter.insert("unitId", value);
221
666
    }
222
680
    if let Some(value) = cond.code {
223
13
        filter.insert("code", value);
224
667
    }
225
680
    if let Some(value) = cond.owner_id {
226
142
        filter.insert("ownerId", value);
227
538
    }
228
680
    if let Some(value) = cond.member_id {
229
218
        filter.insert("memberIds", value);
230
462
    }
231
680
    filter
232
680
}
233

            
234
/// Transforms query conditions to the MongoDB document.
235
100
fn get_list_query_filter(cond: &ListQueryCond) -> Document {
236
100
    let mut filter = Document::new();
237
100
    if let Some(value) = cond.owner_id {
238
24
        filter.insert("ownerId", value);
239
76
    }
240
100
    if let Some(value) = cond.member_id {
241
37
        filter.insert("memberIds", value);
242
63
    }
243
100
    if let Some(value) = cond.unit_id {
244
6
        filter.insert("unitId", value);
245
94
    }
246
100
    if let Some(value) = cond.code_contains {
247
20
        filter.insert(
248
20
            "code",
249
20
            Regex {
250
20
                pattern: value.to_string(),
251
20
                options: "i".to_string(),
252
20
            },
253
20
        );
254
80
    }
255
100
    if let Some(value) = cond.name_contains {
256
8
        filter.insert(
257
8
            "name",
258
8
            Regex {
259
8
                pattern: value.to_string(),
260
8
                options: "i".to_string(),
261
8
            },
262
8
        );
263
92
    }
264
100
    filter
265
100
}
266

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

            
302
/// Transforms query conditions to the MongoDB document.
303
10
fn get_update_query_filter(cond: &UpdateQueryCond) -> Document {
304
10
    doc! {"unitId": cond.unit_id}
305
10
}
306

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