rust-cli-pomodoro 1.4.6

rust-cli-pomodoro manages your time!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
use chrono::SecondsFormat;
use gluesql::core::ast_builder::{table, Build};
use gluesql::prelude::{Glue, MemoryStorage, Payload};
use std::sync::{Arc, Mutex};

use crate::ArcGlue;
use crate::{archived_notification::ArchivedNotification, notification::Notification};

pub fn get_memory_glue() -> Glue<MemoryStorage> {
    let storage = MemoryStorage::default();

    Glue::new(storage)
}

pub async fn initialize(glue: Arc<Mutex<Glue<MemoryStorage>>>) {
    let mut glue = glue.lock().unwrap();

    let sql_stmts = vec![
        table("notifications")
            .drop_table_if_exists()
            .build()
            .unwrap(),
        table("notifications")
            .create_table()
            .add_column("id INTEGER")
            .add_column("description TEXT")
            .add_column("work_time INTEGER")
            .add_column("break_time INTEGER")
            .add_column("created_at TIMESTAMP")
            .add_column("work_expired_at TIMESTAMP")
            .add_column("break_expired_at TIMESTAMP")
            .build()
            .unwrap(),
        table("archived_notifications")
            .drop_table_if_exists()
            .build()
            .unwrap(),
        table("archived_notifications")
            .create_table()
            .add_column("id INTEGER")
            .add_column("description TEXT")
            .add_column("work_time INTEGER")
            .add_column("break_time INTEGER")
            .add_column("created_at TIMESTAMP")
            .add_column("work_expired_at TIMESTAMP")
            .add_column("break_expired_at TIMESTAMP")
            .build()
            .unwrap(),
    ];

    for stmt in sql_stmts {
        let output = glue.execute_stmt(&stmt).unwrap();
        debug!("output: {:?}", output);
    }
}

//TODO(young): Handle error
pub async fn create_notification(glue: ArcGlue, notification: &Notification) {
    let mut glue = glue.lock().unwrap();

    let (id, desc, work_time, break_time, created_at, w_expired_at, b_expired_at) =
        notification.get_values();

    let sql = format!(
        r#"
        INSERT INTO notifications VALUES ({}, '{}', {}, {}, '{}', '{}', '{}');
    "#,
        id,
        desc,
        work_time,
        break_time,
        created_at.to_rfc3339_opts(SecondsFormat::Millis, true),
        w_expired_at.to_rfc3339_opts(SecondsFormat::Millis, true),
        b_expired_at.to_rfc3339_opts(SecondsFormat::Millis, true)
    );

    debug!("create sql: {}", sql);

    let output = glue.execute(sql.as_str()).unwrap();
    debug!("output: {:?}", output);
}

pub async fn read_last_expired_notification(glue: ArcGlue) -> Option<Notification> {
    let mut glue = glue.lock().unwrap();

    let sql = String::from(
        r#"
        SELECT * FROM notifications ORDER BY break_expired_at DESC, work_expired_at DESC LIMIT 1;
        "#,
    );
    debug!("sql: {:?}", sql);

    let output = glue.execute(sql.as_str()).unwrap().swap_remove(0);
    debug!("output: {:?}", output);

    match output {
        Payload::Select {
            labels: _,
            mut rows,
        } => {
            if rows.is_empty() {
                None
            } else {
                Some(Notification::convert_to_notification(rows.swap_remove(0)))
            }
        }
        _ => {
            panic!("no such case!");
        }
    }
}

pub async fn read_notification(glue: ArcGlue, id: u16) -> Option<Notification> {
    let mut glue = glue.lock().unwrap();

    let sql_stmt = table("notifications")
        .select()
        .filter(format!("id = {}", id).as_str())
        .build()
        .unwrap();
    debug!("sql_stmt: {:?}", sql_stmt);

    let output = glue.execute_stmt(&sql_stmt).unwrap();
    debug!("output: {:?}", output);

    match output {
        Payload::Select {
            labels: _,
            mut rows,
        } => {
            if rows.is_empty() {
                None
            } else {
                Some(Notification::convert_to_notification(rows.swap_remove(0)))
            }
        }
        _ => {
            panic!("no such case!");
        }
    }
}

pub async fn list_notification(glue: ArcGlue) -> Vec<Notification> {
    let mut glue = glue.lock().unwrap();

    let sql_stmt = table("notifications").select().build().unwrap();

    let output = glue.execute_stmt(&sql_stmt).unwrap();
    debug!("output: {:?}", output);

    match output {
        Payload::Select { labels: _, rows } => rows
            .into_iter()
            .map(Notification::convert_to_notification)
            .collect(),
        _ => {
            panic!("no such case!");
        }
    }
}

