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

            
3
use async_trait::async_trait;
4
use chrono::{TimeZone, Utc};
5
use futures::TryStreamExt;
6
use sql_builder::{quote, SqlBuilder};
7
use sqlx::SqlitePool;
8

            
9
use super::super::network_dldata::{
10
    Cursor, ListOptions, ListQueryCond, NetworkDlData, NetworkDlDataModel, QueryCond, SortKey,
11
    UpdateQueryCond, Updates,
12
};
13

            
14
/// Model instance.
15
pub struct Model {
16
    /// The associated database connection.
17
    conn: Arc<SqlitePool>,
18
}
19

            
20
/// Cursor instance.
21
///
22
/// The SQLite implementation uses the original list options and the progress offset.
23
pub struct DbCursor {
24
    offset: u64,
25
}
26

            
27
/// SQLite schema.
28
#[derive(sqlx::FromRow)]
29
struct Schema {
30
    pub data_id: String,
31
    /// i64 as time tick from Epoch in milliseconds.
32
    pub proc: i64,
33
    /// i64 as time tick from Epoch in milliseconds.
34
    #[sqlx(rename = "pub")]
35
    pub publish: i64,
36
    /// i64 as time tick from Epoch in milliseconds.
37
    pub resp: Option<i64>,
38
    pub status: i32,
39
    pub unit_id: String,
40
    /// use empty string as NULL.
41
    pub device_id: String,
42
    /// use empty string as NULL.
43
    pub network_code: String,
44
    /// use empty string as NULL.
45
    pub network_addr: String,
46
    pub profile: String,
47
    pub data: String,
48
    /// use empty string as NULL.
49
    pub extension: String,
50
}
51

            
52
/// Use "COUNT(*)" instead of "COUNT(fields...)" to simplify the implementation.
53
#[derive(sqlx::FromRow)]
54
struct CountSchema {
55
    #[sqlx(rename = "COUNT(*)")]
56
    count: i64,
57
}
58

            
59
const TABLE_NAME: &'static str = "network_dldata";
60
const FIELDS: &'static [&'static str] = &[
61
    "data_id",
62
    "proc",
63
    "pub",
64
    "resp",
65
    "status",
66
    "unit_id",
67
    "device_id",
68
    "network_code",
69
    "network_addr",
70
    "profile",
71
    "data",
72
    "extension",
73
];
74
const TABLE_INIT_SQL: &'static str = "\
75
    CREATE TABLE IF NOT EXISTS network_dldata (\
76
    data_id TEXT NOT NULL UNIQUE,\
77
    proc INTEGER NOT NULL,\
78
    pub INTEGER NOT NULL,\
79
    resp INTEGER,\
80
    status INTEGER NOT NULL,\
81
    unit_id TEXT NOT NULL,\
82
    device_id TEXT NOT NULL,\
83
    network_code TEXT NOT NULL,\
84
    network_addr TEXT NOT NULL,\
85
    profile TEXT NOT NULL,\
86
    data TEXT NOT NULL,\
87
    extension TEXT NOT NULL,\
88
    PRIMARY KEY (data_id))";
