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_route::{
10
    Cursor, ListOptions, ListQueryCond, NetworkRoute, NetworkRouteModel, QueryCond, SortKey,
11
};
12

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

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

            
26
/// SQLite schema.
27
#[derive(sqlx::FromRow)]
28
struct Schema {
29
    route_id: String,
30
    unit_id: String,
31
    unit_code: String,
32
    application_id: String,
33
    application_code: String,
34
    network_id: String,
35
    network_code: String,
36
    /// i64 as time tick from Epoch in milliseconds.
37
    created_at: i64,
38
}
39

            
40
/// Use "COUNT(*)" instead of "COUNT(fields...)" to simplify the implementation.
41
#[derive(sqlx::FromRow)]
42
struct CountSchema {
43
    #[sqlx(rename = "COUNT(*)")]
44
    count: i64,
45
}
46

            
47
const TABLE_NAME: &'static str = "network_route";
48
const FIELDS: &'static [&'static str] = &[
49
    "route_id",
50
    "unit_id",
51
    "unit_code",
52
    "application_id",
53
    "application_code",
54
    "network_id",
55
    "network_code",
56
    "created_at",
57
];
58
const TABLE_INIT_SQL: &'static str = "\
59
    CREATE TABLE IF NOT EXISTS network_route (\
60
    route_id TEXT NOT NULL UNIQUE,\
61
    unit_id TEXT NOT NULL,\
62
    unit_code TEXT NOT NULL,\
63
    application_id TEXT NOT NULL,\
64
    application_code TEXT NOT NULL,\
65
    network_id TEXT NOT NULL,\
66
    network_code TEXT NOT NULL,\
67
    created_at INTEGER NOT NULL,\
68
    UNIQUE (application_id,network_id),\
69
    PRIMARY KEY (route_id))";
70

            
71
impl Model {
72
    /// To create the model instance with a database connection.
73
28
    pub async fn new(conn: Arc<SqlitePool>) -> Result<Self, Box<dyn StdError>> {
74
28
        let model = Model { conn };
75
28
        model.init().await?;
76
28
        Ok(model)
77
28
    }
78
}
79

            
80
#[async_trait]
81
impl NetworkRouteModel for Model {
82
48
    async fn init(&self) -> Result<(), Box<dyn StdError>> {
83
48
        let _ = sqlx::query(TABLE_INIT_SQL)
84
48
            .execute(self.conn.as_ref())
85
48
            .await?;
86
48
        Ok(())
87
96
    }
88

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

            
92
88
        let result: Result<CountSchema, sqlx::Error> = sqlx::query_as(sql.as_str())
93
88
            .fetch_one(self.conn.as_ref())
94
88
            .await;
95

            
96
88
        let row = match result {
97
            Err(e) => return Err(Box::new(e)),
98
88
            Ok(row) => row,
99
88
        };
100
88
        Ok(row.count as u64)
101
176
    }