pub async fn list_archived_notification(glue: ArcGlue) -> Vec<ArchivedNotification> {
    let mut glue = glue.lock().unwrap();

    let sql = "SELECT * FROM archived_notifications ORDER BY id DESC;";

    let output = glue.execute(sql).unwrap().swap_remove(0);
    debug!("output: {:?}", output);

    match output {
        Payload::Select { labels: _, rows } => rows
            .into_iter()
            // TODO(young): As of now archived_notifications schema is same as notifications table
            .map(Notification::convert_to_notification)
            .map(ArchivedNotification::from)
            .collect(),
        _ => {
            panic!("no such case!");
        }
    }
}

pub async fn delete_and_archive_notification(glue: ArcGlue, id: u16) {
    archive_notification(glue.clone(), id).await;
    delete_notification(glue.clone(), id).await;
}

//TODO(young): Handle error?
pub async fn delete_notification(glue: ArcGlue, id: u16) {
    let mut glue = glue.lock().unwrap();

    // check if notification exists. It's okay. glue executes commands sequentially as of now.
    let sql_stmt = table("notifications")
        .select()
        .filter(format!("id = {}", id).as_str())
        .build()
        .unwrap();
    debug!("sql_stmt: {:?}", sql_stmt);

    let output = glue.execute_stmt(&sql_stmt).unwrap();
    debug!("output: {:?}", output);

    let sql_stmt = table("notifications")
        .delete()
        .filter(format!("id = {}", id).as_str())
        .build()
        .unwrap();
    debug!("delete sql_stmt: {:?}", sql_stmt);

    let output = glue.execute_stmt(&sql_stmt).unwrap();
    debug!("output: {:?}", output);
}

//TODO(young): Handle error?
pub async fn archive_notification(glue: ArcGlue, id: u16) {
    let mut glue = glue.lock().unwrap();

    let sql = format!(
        r#"
    INSERT INTO archived_notifications
    SELECT * FROM notifications WHERE id = {};
    "#,
        id
    );

    debug!("sql: {:?}", sql);

    let output = glue.execute(sql.as_str()).unwrap();
    debug!("output: {:?}", output);
}

pub async fn archive_all_notification(glue: ArcGlue) {
    let mut glue = glue.lock().unwrap();

    let sql = r#"
    INSERT INTO archived_notifications
    SELECT * FROM notifications;
    "#;

    debug!("archive all sql: {}", sql);

    let output = glue.execute(sql).unwrap();
    debug!("output: {:?}", output);
}

pub async fn delete_all_archived_notification(glue: ArcGlue) {
    let mut glue = glue.lock().unwrap();

    let sql = r#"
    DELETE FROM archived_notifications;
    "#;

    debug!("delete all sql: {}", sql);

    let output = glue.execute(sql).unwrap();
    debug!("output: {:?}", output);
}

pub async fn delete_all_notification(glue: ArcGlue) {
    let mut glue = glue.lock().unwrap();

    let sql_stmt = table("notifications").delete().build().unwrap();
    debug!("delete sql_stmt: {:?}", sql_stmt);

    let output = glue.execute_stmt(&sql_stmt).unwrap();
    debug!("output: {:?}", output);
}

pub async fn delete_and_archive_all_notification(glue: ArcGlue) {
    archive_all_notification(glue.clone()).await;
    delete_all_notification(glue.clone()).await;
}

#[cfg(test)]
mod tests {
    use crate::notification::Notification;
    use chrono::Utc;
    use gluesql::prelude::{Payload, PayloadVariable};

    use super::{
        archive_all_notification, archive_notification, create_notification,
        delete_all_archived_notification, delete_all_notification, delete_notification,
        get_memory_glue, initialize, list_archived_notification, list_notification,
        read_last_expired_notification, read_notification,
    };
    use std::{
        panic,
        sync::{Arc, Mutex},
    };

    #[tokio::test]
    async fn test_initialize_tables() {
        let glue = Arc::new(Mutex::new(get_memory_glue()));
        initialize(glue.clone()).await;

        let sql = "SHOW TABLES;";
        let output = glue.lock().unwrap().execute(sql).unwrap().swap_remove(0);

        match output {
            Payload::ShowVariable(PayloadVariable::Tables(mut names)) => {
                names.sort();

                assert_eq!(2, names.len());
                assert_eq!("archived_notifications", names[0]);
                assert_eq!("notifications", names[1]);
            }
            _ => {
                panic!("no such case");
            }
        }
    }

