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::{
10
    super::unit::{
11
        Cursor, ListOptions, ListQueryCond, QueryCond, SortKey, Unit, UnitModel, UpdateQueryCond,
12
        Updates,
13
    },
14
    build_where_like,
15
};
16

            
17
/// Model instance.
18
pub struct Model {
19
    /// The associated database connection.
20
    conn: Arc<SqlitePool>,
21
}
22

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

            
30
/// SQLite schema.
31
#[derive(sqlx::FromRow)]
32
struct Schema {
33
    unit_id: String,
34
    code: String,
35
    /// i64 as time tick from Epoch in milliseconds.
36
    created_at: i64,
37
    /// i64 as time tick from Epoch in milliseconds.
38
    modified_at: i64,
39
    owner_id: String,
40
    /// Space-separated value such as `member_id1 member_id2`.
41
    member_ids: String,
42
    name: String,
43
    info: String,
44
}
45

            
46
/// Use "COUNT(*)" instead of "COUNT(fields...)" to simplify the implementation.
47
#[derive(sqlx::FromRow)]
48
struct CountSchema {
49
    #[sqlx(rename = "COUNT(*)")]
50
    count: i64,
51
}
52

            
53
const TABLE_NAME: &'static str = "unit";
54
const FIELDS: &'static [&'static str] = &[
55
    "unit_id",
56
    "code",
57
    "created_at",
58
    "modified_at",
59
    "owner_id",
60
    "member_ids",
61
    "name",
62
    "info",
63
];
64
const TABLE_INIT_SQL: &'static str = "\
65
    CREATE TABLE IF NOT EXISTS unit (\
66
    unit_id TEXT NOT NULL UNIQUE,\
67
    code TEXT NOT NULL UNIQUE,\
68
    created_at INTEGER NOT NULL,\
69
    modified_at INTEGER NOT NULL,\
70
    owner_id TEXT NOT NULL,\
71
    member_ids TEXT NOT NULL,\
72
    name TEXT NOT NULL,\
73
    info TEXT,\
74
    PRIMARY KEY (unit_id))";
75

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

            
85
#[async_trait]
86
impl UnitModel for Model {
87
48
    async fn init(&self) -> Result<(), Box<dyn StdError>> {
88
48
        let _ = sqlx::query(TABLE_INIT_SQL)
89
48
            .execute(self.conn.as_ref())
90
96
            .await?;
91
48
        Ok(())
92
96
    }
93

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

            
97
43
        let result: Result<CountSchema, sqlx::Error> = sqlx::query_as(sql.as_str())
98
43
            .fetch_one(self.conn.as_ref())
99
86
            .await;
100

            
101
43
        let row = match result {
102
            Err(e) => return Err(Box::new(e)),
103
43
            Ok(row) => row,
104
43
        };
105
43
        Ok(row.count as u64)
106
86
    }
107

            
108
    async fn list(
109
        &self,
110
        opts: &ListOptions,
111
        cursor: Option<Box<dyn Cursor>>,
112
126
    ) -> Result<(Vec<Unit>, Option<Box<dyn Cursor>>), Box<dyn StdError>> {
113
126
        let mut cursor = match cursor {
114
108
            None => Box::new(DbCursor::new()),
115
18
            Some(cursor) => cursor,
116
        };
117

            
118
126
        let mut opts = ListOptions { ..*opts };
119
126
        if let Some(offset) = opts.offset {
120
24
            opts.offset = Some(offset + cursor.offset());
121
102
        } else {
122
102
            opts.offset = Some(cursor.offset());
123
102
        }
124
126
        let opts_limit = opts.limit;
125
126
        if let Some(limit) = opts_limit {
126
80
            if limit > 0 {
127
79
                if cursor.offset() >= limit {
128
5
                    return Ok((vec![], None));
129
74
                }
130
74
                opts.limit = Some(limit - cursor.offset());
131
1
            }
132
46
        }
133
121
        let mut builder = SqlBuilder::select_from(TABLE_NAME);
134
121
        build_limit_offset(&mut builder, &opts);
135
121
        build_sort(&mut builder, &opts);
136
121
        let sql = build_list_where(&mut builder, opts.cond).sql()?;
137

            
138
121
        let mut rows = sqlx::query_as::<_, Schema>(sql.as_str()).fetch(self.conn.as_ref());
139
121

            
140
121
        let mut count: u64 = 0;
141
121
        let mut list = vec![];
142
1974
        while let Some(row) = rows.try_next().await? {
143
1881
            let _ = cursor.as_mut().try_next().await?;
144
1881
            let member_ids = row
145
1881
                .member_ids
146
1881
                .split(" ")
147
1934
                .filter_map(|x| {
148
1934
                    if x.len() > 0 {
149
1856
                        Some(x.to_string())
150
                    } else {
151
78
                        None
152
                    }
153
1934
                })
154
1881
                .collect();
155
1881
            list.push(Unit {
156
1881
                unit_id: row.unit_id,
157
1881
                code: row.code,
158
1881
                created_at: Utc.timestamp_nanos(row.created_at * 1000000),
159
1881
                modified_at: Utc.timestamp_nanos(row.modified_at * 1000000),
160
1881
                owner_id: row.owner_id,
161
1881
                member_ids,
162
1881
                name: row.name,
163
1881
                info: serde_json::from_str(row.info.as_str())?,
164
            });
165
1881
            if let Some(limit) = opts_limit {
166
1003
                if limit > 0 && cursor.offset() >= limit {
167
15
                    if let Some(cursor_max) = opts.cursor_max {
168
14
                        if (count + 1) >= cursor_max {
169
5
                            return Ok((list, Some(cursor)));
170
9
                        }
171
1
                    }
172
10
                    return Ok((list, None));
173
988
                }
174
878
            }
175
1866
            if let Some(cursor_max) = opts.cursor_max {
176
1783
                count += 1;
177
1783
                if count >= cursor_max {
178
13
                    return Ok((list, Some(cursor)));
179
1770
                }
180
83
            }
181
        }
182
93
        Ok((list, None))
183
252
    }