102

            
103
    async fn list(
104
        &self,
105
        opts: &ListOptions,
106
        cursor: Option<Box<dyn Cursor>>,
107
227
    ) -> Result<(Vec<NetworkRoute>, Option<Box<dyn Cursor>>), Box<dyn StdError>> {
108
227
        let mut cursor = match cursor {
109
197
            None => Box::new(DbCursor::new()),
110
30
            Some(cursor) => cursor,
111
        };
112

            
113
227
        let mut opts = ListOptions { ..*opts };
114
227
        if let Some(offset) = opts.offset {
115
24
            opts.offset = Some(offset + cursor.offset());
116
203
        } else {
117
203
            opts.offset = Some(cursor.offset());
118
203
        }
119
227
        let opts_limit = opts.limit;
120
227
        if let Some(limit) = opts_limit {
121
154
            if limit > 0 {
122
153
                if cursor.offset() >= limit {
123
13
                    return Ok((vec![], None));
124
140
                }
125
140
                opts.limit = Some(limit - cursor.offset());
126
1
            }
127
73
        }
128
214
        let mut builder = SqlBuilder::select_from(TABLE_NAME);
129
214
        build_limit_offset(&mut builder, &opts);
130
214
        build_sort(&mut builder, &opts);
131
214
        let sql = build_list_where(&mut builder, opts.cond).sql()?;
132

            
133
214
        let mut rows = sqlx::query_as::<_, Schema>(sql.as_str()).fetch(self.conn.as_ref());
134
214

            
135
214
        let mut count: u64 = 0;
136
214
        let mut list = vec![];
137
3333
        while let Some(row) = rows.try_next().await? {
138
3163
            let _ = cursor.as_mut().try_next().await?;
139
3163
            list.push(NetworkRoute {
140
3163
                route_id: row.route_id,
141
3163
                unit_id: row.unit_id,
142
3163
                unit_code: row.unit_code,
143
3163
                application_id: row.application_id,
144
3163
                application_code: row.application_code,
145
3163
                network_id: row.network_id,
146
3163
                network_code: row.network_code,
147
3163
                created_at: Utc.timestamp_nanos(row.created_at * 1000000),
148
3163
            });
149
3163
            if let Some(limit) = opts_limit {
150
1889
                if limit > 0 && cursor.offset() >= limit {
151
27
                    if let Some(cursor_max) = opts.cursor_max {
152
22
                        if (count + 1) >= cursor_max {
153
13
                            return Ok((list, Some(cursor)));
154
9
                        }
155
5
                    }
156
14
                    return Ok((list, None));
157
1862
                }
158
1274
            }
159
3136
            if let Some(cursor_max) = opts.cursor_max {
160
3058
                count += 1;
161
3058
                if count >= cursor_max {
162
17
                    return Ok((list, Some(cursor)));
163
3041
                }
164
78
            }
165
        }
166
170
        Ok((list, None))
167
454
    }
168

            
169
135
    async fn get(&self, route_id: &str) -> Result<Option<NetworkRoute>, Box<dyn StdError>> {
170
135
        let sql = SqlBuilder::select_from(TABLE_NAME)
171
135
            .fields(FIELDS)
172
135
            .and_where_eq("route_id", quote(route_id))
173
135
            .sql()?;
174

            
175
135
        let result: Result<Schema, sqlx::Error> = sqlx::query_as(sql.as_str())
176
135
            .fetch_one(self.conn.as_ref())
177
135
            .await;
178

            
179
135
        let row = match result {
180
37
            Err(e) => match e {
181
37
                sqlx::Error::RowNotFound => return Ok(None),
182
                _ => return Err(Box::new(e)),
183
            },
184
98
            Ok(row) => row,
185
98
        };
186
98

            
187
98
        Ok(Some(NetworkRoute {
188
98
            route_id: row.route_id,
189
98
            unit_id: row.unit_id,
190
98
            unit_code: row.unit_code,
191
98
            application_id: row.application_id,
192
98
            application_code: row.application_code,
193
98
            network_id: row.network_id,
194
98
            network_code: row.network_code,
195
98
            created_at: Utc.timestamp_nanos(row.created_at * 1000000),
196
98
        }))
197
270
    }
198

            
199
996
    async fn add(&self, route: &NetworkRoute) -> Result<(), Box<dyn StdError>> {
200
996
        let values = vec![
201
996
            quote(route.route_id.as_str()),
202
996
            quote(route.unit_id.as_str()),
203
996
            quote(route.unit_code.as_str()),
204
996
            quote(route.application_id.as_str()),
205
996
            quote(route.application_code.as_str()),
206
996
            quote(route.network_id.as_str()),
207
996
            quote(route.network_code.as_str()),
208
996
            route.created_at.timestamp_millis().to_string(),
209
996
        ];
210
996
        let sql = SqlBuilder::insert_into(TABLE_NAME)
211
996
            .fields(FIELDS)
212
996
            .values(&values)
213
996
            .sql()?;
214
996
        let _ = sqlx::query(sql.as_str())
215
996
            .execute(self.conn.as_ref())
216
996
            .await?;
217
994
        Ok(())
218
1992
    }
219

            
220
47
    async fn del(&self, cond: &QueryCond) -> Result<(), Box<dyn StdError>> {
221
47
        let sql = build_where(&mut SqlBuilder::delete_from(TABLE_NAME), cond).sql()?;
222
47
        let _ = sqlx::query(sql.as_str())
223
47
            .execute(self.conn.as_ref())
224
47
            .await?;
225
47
        Ok(())
226
94
    }