89

            
90
impl Model {
91
    /// To create the model instance with a database connection.
92
12
    pub async fn new(conn: Arc<SqlitePool>) -> Result<Self, Box<dyn StdError>> {
93
12
        let model = Model { conn };
94
25
        model.init().await?;
95
12
        Ok(model)
96
12
    }
97
}
98

            
99
#[async_trait]
100
impl NetworkDlDataModel for Model {
101
19
    async fn init(&self) -> Result<(), Box<dyn StdError>> {
102
19
        let _ = sqlx::query(TABLE_INIT_SQL)
103
19
            .execute(self.conn.as_ref())
104
39
            .await?;
105
19
        Ok(())
106
38
    }
107

            
108
44
    async fn count(&self, cond: &ListQueryCond) -> Result<u64, Box<dyn StdError>> {
109
44
        let sql = build_list_where(SqlBuilder::select_from(TABLE_NAME).count("*"), &cond).sql()?;
110

            
111
44
        let result: Result<CountSchema, sqlx::Error> = sqlx::query_as(sql.as_str())
112
44
            .fetch_one(self.conn.as_ref())
113
88
            .await;
114

            
115
44
        let row = match result {
116
            Err(e) => return Err(Box::new(e)),
117
44
            Ok(row) => row,
118
44
        };
119
44
        Ok(row.count as u64)
120
88
    }
121

            
122
    async fn list(
123
        &self,
124
        opts: &ListOptions,
125
        cursor: Option<Box<dyn Cursor>>,
126
103
    ) -> Result<(Vec<NetworkDlData>, Option<Box<dyn Cursor>>), Box<dyn StdError>> {
127
103
        let mut cursor = match cursor {
128
90
            None => Box::new(DbCursor::new()),
129
13
            Some(cursor) => cursor,
130
        };
131

            
132
103
        let mut opts = ListOptions { ..*opts };
133
103
        if let Some(offset) = opts.offset {
134
19
            opts.offset = Some(offset + cursor.offset());
135
84
        } else {
136
84
            opts.offset = Some(cursor.offset());
137
84
        }
138
103
        let opts_limit = opts.limit;
139
103
        if let Some(limit) = opts_limit {
140
77
            if limit > 0 {
141
71
                if cursor.offset() >= limit {
142
3
                    return Ok((vec![], None));
143
68
                }
144
68
                opts.limit = Some(limit - cursor.offset());
145
6
            }
146
26
        }
147
100
        let mut builder = SqlBuilder::select_from(TABLE_NAME);
148
100
        build_limit_offset(&mut builder, &opts);
149
100
        build_sort(&mut builder, &opts);
150
100
        let sql = build_list_where(&mut builder, opts.cond).sql()?;
151

            
152
100
        let mut rows = sqlx::query_as::<_, Schema>(sql.as_str()).fetch(self.conn.as_ref());
153
100

            
154
100
        let mut count: u64 = 0;
155
100
        let mut list = vec![];
156
1263
        while let Some(row) = rows.try_next().await? {
157
1185
            let _ = cursor.as_mut().try_next().await?;
158
1185
            list.push(NetworkDlData {
159
1185
                data_id: row.data_id,
160
1185
                proc: Utc.timestamp_nanos(row.proc * 1000000),
161
1185
                publish: Utc.timestamp_nanos(row.publish * 1000000),
162
1185
                resp: match row.resp {
163
760
                    None => None,
164
425
                    Some(resp) => Some(Utc.timestamp_nanos(resp * 1000000)),
165
                },
166
1185
                status: row.status,
167
1185
                unit_id: row.unit_id,
168
1185
                device_id: row.device_id,
169
1185
                network_code: row.network_code,
170
1185
                network_addr: row.network_addr,
171
1185
                profile: row.profile,
172
1185
                data: row.data,
173
1185
                extension: match row.extension.len() {
174
928
                    0 => None,
175
257
                    _ => serde_json::from_str(row.extension.as_str())?,
176
                },
177
            });
178
1185
            if let Some(limit) = opts_limit {
179
1099
                if limit > 0 && cursor.offset() >= limit {
180
12
                    if let Some(cursor_max) = opts.cursor_max {
181
11
                        if (count + 1) >= cursor_max {
182
3
                            return Ok((list, Some(cursor)));
183
8
                        }
184
1
                    }
185
9
                    return Ok((list, None));
186
1087
                }
187
86
            }
188
1173
            if let Some(cursor_max) = opts.cursor_max {
189
1078
                count += 1;
190
1078
                if count >= cursor_max {
191
10
                    return Ok((list, Some(cursor)));
192
1068
                }
193
95
            }
194
        }
195
78
        Ok((list, None))
196
206
    }
197

            
198
473
    async fn add(&self, data: &NetworkDlData) -> Result<(), Box<dyn StdError>> {
199
473
        let extension = match data.extension.as_ref() {
200
262
            None => quote(""),
201
211
            Some(extension) => match serde_json::to_string(extension) {
202
                Err(_) => quote("{}"),
203
211
                Ok(value) => quote(value.as_str()),
204
            },
205
        };
206
473
        let values = vec![
207
473
            quote(data.data_id.as_str()),
208
473
            data.proc.timestamp_millis().to_string(),
209
473
            data.publish.timestamp_millis().to_string(),
210
473
            match data.resp {
211
238
                None => "NULL".to_string(),
212
235
                Some(resp) => resp.timestamp_millis().to_string(),
213
            },
214
473
            data.status.to_string(),
215
473
            quote(data.unit_id.as_str()),
216
473
            quote(data.device_id.as_str()),
217
473
            quote(data.network_code.as_str()),
218
473
            quote(data.network_addr.as_str()),
219
473
            quote(data.profile.as_str()),
220
473
            quote(data.data.as_str()),
221
473
            extension,
222
        ];
223
473
        let sql = SqlBuilder::insert_into(TABLE_NAME)
224
473
            .fields(FIELDS)
225
473
            .values(&values)
226
473
            .sql()?;
227
473
        let _ = sqlx::query(sql.as_str())
228
473
            .execute(self.conn.as_ref())
229
945
            .await?;
230
472
        Ok(())
231
946
    }
232

            
233
41
    async fn del(&self, cond: &QueryCond) -> Result<(), Box<dyn StdError>> {
234
41
        let sql = build_where(&mut SqlBuilder::delete_from(TABLE_NAME), cond).sql()?;
235
41
        let _ = sqlx::query(sql.as_str())
236
41
            .execute(self.conn.as_ref())
237
75
            .await?;
238
41
        Ok(())
239
82
    }
240

            
241
    async fn update(
242
        &self,
243
        cond: &UpdateQueryCond,
244
        updates: &Updates,
245
17
    ) -> Result<(), Box<dyn StdError>> {
246
17
        let sql = match build_update_where(&mut SqlBuilder::update_table(TABLE_NAME), cond, updates)
247
        {
248
            None => return Ok(()),
249
17
            Some(builder) => builder.sql()?,
250
        };
251
17
        let _ = sqlx::query(sql.as_str())
252
17
            .execute(self.conn.as_ref())
253
36
            .await?;
254
17
        Ok(())
255
34
    }
256
}
257

            
258
impl DbCursor {
259
    /// To create the cursor instance.
260
90
    pub fn new() -> Self {
261
90
        DbCursor { offset: 0 }
262
90
    }
263
}
264

            
265
#[async_trait]
266
impl Cursor for DbCursor {
267
1185
    async fn try_next(&mut self) -> Result<Option<NetworkDlData>, Box<dyn StdError>> {
268
1185
        self.offset += 1;
269
1185
        Ok(None)
270
2370
    }
271

            
272
942
    fn offset(&self) -> u64 {
273
942
        self.offset
274
942
    }
275
}
276

            
277
/// Transforms query conditions to the SQL builder.
278
41
fn build_where<'a>(builder: &'a mut SqlBuilder, cond: &QueryCond<'a>) -> &'a mut SqlBuilder {
279
41
    if let Some(value) = cond.unit_id {
280
3
        builder.and_where_eq("unit_id", quote(value));
281
38
    }
282
41
    if let Some(value) = cond.device_id {
283
1
        builder.and_where_eq("device_id", quote(value));
284
40
    }
285
41
    if let Some(value) = cond.proc_gte {
286
1
        builder.and_where_ge("proc", value.timestamp_millis());
287
40
    }
288
41
    if let Some(value) = cond.proc_lte {
289
1
        builder.and_where_le("proc", value.timestamp_millis());
290
40
    }
291
41
    builder
292
41
}
293

            
294
/// Transforms query conditions to the SQL builder.
295
144
fn build_list_where<'a>(
296
144
    builder: &'a mut SqlBuilder,