    #[tokio::test]
    async fn test_create_notification() {
        let glue = Arc::new(Mutex::new(get_memory_glue()));
        initialize(glue.clone()).await;

        let now = Utc::now();
        let notification = Notification::new(0, 25, 5, now);

        create_notification(glue.clone(), &notification).await;

        let result = read_notification(glue.clone(), 0).await.unwrap();
        assert_eq!(
            0,
            result.get_id(),
            "id are different {}, {}",
            0,
            result.get_id()
        );
        assert_eq!(
            now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
            result
                .get_start_at()
                .to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
        );
    }

    #[tokio::test]
    async fn test_list_notification() {
        let glue = Arc::new(Mutex::new(get_memory_glue()));
        initialize(glue.clone()).await;

        // empty row
        let result = list_notification(glue.clone()).await;
        assert_eq!(0, result.len());

        let now = Utc::now();
        let notification = Notification::new(0, 25, 5, now);
        create_notification(glue.clone(), &notification).await;

        let notification = Notification::new(1, 30, 10, now);
        create_notification(glue.clone(), &notification).await;

        let result = list_notification(glue.clone()).await;
        assert_eq!(2, result.len());
        assert_eq!(0, result[0].get_id());
        assert_eq!(1, result[1].get_id());
    }

    #[tokio::test]
    async fn test_delete_notification() {
        let glue = Arc::new(Mutex::new(get_memory_glue()));
        initialize(glue.clone()).await;

        let now = Utc::now();
        let notification = Notification::new(0, 25, 5, now);
        create_notification(glue.clone(), &notification).await;

        delete_notification(glue.clone(), 0).await;
        let result = read_notification(glue.clone(), 0).await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_delete_all_notifications() {
        let glue = Arc::new(Mutex::new(get_memory_glue()));
        initialize(glue.clone()).await;

        let now = Utc::now();
        let notification = Notification::new(0, 25, 5, now);
        create_notification(glue.clone(), &notification).await;

        let notification = Notification::new(1, 30, 10, now);
        create_notification(glue.clone(), &notification).await;

        delete_all_notification(glue.clone()).await;
        let result = list_notification(glue.clone()).await;
        assert!(result.is_empty());
    }

    #[tokio::test]
    async fn test_archive_notification() {
        let glue = Arc::new(Mutex::new(get_memory_glue()));
        initialize(glue.clone()).await;

        let now = Utc::now();
        let notification = Notification::new(0, 25, 5, now);
        create_notification(glue.clone(), &notification).await;

        let notification = Notification::new(1, 30, 10, now);
        create_notification(glue.clone(), &notification).await;

        archive_all_notification(glue.clone()).await;

        let result = list_notification(glue.clone()).await;
        assert!(result.len() == 2);

        let result = list_archived_notification(glue.clone()).await;
        assert!(result.len() == 2);
    }

    #[tokio::test]
    async fn test_archive_all_notification() {
        let glue = Arc::new(Mutex::new(get_memory_glue()));
        initialize(glue.clone()).await;

        let now = Utc::now();
        let notification = Notification::new(0, 25, 5, now);
        create_notification(glue.clone(), &notification).await;

        archive_notification(glue.clone(), 0).await;

        let result = list_notification(glue.clone()).await;
        assert!(result.len() == 1);

        let result = list_archived_notification(glue.clone()).await;
        assert!(result.len() == 1);
    }

    #[tokio::test]
    async fn test_delete_all_archived_notification() {
        let glue = Arc::new(Mutex::new(get_memory_glue()));
        initialize(glue.clone()).await;

        let now = Utc::now();
        let notification = Notification::new(0, 25, 5, now);
        create_notification(glue.clone(), &notification).await;

        archive_notification(glue.clone(), 0).await;

        let result = list_archived_notification(glue.clone()).await;
        assert!(result.len() == 1);

        delete_all_archived_notification(glue.clone()).await;

        let result = list_archived_notification(glue.clone()).await;
        assert!(result.len() == 0);
    }

    #[tokio::test]
    async fn test_read_last_expired_notification() {
        let glue = Arc::new(Mutex::new(get_memory_glue()));
        initialize(glue.clone()).await;

        let now = Utc::now();
        let notification = Notification::new(0, 25, 5, now);
        create_notification(glue.clone(), &notification).await;

        let notification = Notification::new(1, 30, 10, now);
        create_notification(glue.clone(), &notification).await;

        let result = read_last_expired_notification(glue.clone()).await;
        assert!(result.is_some());
        assert_eq!(1, result.unwrap().get_id());
    }
}