227
}
228

            
229
impl DbCursor {
230
    /// To create the cursor instance.
231
197
    pub fn new() -> Self {
232
197
        DbCursor { offset: 0 }
233
197
    }
234
}
235

            
236
#[async_trait]
237
impl Cursor for DbCursor {
238
3163
    async fn try_next(&mut self) -> Result<Option<NetworkRoute>, Box<dyn StdError>> {
239
3163
        self.offset += 1;
240
3163
        Ok(None)
241
6326
    }
242

            
243
2409
    fn offset(&self) -> u64 {
244
2409
        self.offset
245
2409
    }
246
}
247

            
248
/// Transforms query conditions to the SQL builder.
249
47
fn build_where<'a>(builder: &'a mut SqlBuilder, cond: &QueryCond<'a>) -> &'a mut SqlBuilder {
250
47
    if let Some(value) = cond.route_id {
251
6
        builder.and_where_eq("route_id", quote(value));
252
41
    }
253
47
    if let Some(value) = cond.unit_id {
254
18
        builder.and_where_eq("unit_id", quote(value));
255
29
    }
256
47
    if let Some(value) = cond.application_id {
257
11
        builder.and_where_eq("application_id", quote(value));
258
36
    }
259
47
    if let Some(value) = cond.network_id {
260
13
        builder.and_where_eq("network_id", quote(value));
261
34
    }
262
47
    builder
263
47
}
264

            
265
/// Transforms query conditions to the SQL builder.
266
302
fn build_list_where<'a>(
267
302
    builder: &'a mut SqlBuilder,
268
302
    cond: &ListQueryCond<'a>,
269
302
) -> &'a mut SqlBuilder {
270
302
    if let Some(value) = cond.route_id {
271
26
        builder.and_where_eq("route_id", quote(value));
272
276
    }
273
302
    if let Some(value) = cond.unit_id {
274
110
        builder.and_where_eq("unit_id", quote(value));
275
192
    }
276
302
    if let Some(value) = cond.unit_code {
277
6
        builder.and_where_eq("unit_code", quote(value));
278
296
    }
279
302
    if let Some(value) = cond.application_id {
280
86
        builder.and_where_eq("application_id", quote(value));
281
216
    }
282
302
    if let Some(value) = cond.application_code {
283
6
        builder.and_where_eq("application_code", quote(value));
284
296
    }
285
302
    if let Some(value) = cond.network_id {
286
109
        builder.and_where_eq("network_id", quote(value));
287
193
    }
288
302
    if let Some(value) = cond.network_code {
289
6
        builder.and_where_eq("network_code", quote(value));
290
296
    }
291
302
    builder
292
302
}
293

            
294
/// Transforms model options to the SQL builder.
295
214
fn build_limit_offset<'a>(builder: &'a mut SqlBuilder, opts: &ListOptions) -> &'a mut SqlBuilder {
296
214
    if let Some(value) = opts.limit {
297
141
        if value > 0 {
298
140
            builder.limit(value);
299
140
        }
300
73
    }
301
214
    if let Some(value) = opts.offset {
302
214
        match opts.limit {
303
73
            None => builder.limit(-1).offset(value),
304
1
            Some(0) => builder.limit(-1).offset(value),
305
140
            _ => builder.offset(value),
306
        };
307
    }
308
214
    builder
309
214
}
310

            
311
/// Transforms model options to the SQL builder.
312
214
fn build_sort<'a>(builder: &'a mut SqlBuilder, opts: &ListOptions) -> &'a mut SqlBuilder {
313
214
    if let Some(sort_cond) = opts.sort.as_ref() {
314
274
        for cond in sort_cond.iter() {
315
274
            let key = match cond.key {
316
130
                SortKey::CreatedAt => "created_at",
317
8
                SortKey::ApplicationCode => "application_code",
318
136
                SortKey::NetworkCode => "network_code",
319
            };
320
274
            builder.order_by(key, !cond.asc);
321
        }
322
67
    }
323
214
    builder
324
214
}