297
144
    cond: &ListQueryCond<'a>,
298
144
) -> &'a mut SqlBuilder {
299
144
    if let Some(value) = cond.unit_id {
300
58
        builder.and_where_eq("unit_id", quote(value));
301
86
    }
302
144
    if let Some(value) = cond.device_id {
303
14
        builder.and_where_eq("device_id", quote(value));
304
130
    }
305
144
    if let Some(value) = cond.network_code {
306
8
        builder.and_where_eq("network_code", quote(value));
307
136
    }
308
144
    if let Some(value) = cond.network_addr {
309
6
        builder.and_where_eq("network_addr", quote(value));
310
138
    }
311
144
    if let Some(value) = cond.profile {
312
6
        builder.and_where_eq("profile", quote(value));
313
138
    }
314
144
    if let Some(value) = cond.proc_gte {
315
31
        builder.and_where_ge("proc", value.timestamp_millis());
316
113
    }
317
144
    if let Some(value) = cond.proc_lte {
318
8
        builder.and_where_le("proc", value.timestamp_millis());
319
136
    }
320
144
    if let Some(value) = cond.pub_gte {
321
14
        builder.and_where_ge("pub", value.timestamp_millis());
322
130
    }
323
144
    if let Some(value) = cond.pub_lte {
324
8
        builder.and_where_le("pub", value.timestamp_millis());
325
136
    }