184

            
185
1315
    async fn get(&self, cond: &QueryCond) -> Result<Option<Unit>, Box<dyn StdError>> {
186
1315
        let sql = build_where(SqlBuilder::select_from(TABLE_NAME).fields(FIELDS), &cond).sql()?;
187

            
188
1315
        let result: Result<Schema, sqlx::Error> = sqlx::query_as(sql.as_str())
189
1315
            .fetch_one(self.conn.as_ref())
190
2626
            .await;
191

            
192
1315
        let row = match result {
193
236
            Err(e) => match e {
194
236
                sqlx::Error::RowNotFound => return Ok(None),
195
                _ => return Err(Box::new(e)),
196
            },
197
1079
            Ok(row) => row,
198
1079
        };
199
1079

            
200
1079
        let member_ids = row
201
1079
            .member_ids
202
1079
            .split(" ")
203
1454
            .filter_map(|x| {
204
1454
                if x.len() > 0 {
205
1446
                    Some(x.to_string())
206
                } else {
207
8
                    None
208
                }
209
1454
            })
210
1079
            .collect();
211
1079
        Ok(Some(Unit {
212
1079
            unit_id: row.unit_id,
213
1079
            code: row.code,
214
1079
            created_at: Utc.timestamp_nanos(row.created_at * 1000000),
215
1079
            modified_at: Utc.timestamp_nanos(row.modified_at * 1000000),
216
1079
            owner_id: row.owner_id,
217
1079
            member_ids,
218
1079
            name: row.name,
219
1079
            info: serde_json::from_str(row.info.as_str())?,
220
        }))
221
2630
    }
222

            
223
1359
    async fn add(&self, unit: &Unit) -> Result<(), Box<dyn StdError>> {
224
1359
        let info = match serde_json::to_string(&unit.info) {
225
            Err(_) => quote("{}"),
226
1359
            Ok(value) => quote(value.as_str()),
227
        };
228
1359
        let values = vec![
229
1359
            quote(unit.unit_id.as_str()),
230
1359
            quote(unit.code.as_str()),
231
1359
            unit.created_at.timestamp_millis().to_string(),
232
1359
            unit.modified_at.timestamp_millis().to_string(),
233
1359
            quote(unit.owner_id.as_str()),
234
1359
            quote(unit.member_ids.join(" ")),
235
1359
            quote(unit.name.as_str()),
236
1359
            info,
237
1359
        ];
238
1359
        let sql = SqlBuilder::insert_into(TABLE_NAME)
239
1359
            .fields(FIELDS)
240
1359
            .values(&values)
241
1359
            .sql()?;
242
1359
        let _ = sqlx::query(sql.as_str())
243
1359
            .execute(self.conn.as_ref())
244
2714
            .await?;
245
1357
        Ok(())
246
2718
    }
247

            
248
19
    async fn del(&self, cond: &QueryCond) -> Result<(), Box<dyn StdError>> {
249
19
        let sql = build_where(&mut SqlBuilder::delete_from(TABLE_NAME), cond).sql()?;
250
19
        let _ = sqlx::query(sql.as_str())
251
19
            .execute(self.conn.as_ref())
252
38
            .await?;
253
19
        Ok(())
254
38
    }
255

            
256
    async fn update(
257
        &self,
258
        cond: &UpdateQueryCond,
259
        updates: &Updates,
260
15
    ) -> Result<(), Box<dyn StdError>> {
261
15
        let sql = match build_update_where(&mut SqlBuilder::update_table(TABLE_NAME), cond, updates)
262
        {
263
1
            None => return Ok(()),
264
14
            Some(builder) => builder.sql()?,
265
        };
266
14
        let _ = sqlx::query(sql.as_str())
267
14
            .execute(self.conn.as_ref())
268
28
            .await?;
269
14
        Ok(())
270
30
    }
