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, Bson, DateTime, Document, Regex},
8
    Cursor as MongoDbCursor, Database,
9
};
10
use serde::{Deserialize, Serialize};
11

            
12
use super::super::network::{
13
    Cursor, ListOptions, ListQueryCond, Network, NetworkModel, QueryCond, SortKey, 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
#[derive(Deserialize, Serialize)]
33
struct Schema {
34
    #[serde(rename = "networkId")]
35
    network_id: String,
36
    code: String,
37
    #[serde(rename = "unitId")]
38
    unit_id: Option<String>,
39
    #[serde(rename = "unitCode")]
40
    unit_code: Option<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 = "network";
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 NetworkModel for Model {
64
38
    async fn init(&self) -> Result<(), Box<dyn StdError>> {
65
38
        let indexes = vec![
66
38
            doc! {"name": "networkId_1", "key": {"networkId": 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
212
    ) -> Result<(Vec<Network>, Option<Box<dyn Cursor>>), Box<dyn StdError>> {
97
212
        let mut cursor = match cursor {
98
            None => {
99
174
                let filter = get_list_query_filter(opts.cond);
100
174
                Box::new(DbCursor::new(
101
174
                    build_find_options(opts, self.conn.collection::<Schema>(COL_NAME).find(filter))
102
174
                        .await?,
103
                ))
104
            }
105
38
            Some(cursor) => cursor,
106
        };
107

            
108
212
        let mut count: u64 = 0;
109
212
        let mut list = Vec::new();
110
3822
        while let Some(item) = cursor.try_next().await? {
111
3648
            list.push(item);
112
3648
            if let Some(cursor_max) = opts.cursor_max {
113
3478
                count += 1;
114
3478
                if count >= cursor_max {
115
38
                    return Ok((list, Some(cursor)));
116
3440
                }
117
170
            }
118
        }
119
174
        Ok((list, None))
120
424
    }
121

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

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

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

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

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

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

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

            
221
/// Transforms query conditions to the MongoDB document.
222
630
fn get_query_filter(cond: &QueryCond) -> Document {
223
630
    let mut filter = Document::new();
224
630
    if let Some(value) = cond.unit_id {
225
64
        match value {
226
16
            None => {
227
16
                filter.insert("unitId", Bson::Null);
228
16
            }
229
48
            Some(value) => {
230
48
                filter.insert("unitId", value);
231
48
            }
232
        }
233
566
    }
234
630
    if let Some(value) = cond.network_id {
235
580
        filter.insert("networkId", value);
236
580
    }
237
630
    if let Some(value) = cond.code {
238
32
        filter.insert("code", value);
239
598
    }
240
630
    filter
241
630
}
242

            
243
/// Transforms query conditions to the MongoDB document.
244
234
fn get_list_query_filter(cond: &ListQueryCond) -> Document {
245
234
    let mut filter = Document::new();
246
234
    if let Some(value) = cond.unit_id {
247
108
        match value {
248
20
            None => {
249
20
                filter.insert("unitId", Bson::Null);
250
20
            }
251
88
            Some(value) => {
252
88
                filter.insert("unitId", value);
253
88
            }
254
        }
255
126
    }
256
234
    if let Some(value) = cond.network_id {
257
12
        filter.insert("networkId", value);
258
222
    }
259
234
    if let Some(value) = cond.code {
260
32
        filter.insert("code", value);
261
202
    }
262
234
    if let Some(value) = cond.code_contains {
263
44
        filter.insert(
264
44
            "code",
265
44
            Regex {
266
44
                pattern: value.to_string(),
267
44
                options: "i".to_string(),
268
44
            },
269
44
        );
270
190
    }
271
234
    if let Some(value) = cond.name_contains {
272
16
        filter.insert(
273
16
            "name",
274
16
            Regex {
275
16
                pattern: value.to_string(),
276
16
                options: "i".to_string(),
277
16
            },
278
16
        );
279
218
    }
280
234
    filter
281
234
}
282

            
283
/// Transforms model options to the options.
284
174
fn build_find_options<'a, T>(opts: &ListOptions, mut find: Find<'a, T>) -> Find<'a, T>
285
174
where
286
174
    T: Send + Sync,
287
174
{
288
174
    if let Some(offset) = opts.offset {
289
20
        find = find.skip(offset);
290
154
    }
291
174
    if let Some(limit) = opts.limit {
292
82
        if limit > 0 {
293
80
            find = find.limit(limit as i64);
294
80
        }
295
92
    }
296
174
    if let Some(sort_list) = opts.sort.as_ref() {
297
116
        if sort_list.len() > 0 {
298
114
            let mut sort_opts = Document::new();
299
118
            for cond in sort_list.iter() {
300
118
                let key = match cond.key {
301
12
                    SortKey::CreatedAt => "createdAt",
302
8
                    SortKey::ModifiedAt => "modifiedAt",
303
86
                    SortKey::Code => "code",
304
12
                    SortKey::Name => "name",
305
                };
306
118
                if cond.asc {
307
100
                    sort_opts.insert(key.to_string(), 1);
308
100
                } else {
309
18
                    sort_opts.insert(key.to_string(), -1);
310
18
                }
311
            }
312
114
            find = find.sort(sort_opts);
313
2
        }
314
58
    }
315
174
    find
316
174
}
317

            
318
/// Transforms query conditions to the MongoDB document.
319
22
fn get_update_query_filter(cond: &UpdateQueryCond) -> Document {
320
22
    doc! {"networkId": cond.network_id}
321
22
}
322

            
323
/// Transforms the model object to the MongoDB document.
324
22
fn get_update_doc(updates: &Updates) -> Option<Document> {
325
22
    let mut count = 0;
326
22
    let mut document = Document::new();
327
22
    if let Some(value) = updates.modified_at.as_ref() {
328
20
        document.insert(
329
20
            "modifiedAt",
330
20
            DateTime::from_millis(value.timestamp_millis()),
331
20
        );
332
20
        count += 1;
333
20
    }
334
22
    if let Some(value) = updates.host_uri {
335
10
        document.insert("hostUri", value);
336
10
        count += 1;
337
12
    }
338
22
    if let Some(value) = updates.name {
339
16
        document.insert("name", value);
340
16
        count += 1;
341
16
    }
342
22
    if let Some(value) = updates.info {
343
16
        document.insert(
344
16
            "info",
345
16
            match bson::to_document(value) {
346
                Err(_) => return None,
347
16
                Ok(doc) => doc,
348
16
            },
349
16
        );
350
16
        count += 1;
351
6
    }
352
22
    if count == 0 {
353
2
        return None;
354
20
    }
355
20
    Some(doc! {"$set": document})
356
22
}