326
144
    if let Some(value) = cond.resp_gte {
327
14
        builder.and_where_ge("resp", value.timestamp_millis());
328
130
    }
329
144
    if let Some(value) = cond.resp_lte {
330
8
        builder.and_where_le("resp", value.timestamp_millis());
331
136
    }
332
144
    builder
333
144
}
334

            
335
/// Transforms model options to the SQL builder.
336
100
fn build_limit_offset<'a>(builder: &'a mut SqlBuilder, opts: &ListOptions) -> &'a mut SqlBuilder {
337
100
    if let Some(value) = opts.limit {
338
74
        if value > 0 {
339
68
            builder.limit(value);
340
68
        }
341
26
    }
342
100
    if let Some(value) = opts.offset {
343
100
        match opts.limit {
344
26
            None => builder.limit(-1).offset(value),
345
6
            Some(0) => builder.limit(-1).offset(value),
346
68
            _ => builder.offset(value),
347
        };
348
    }
349
100
    builder
350
100
}
351

            
352
/// Transforms model options to the SQL builder.
353
100
fn build_sort<'a>(builder: &'a mut SqlBuilder, opts: &ListOptions) -> &'a mut SqlBuilder {
354
100
    if let Some(sort_cond) = opts.sort.as_ref() {
355
103
        for cond in sort_cond.iter() {
356
103
            let key = match cond.key {
357
79
                SortKey::Proc => "proc",
358
4
                SortKey::Pub => "pub",
359
4
                SortKey::Resp => "resp",
360
8
                SortKey::NetworkCode => "network_code",
361
8
                SortKey::NetworkAddr => "network_addr",
362
            };
363
103
            builder.order_by(key, !cond.asc);
364
        }
365
13
    }
366
100
    builder
367
100
}
368

            
369
/// Transforms query conditions and the model object to the SQL builder.
370
17
fn build_update_where<'a>(
371
17
    builder: &'a mut SqlBuilder,
372
17
    cond: &UpdateQueryCond<'a>,
373
17
    updates: &Updates,
374
17
) -> Option<&'a mut SqlBuilder> {
375
17
    builder.set("resp", updates.resp.timestamp_millis());
376
17
    builder.set("status", updates.status);
377
17
    builder.and_where_eq("data_id", quote(cond.data_id));
378
17
    if updates.status >= 0 {
379
13
        builder.and_where_ne("status", 0);
380
13
    } else {
381
4
        builder.and_where_lt("status", updates.status);
382
4
    }
383
17
    Some(builder)
384
17
}