271
}
272

            
273
impl DbCursor {
274
    /// To create the cursor instance.
275
108
    pub fn new() -> Self {
276
108
        DbCursor { offset: 0 }
277
108
    }
278
}
279

            
280
#[async_trait]
281
impl Cursor for DbCursor {
282
1881
    async fn try_next(&mut self) -> Result<Option<Unit>, Box<dyn StdError>> {
283
1881
        self.offset += 1;
284
1881
        Ok(None)
285
3762
    }
286

            
287
1282
    fn offset(&self) -> u64 {
288
1282
        self.offset
289
1282
    }
290
}
291

            
292
/// Transforms query conditions to the SQL builder.
293
1334
fn build_where<'a>(builder: &'a mut SqlBuilder, cond: &QueryCond<'a>) -> &'a mut SqlBuilder {
294
1334
    if let Some(value) = cond.unit_id {
295
1309
        builder.and_where_eq("unit_id", quote(value));
296
1309
    }
297
1334
    if let Some(value) = cond.code {
298
24
        builder.and_where_eq("code", quote(value));
299
1310
    }
300
1334
    if let Some(value) = cond.owner_id {
301
275
        builder.and_where_eq("owner_id", quote(value));
302
1059
    }
303
1334
    if let Some(value) = cond.member_id {
304
434
        // Use LIKE because one ID will not be part of another ID.
305
434
        build_where_like(builder, "member_ids", value);
306
900
    }
307
1334
    builder
308
1334
}
309

            
310
/// Transforms query conditions to the SQL builder.
311
164
fn build_list_where<'a>(
312
164
    builder: &'a mut SqlBuilder,
313
164
    cond: &ListQueryCond<'a>,
314
164
) -> &'a mut SqlBuilder {
315
164
    if let Some(value) = cond.owner_id {
316
44
        builder.and_where_eq("owner_id", quote(value));
317
120
    }
318
164
    if let Some(value) = cond.member_id {
319
78
        // Use LIKE because one ID will not be part of another ID.
320
78
        build_where_like(builder, "member_ids", value);
321
86
    }
322
164
    if let Some(value) = cond.unit_id {
323
6
        builder.and_where_eq("unit_id", quote(value));
324
158
    }
325
164
    if let Some(value) = cond.code_contains {
326
41
        build_where_like(builder, "code", value.to_lowercase().as_str());
327
123
    }
328
164
    if let Some(value) = cond.name_contains {
329
8
        build_where_like(builder, "name", value.to_lowercase().as_str());
330
156
    }
331
164
    builder
332
164
}
333

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

            
351
/// Transforms model options to the SQL builder.
352
121
fn build_sort<'a>(builder: &'a mut SqlBuilder, opts: &ListOptions) -> &'a mut SqlBuilder {
353
121
    if let Some(sort_cond) = opts.sort.as_ref() {
354
100
        for cond in sort_cond.iter() {
355
100
            let key = match cond.key {
356
8
                SortKey::CreatedAt => "created_at",
357
6
                SortKey::ModifiedAt => "modified_at",
358
78
                SortKey::Code => "code",
359
8
                SortKey::Name => "name",
360
            };
361
100
            builder.order_by(key, !cond.asc);
362
        }
363
22
    }
364
121
    builder
365
121
}
366

            
367
/// Transforms query conditions and the model object to the SQL builder.
368
15
fn build_update_where<'a>(
369
15
    builder: &'a mut SqlBuilder,
370
15
    cond: &UpdateQueryCond<'a>,
371
15
    updates: &Updates,
372
15
) -> Option<&'a mut SqlBuilder> {
373
15
    let mut count = 0;
374
15
    if let Some(value) = updates.modified_at.as_ref() {
375
14
        builder.set("modified_at", value.timestamp_millis());
376
14
        count += 1;
377
14
    }
378
15
    if let Some(value) = updates.owner_id.as_ref() {
379
8
        builder.set("owner_id", quote(value));
380
8
        count += 1;
381
8
    }
382
15
    if let Some(value) = updates.member_ids.as_ref() {
383
8
        builder.set("member_ids", quote(value.join(" ")));
384
8
        count += 1;
385
8
    }
386
15
    if let Some(value) = updates.name.as_ref() {
387
10
        builder.set("name", quote(value));
388
10
        count += 1;
389
10
    }
390
15
    if let Some(value) = updates.info {
391
10
        match serde_json::to_string(value) {
392
            Err(_) => {
393
                builder.set("info", quote("{}"));
394
            }
395
10
            Ok(value) => {
396
10
                builder.set("info", quote(value));
397
10
            }
398
        }
399
10
        count += 1;
400
5
    }
401
15
    if count == 0 {
402
1
        return None;
403
14
    }
404
14

            
405
14
    builder.and_where_eq("unit_id", quote(cond.unit_id));
406
14
    Some(builder)
407
15
}