comment_app_backend 0.1.3

Serves comments through Restful APIs
Documentation
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
// db.rs
// database related functions are implemented here

use std::fs::create_dir;
use std::path::Path;
use std::sync::Arc;
use tokio::sync::Mutex;

use rusqlite::{Connection, named_params, Result, Row};
use rusqlite::NO_PARAMS;
use log::*;

use crate::models::comment::Comment;
use crate::models::status::Status;
use crate::models::reply::Reply;
use crate::models::upvote::Upvote;
use crate::models::downvote::Downvote;

pub type DbConn = Arc<Mutex<Connection>>;

// database connectivity
pub fn conn() -> DbConn {
    //debug!("db::conn().................<< called up");
    let folder = super::config("db_folder");
    let filename = super::config("db_filename");
    let db_init_needed = dir_created(&folder) || file_missing(&folder, &filename);
    let conn = Connection::open( file_path_string(&folder, &filename) ).unwrap(); // creates db if it is missing and then, opens a connection
    if db_init_needed {
        debug!("starting db init.......................");
        init_db(&conn); // database does not exist, then initialize it
    }
    Arc::new(Mutex::new(conn))
}

// database setup
fn init_db(conn: &Connection) {
    match create_comment_table(conn) {
        Ok(count) => debug!("{:?} comment table is created", count),
        Err(message) => error!("{:?} occurred in create comment table", message),
    }
    match create_archive_comment_table(conn) {
        Ok(count) => debug!("{:?} archive comment table is created", count),
        Err(message) => error!("{:?} occurred in create archive comment table", message),
    }
    match create_reply_table(conn) {
        Ok(count) => debug!("{:?} reply table is created", count),
        Err(message) => error!("{:?} occurred in create reply table", message),
    }
    match create_archive_reply_table(conn) {
        Ok(count) => debug!("{:?} reply table is created", count),
        Err(message) => error!("{:?} occurred in create reply table", message),
    }
    match create_upvote_table(conn) {
        Ok(count) => debug!("{:?} upvote table is created", count),
        Err(message) => error!("{:?} occurred in create upvote table", message),
    }    
    match create_archive_upvote_table(conn) {
        Ok(count) => debug!("{:?} archive upvote table is created", count),
        Err(message) => error!("{:?} occurred in create archive upvote table", message),
    }
    match create_downvote_table(conn) {
        Ok(count) => debug!("{:?} downvote table is created", count),
        Err(message) => error!("{:?} occurred in create downvote table", message),
    }    
    match create_archive_downvote_table(conn) {
        Ok(count) => debug!("{:?} archive downvote table is created", count),
        Err(message) => error!("{:?} occurred in create archive downvote table", message),
    }
    debug!("Database initialized...");
}

// database folder and file
fn dir_created(folder: &str) -> bool {
    if Path::new(&folder).is_dir() {
        return false;
    }
    debug!("{} folder is CREATED", &folder);
    create_dir(&folder).unwrap();
    true
}
fn file_missing(folder: &str, filename: &str) -> bool {
    let path = file_path_string(folder, filename);
    !Path::new(&path).is_file()
}
fn file_path_string(folder: &str, filename: &str) -> String {
    folder.to_owned() + &"/".to_string() + &filename
}

// Table(s) creation
fn create_comment_table(conn: &Connection) -> Result<usize> {
    let count = conn.execute(
        "create table if not exists comment(
            id INTEGER PRIMARY KEY,
            message TEXT,
            anonymous INTEGER,
            status TEXT,
            remarks TEXT,
            unique_id TEXT UNIQUE,
            user_id TEXT,
            created_on TEXT,
            updated_on TEXT,
            deleted_on TEXT
        )", 
        NO_PARAMS,)?;
    Ok(count)
}
fn create_archive_comment_table(conn: &Connection) -> Result<usize> {
    let count = conn.execute(
        "create table if not exists archive_comment(
            id INTEGER PRIMARY KEY,
            message TEXT,
            anonymous INTEGER,
            status TEXT,
            remarks TEXT,
            unique_id TEXT,
            user_id TEXT,
            created_on TEXT,
            updated_on TEXT,
            deleted_on TEXT
        )", 
        NO_PARAMS,)?;
    Ok(count)
}
fn create_reply_table(conn: &Connection) -> Result<usize> {
    let count = conn.execute(
        "create table if not exists reply(
            id INTEGER PRIMARY KEY,
            message TEXT,
            anonymous INTEGER,
            status TEXT,
            remarks TEXT,
            unique_id TEXT UNIQUE,
            parent_id TEXT,
            comment_id TEXT,
            level INTEGER,
            user_id TEXT,
            created_on TEXT,
            updated_on TEXT,
            deleted_on TEXT
        )", 
        NO_PARAMS,)?;
    Ok(count)
}
fn create_archive_reply_table(conn: &Connection) -> Result<usize> {
    let count = conn.execute(
        "create table if not exists archive_reply(
            id INTEGER PRIMARY KEY,
            message TEXT,
            anonymous INTEGER,
            status TEXT,
            remarks TEXT,
            unique_id TEXT,
            parent_id TEXT,
            comment_id TEXT,
            level INTEGER,
            user_id TEXT,
            created_on TEXT,
            updated_on TEXT,
            deleted_on TEXT
        )", 
        NO_PARAMS,)?;
    Ok(count)
}
fn create_upvote_table(conn: &Connection) -> Result<usize> {
    let count = conn.execute(
        "create table if not exists upvote(
            id INTEGER PRIMARY KEY,
            comment_id TEXT,
            user_id TEXT,
            remarks TEXT,
            created_on TEXT,
            updated_on TEXT,
            deleted_on TEXT,
            UNIQUE(comment_id, user_id)
        )", 
        NO_PARAMS,)?;
    Ok(count)
}
fn create_archive_upvote_table(conn: &Connection) -> Result<usize> {
    let count = conn.execute(
        "create table if not exists archive_upvote(
            id INTEGER PRIMARY KEY,
            comment_id TEXT,
            user_id TEXT,
            remarks TEXT,
            created_on TEXT,
            updated_on TEXT,
            deleted_on TEXT
        )", 
        NO_PARAMS,)?;
    Ok(count)
}
fn create_downvote_table(conn: &Connection) -> Result<usize> {
    let count = conn.execute(
        "create table if not exists downvote(
            id INTEGER PRIMARY KEY,
            comment_id TEXT,
            user_id TEXT,
            remarks TEXT,
            created_on TEXT,
            updated_on TEXT,
            deleted_on TEXT,
            UNIQUE(comment_id, user_id)
        )", 
        NO_PARAMS,)?;
    Ok(count)
}
fn create_archive_downvote_table(conn: &Connection) -> Result<usize> {
    let count = conn.execute(
        "create table if not exists archive_downvote(
            id INTEGER PRIMARY KEY,
            comment_id TEXT,
            user_id TEXT,
            remarks TEXT,
            created_on TEXT,
            updated_on TEXT,
            deleted_on TEXT
        )", 
        NO_PARAMS,)?;
    Ok(count)
}

// Actions on Comment table
fn sql_to_add_comment() -> String {
    "INSERT INTO comment (
        message, 
        anonymous,
        status, 
        remarks, 
        unique_id, 
        user_id,
        created_on
    ) VALUES (
        :message,
        :anonymous,
        :status,
        :remarks,
        :unique_id,
        :user_id,
        :created_on
    )".to_string()
}

pub async fn add_comment(comment: &Comment, db_conn: DbConn) -> Result<usize> {
    debug!("add_comment({:?})........................", comment);
    let conn = db_conn.lock().await;
    let row_count = conn.execute_named(
        &sql_to_add_comment(),
        named_params!{
            ":message": comment.message,
            ":anonymous": comment.anonymous,
            ":status": comment.status.to_string(),
            ":remarks": comment.remarks,
            ":unique_id": comment.unique_id,
            ":user_id": comment.user_id,
            ":created_on": comment.created_on
        } 
    )?;
    Ok(row_count)
}

pub async fn _get_comments(status: &str, db_conn: DbConn) -> Result<Vec<Comment>> {
    debug!("get_comments({:?})..........................<<", &status);
    let conn = db_conn.lock().await;
    let mut stmt = conn.prepare(
        "SELECT 
            message, anonymous, status, remarks, unique_id, 
            user_id, created_on, updated_on, deleted_on 
         FROM comment 
         WHERE status = :status
         ORDER BY unique_id ASC")?;
    let rows = stmt.query_map_named(
        &[ (":status", &status.to_string()) ], 
        |row| extract_comment_data(row) 
    )?;
    let mut results = Vec::new();
    for row in rows {
        results.push(row?);
    }
    debug!("comments are: {:?}", results);
    Ok(results)
}
fn sql_to_get_all_comments() -> String {
    "SELECT 
        message, anonymous, status, remarks, unique_id, 
        user_id, created_on, updated_on, deleted_on 
    FROM comment 
    WHERE deleted_on is null OR deleted_on = ''
    ORDER BY unique_id ASC".to_string()
}
pub async fn get_all_comments(db_conn: DbConn) -> Result<Vec<Comment>> {
    debug!("get_all_comments()..........................<<");
    let conn = db_conn.lock().await;
    let mut stmt = conn.prepare( &sql_to_get_all_comments() )?;
    let rows = stmt.query_map_named(
        &[], 
        |row| extract_comment_data(row) 
    )?;
    let mut results = Vec::new();
    for row in rows {
        results.push(row?);
    }
    debug!("all comments are: {:?}", results);
    Ok(results)
}
fn sql_to_get_more_comments() -> String {
    "SELECT 
        message, anonymous, status, remarks, unique_id, 
        user_id, created_on, updated_on, deleted_on 
    FROM comment 
    WHERE deleted_on is null OR deleted_on = ''
    ORDER BY unique_id ASC
    LIMIT :count".to_string()
}
pub async fn get_more_comments(count: usize, db_conn: DbConn) -> Result<Vec<Comment>> {
    debug!("get_more_comments()..........................<<");
    let conn = db_conn.lock().await;
    let mut stmt = conn.prepare( &sql_to_get_more_comments() )?;
    let rows = stmt.query_map_named(
        &[ ( ":count", &count.to_string() )], 
        |row| extract_comment_data(row) 
    )?;
    let mut results = Vec::new();
    for row in rows {
        results.push(row?);
    }
    debug!("more comments are: {:?}", results);
    Ok(results)
}

fn extract_comment_data(row: &Row) -> Result<Comment> {
    Ok( Comment {
        message: row.get(0).unwrap_or(String::new()), // message
        anonymous: row.get(1).unwrap_or(false), // anonymous
        status: Status::from_string( row.get(2).unwrap_or(String::from("Pending")) ), // status
        remarks: row.get(3).unwrap_or(String::new()), // remarks
        unique_id: row.get(4).unwrap_or(String::new()), // unique_id
        user_id: row.get(5).unwrap_or(String::new()), // unique_id
        created_on: row.get(6).unwrap_or(String::new()), // created_on
        updated_on: row.get(7).unwrap_or(String::new()), // updated_on
        deleted_on: row.get(8).unwrap_or(String::new())  // deleted_on
    })
}
fn sql_to_update_comment() -> String {
    "UPDATE comment
    SET 
        message = :message, 
        status = :status, 
        remarks = :remarks,
        updated_on = :updated_on
    WHERE 
        unique_id = :unique_id".to_string()
}
pub async fn update_comment(comment: &Comment, db_conn: DbConn) -> Result<usize> {
    debug!("update_comment(..)...............<<");
    let conn = db_conn.lock().await;
    // archive the row before carrying out the update
    let _row_count = conn.execute_named(
        &sql_to_archive_comment(),
        &[ (":unique_id", &comment.unique_id) ] )?;
    // carry out the update now    
    let row_count = conn.execute_named(
        &sql_to_update_comment(),
        &[ (":message", &comment.message),
           (":status", &comment.status.to_string()),
           (":remarks", &comment.remarks),
           (":updated_on", &comment.updated_on),
           (":unique_id", &comment.unique_id) ]
    )?;
    Ok(row_count)
}

fn sql_to_update_comment_status() -> String {
    "UPDATE comment
    SET 
        status = :status, 
        remarks = 'status updated',
        updated_on = :updated_on
    WHERE 
        unique_id = :unique_id".to_string()
}

pub async fn update_comment_status(status: Status, uid: String, now: String, db_conn: DbConn) -> Result<usize> {
    debug!("update_comment_status(..)...............<<");
    let conn = db_conn.lock().await;
    // archive the row before carrying out the update
    let _row_count = conn.execute_named(
        &sql_to_archive_comment(),
        &[ (":unique_id", &uid) ] )?;
    // carry out the update now    
    let row_count = conn.execute_named(
        &sql_to_update_comment_status(),
        &[
            (":status", &status.to_string()),
            (":updated_on", &now),
            (":unique_id", &uid),
        ]
    )?;
    Ok(row_count)
}
fn sql_to_update_comment_message() -> String {
    "UPDATE comment
        SET 
            message = :message, 
            remarks = 'message updated',
            updated_on = :updated_on
        WHERE 
            unique_id = :unique_id".to_string()
}
pub async fn update_comment_message(msg: String, uid: String, now: String, db_conn: DbConn) -> Result<usize> {
    debug!("update_comment_message(..)...............<<");
    let conn = db_conn.lock().await;
    // archive the row before carrying out the update
    let _row_count = conn.execute_named(
        &sql_to_archive_comment(),
        &[ (":unique_id", &uid) ] )?;
    // carry out the update now    
    let row_count = conn.execute_named(
        &sql_to_update_comment_message(),
        &[ (":message", &msg),
           (":updated_on", &now),
           (":unique_id", &uid) ]
    )?;
    Ok(row_count)
}

fn comment_deleted_on() -> String {
    "UPDATE comment
    SET remarks = 'deleted', deleted_on = :deleted_on
    WHERE unique_id = :unique_id".to_string()
}
fn replies_deleted_on() -> String { // marks to deleted on all replies to a comment
    "UPDATE reply
    SET remarks = 'deleted', deleted_on = :deleted_on
    WHERE comment_id = :comment_id".to_string()
}

pub async fn delete_comment(uid: &str, now: String, db_conn: DbConn) -> Result<usize> {
    debug!("delete comment(..)................<<");
    let conn = db_conn.lock().await;
    // step 1a: update deleted on field in comment table
    let _row_count = conn.execute_named(
        &comment_deleted_on(),
        &[ (":deleted_on", &now), (":unique_id", &uid) ] )?;
    // step 1b: update deleted on field in reply table
    let _row_count = conn.execute_named(
        &replies_deleted_on(),
        &[ (":deleted_on", &now), (":comment_id", &uid) ] )?;
    // step 2a: archive the row to be deleted into archive_comment table
    let _row_count = conn.execute_named(
        &sql_to_archive_comment(),
        &[ (":unique_id", &uid) ] )?;
    // step 2b: archive the row to be deleted into archive_reply table
    let _row_count = conn.execute_named(
        &sql_to_archive_all_replies_on_comment(),
        &[ (":comment_id", &uid) ] )?;
    // step 3a: actual delete on replies
    let _result = conn.execute_named(
        "DELETE FROM reply WHERE comment_id = :uid",
        &[ (":uid", &uid) ] )?;

    // step 3b: actual delete on comment 
    let result = conn.execute_named(
        "DELETE FROM comment WHERE unique_id = :uid",
        &[ (":uid", &uid) ] )?;

    Ok(result)
}
fn sql_to_get_comment() -> String {
    "SELECT
        message, anonymous, status, remarks, unique_id, 
        user_id, created_on, updated_on, deleted_on         
    FROM comment 
    WHERE unique_id = :uid".to_string()
}
pub async fn get_comment(uid: &str, db_conn: DbConn) -> Result<Comment> {
    debug!("get_comment({}).....................<<", uid);
    let conn = db_conn.lock().await;
    let result = conn.query_row_named(
        &sql_to_get_comment(),
        &[ (":uid", &uid) ],
        |row| extract_comment_data(row)
    )?;
    debug!("Comment is: {:?}", result);
    Ok(result)
}

fn sql_to_get_comments_total() -> String {
    "SELECT count(*)
    FROM comment 
    WHERE deleted_on is null OR deleted_on = ''
    ORDER BY unique_id ASC".to_string()
}
pub async fn get_comments_total(db_conn: DbConn) -> Result<u32> {
    debug!("get_comments_total().....................<<");
    let conn = db_conn.lock().await;
    let result = conn.query_row_named(
        &sql_to_get_comments_total(),
        &[ ],
        |row| row.get(0)
    )?;
    debug!("Total comments are: {:?}", result);
    Ok(result)
}

// Actions on Archive Comment table
pub fn sql_to_archive_comment() -> String {
    "INSERT INTO archive_comment (
            message, 
            anonymous,
            status, 
            remarks, 
            unique_id, 
            user_id,
            created_on,
            updated_on,
            deleted_on
        ) 
        SELECT 
            message,
            anonymous,
            status,
            remarks,
            unique_id,
            user_id,
            created_on,
            updated_on,
            deleted_on
        FROM
            comment
        WHERE 
            unique_id = :unique_id".to_string()
}

// Actions on Reply table
fn sql_to_add_reply() -> String {
    "INSERT INTO reply (
        message, 
        anonymous,
        status, 
        remarks, 
        unique_id, 
        parent_id,
        comment_id,
        level,
        user_id,
        created_on
    ) VALUES (
        :message,
        :anonymous,
        :status,
        :remarks,
        :unique_id,
        :parent_id,
        :comment_id,
        :level,
        :user_id,
        :created_on
    )".to_string()
}
pub async fn add_reply(reply: &Reply, db_conn: DbConn) -> Result<usize> {
    debug!("add_reply({:?})........................", reply);
    let conn = db_conn.lock().await;
    let row_count = conn.execute_named(
        &sql_to_add_reply(),
        named_params!{
            ":message": reply.message,
            ":anonymous": reply.anonymous,
            ":status": reply.status.to_string(),
            ":remarks": reply.remarks,
            ":unique_id": reply.unique_id,
            ":parent_id": reply.parent_id,
            ":comment_id": reply.comment_id,
            ":level": reply.level,
            ":user_id": reply.user_id,
            ":created_on": reply.created_on
        } 
    )?;
    Ok(row_count)
}
fn sql_to_get_replies() -> String {
    "SELECT 
        message, anonymous, status, remarks, unique_id, 
        parent_id, comment_id, level, user_id, created_on, updated_on, deleted_on 
    FROM reply 
    WHERE comment_id = :comment_id 
        AND status = :status 
        AND ( deleted_on is null OR deleted_on = '')
    ORDER BY unique_id ASC".to_string()
}
pub async fn get_replies(comment_id: String, status: &str, db_conn: DbConn) -> Result<Vec<Reply>> {
    debug!("get_replies({:?}, {:?})..........................<<", &comment_id, &status);
    let conn = db_conn.lock().await;
    let mut stmt = conn.prepare( &sql_to_get_replies() )?;
    let rows = stmt.query_map_named(
        &[ (":comment_id", &comment_id),
           (":status", &status.to_string()) ], 
        |row| extract_reply_data(row) 
    )?;
    let mut results = Vec::new();
    for row in rows {
        results.push(row?);
    }
    debug!("replies are: {:?}", results);
    Ok(results)
}

fn extract_reply_data(row: &Row) -> Result<Reply> {
    Ok( Reply {
        message: row.get(0).unwrap_or(String::new()), // message
        anonymous: row.get(1).unwrap_or(false), // anonymous
        status: Status::from_string( row.get(2).unwrap_or(String::from("Pending")) ), // status
        remarks: row.get(3).unwrap_or(String::new()), // remarks
        unique_id: row.get(4).unwrap_or(String::new()), // unique_id
        parent_id: row.get(5).unwrap_or(String::new()), // parent_id
        comment_id: row.get(6).unwrap_or(String::new()), // comment_id
        level: row.get(7).unwrap_or(0), // level
        user_id: row.get(8).unwrap_or(String::new()), // unique_id
        created_on: row.get(9).unwrap_or(String::new()), // created_on
        updated_on: row.get(10).unwrap_or(String::new()), // updated_on
        deleted_on: row.get(11).unwrap_or(String::new())  // deleted_on
    })
}
fn sql_to_update_reply() -> String {
    "UPDATE reply
    SET 
        message = :message, 
        status = :status, 
        remarks = :remarks,
        updated_on = :updated_on
    WHERE 
        unique_id = :unique_id".to_string()
}
pub async fn update_reply(reply: &Reply, db_conn: DbConn) -> Result<usize> {
    debug!("update_reply(..)...............<<");

    let conn = db_conn.lock().await;
    // archive the row before carrying out the update
    let _row_count = conn.execute_named(
        &sql_to_archive_reply(),
        &[ (":unique_id", &reply.unique_id) ] )?;
    // carry out the update now    
    let row_count = conn.execute_named(
        &sql_to_update_reply(),
        &[ (":message", &reply.message),
           (":status", &reply.status.to_string()),
           (":remarks", &reply.remarks),
           (":updated_on", &reply.updated_on),
           (":unique_id", &reply.unique_id) ]
    )?;
    Ok(row_count)
}
fn sql_to_update_reply_message() -> String {
    "UPDATE reply
    SET 
        message = :message, 
        remarks = 'message updated',
        updated_on = :updated_on
    WHERE 
        unique_id = :unique_id".to_string()
}
pub async fn update_reply_message(msg: String, uid: String, now: String, db_conn: DbConn) -> Result<usize> {
    debug!("update_reply_message(..)...............<<");
    let conn = db_conn.lock().await;
    // archive the row before carrying out the update
    let _row_count = conn.execute_named(
        &sql_to_archive_reply(),
        &[ (":unique_id", &uid) ] )?;
    // carry out the update now
    let row_count = conn.execute_named(
        &sql_to_update_reply_message(),
        &[ (":message", &msg),
           (":updated_on", &now),
           (":unique_id", &uid) ]
    )?;
    Ok(row_count)
}

fn reply_deleted_on() -> String {
    "UPDATE reply
     SET remarks = 'deleted', deleted_on = :deleted_on
     WHERE unique_id = :unique_id".to_string()
}

// delete_reply removes permanently
pub async fn delete_reply(uid: &str, now: String, db_conn: DbConn) -> Result<usize> {
    debug!("delete reply(..)................<<");
    let conn = db_conn.lock().await;
    // step 1: update deleted_on field in reply table
    let _row_count = conn.execute_named(
        &reply_deleted_on(),
        &[ (":deleted_on", &now), (":unique_id", &uid) ] )?;
    // step 2: archive the row to be deleted into archive_reply
    let _row_count = conn.execute_named(
        &sql_to_archive_reply(),
        &[ (":unique_id", &uid) ] );
    // step 3: actual delete of reply
    let result = conn.execute_named(
        "DELETE FROM reply WHERE unique_id = :uid",
        &[ (":uid", &uid) ] )?;

    Ok(result)
}
fn sql_to_get_reply() -> String {
    "SELECT
        message, anonymous, status, remarks, unique_id, 
        parent_id, comment_id, level, user_id, created_on, updated_on, deleted_on         
    FROM reply 
    WHERE unique_id = :uid".to_string()
}
pub async fn get_reply(uid: &str, db_conn: DbConn) -> Result<Reply> {
    debug!("get_reply({}).....................<<", uid);
    let conn = db_conn.lock().await;
    let result = conn.query_row_named( 
        &sql_to_get_reply(),
        &[ (":uid", &uid) ],
        |row| extract_reply_data(row)
    )?;
    debug!("Reply is: {:?}", result);
    Ok(result)
}

// Actions on Archive Reply table
pub fn sql_to_archive_all_replies_on_comment() -> String {
    debug!("sql to archive all replies on comment()........................");
    "INSERT INTO archive_reply (
            message, 
            anonymous,
            status, 
            remarks, 
            unique_id, 
            parent_id,
            comment_id,
            level,
            user_id,
            created_on,
            updated_on,
            deleted_on
        ) 
        SELECT 
            message,
            anonymous,
            status,
            remarks,
            unique_id,
            parent_id,
            comment_id,
            level,
            user_id,
            created_on,
            updated_on,
            deleted_on
        FROM
            reply
        WHERE 
            comment_id = :comment_id".to_string()
}
fn sql_to_archive_reply() -> String {
    debug!("sql to archive reply()........................");
    "INSERT INTO archive_reply (
            message, 
            anonymous,
            status, 
            remarks, 
            unique_id, 
            parent_id,
            comment_id,
            level,
            user_id,
            created_on,
            updated_on,
            deleted_on
        ) 
        SELECT 
            message,
            anonymous,
            status,
            remarks,
            unique_id,
            parent_id,
            comment_id,
            level,
            user_id,
            created_on,
            updated_on,
            deleted_on
        FROM
            reply
        WHERE 
            unique_id = :unique_id".to_string()
}

// Actions on Upvote table
fn sql_to_add_upvote() -> String {
    "INSERT INTO upvote (
        comment_id, 
        user_id,
        remarks, 
        created_on
    ) VALUES (
        :comment_id,
        :user_id,
        :remarks,
        :created_on
    )".to_string()
}
pub async fn add_upvote(upvote: &Upvote, db_conn: DbConn) -> Result<usize> {
    debug!("add_upvote({:?})........................", upvote);
    let conn = db_conn.lock().await;
    let row_count = conn.execute_named(
        &sql_to_add_upvote(),
        named_params!{
            ":comment_id": upvote.comment_id,
            ":user_id": upvote.user_id,
            ":remarks": upvote.remarks,
            ":created_on": upvote.created_on
        } 
    )?;
    Ok(row_count)
}

fn upvote_deleted_on() -> String {
    "UPDATE upvote
    SET remarks = 'deleted', deleted_on = :deleted_on
    WHERE comment_id = :comment_id
        AND user_id = :user_id".to_string()
}
pub async fn delete_upvote(comment_id: &str, user_id: &str, now: String, db_conn: DbConn) -> Result<usize> {
    debug!("delete upvote(..)................<<");
    let conn = db_conn.lock().await;
    // step 1: update deleted on field in upvote table
    let _row_count = conn.execute_named(
        &upvote_deleted_on(),
        &[ (":deleted_on", &now), 
           (":comment_id", &comment_id), 
           (":user_id", &user_id) ] )?;
    // step 2: archive the row to be deleted into archive_upvote table
    let _row_count = conn.execute_named(
        &sql_to_archive_upvote(),
        &[ (":comment_id", &comment_id), 
           (":user_id", &user_id) ] )?;
    // step 3: actual delete on upvote 
    let result = conn.execute_named(
        "DELETE FROM 
            upvote 
        WHERE 
            comment_id = :comment_id 
            AND user_id = :user_id",
        &[ (":comment_id", &comment_id), 
           (":user_id", &user_id) ] )?;

    Ok(result)
}
fn sql_to_get_upvotes_total() -> String {
    "SELECT count(*)
    FROM upvote 
    WHERE (deleted_on is null OR deleted_on = '') 
    AND comment_id = :comment_id".to_string()
}
pub async fn get_upvotes_total(comment_id: &str, db_conn: DbConn) -> Result<u32> {
    debug!("get_upvotes_total({}).....................<<", &comment_id);
    let conn = db_conn.lock().await;
    let result = conn.query_row_named(
        &sql_to_get_upvotes_total(),
        &[ (":comment_id", &comment_id) ],
        |row| row.get(0)
    )?;
    debug!("Total upvotes for comment_id: {} are: {:?}", &comment_id, &result);
    Ok(result)
}

// Actions on Archive Upvote table
pub fn sql_to_archive_upvote() -> String {
    "INSERT INTO archive_upvote (
            comment_id, 
            user_id,
            remarks, 
            created_on,
            updated_on,
            deleted_on
        ) 
        SELECT 
            comment_id,
            user_id,
            remarks,
            created_on,
            updated_on,
            deleted_on
        FROM
            upvote
        WHERE 
            comment_id = :comment_id 
            AND user_id = :user_id".to_string()
}

// Actions on Downvote table
fn sql_to_add_downvote() -> String {
    "INSERT INTO downvote (
        comment_id, 
        user_id,
        remarks, 
        created_on
    ) VALUES (
        :comment_id,
        :user_id,
        :remarks,
        :created_on
    )".to_string()
}
pub async fn add_downvote(downvote: &Downvote, db_conn: DbConn) -> Result<usize> {
    debug!("add_downvote({:?})........................", downvote);
    let conn = db_conn.lock().await;
    let row_count = conn.execute_named(
        &sql_to_add_downvote(),
        named_params!{
            ":comment_id": downvote.comment_id,
            ":user_id": downvote.user_id,
            ":remarks": downvote.remarks,
            ":created_on": downvote.created_on
        } 
    )?;
    Ok(row_count)
}

fn downvote_deleted_on() -> String {
    "UPDATE downvote
    SET remarks = 'deleted', deleted_on = :deleted_on
    WHERE comment_id = :comment_id
        AND user_id = :user_id".to_string()
}
pub async fn delete_downvote(comment_id: &str, user_id: &str, now: String, db_conn: DbConn) -> Result<usize> {
    debug!("delete downvote(..)................<<");
    let conn = db_conn.lock().await;
    // step 1: update deleted on field in downvote table
    let _row_count = conn.execute_named(
        &downvote_deleted_on(),
        &[ (":deleted_on", &now), 
           (":comment_id", &comment_id), 
           (":user_id", &user_id) ] )?;
    // step 2: archive the row to be deleted into archive_downvote table
    let _row_count = conn.execute_named(
        &sql_to_archive_downvote(),
        &[ (":comment_id", &comment_id), 
           (":user_id", &user_id) ] )?;
    // step 3: actual delete on downvote 
    let result = conn.execute_named(
        "DELETE FROM 
            downvote 
        WHERE 
            comment_id = :comment_id 
            AND user_id = :user_id",
        &[ (":comment_id", &comment_id), 
           (":user_id", &user_id) ] )?;

    Ok(result)
}
fn sql_to_get_downvotes_total() -> String {
    "SELECT count(*)
    FROM downvote 
    WHERE (deleted_on is null OR deleted_on = '') 
    AND comment_id = :comment_id".to_string()
}
pub async fn get_downvotes_total(comment_id: &str, db_conn: DbConn) -> Result<u32> {
    debug!("get_downvotes_total({}).....................<<", &comment_id);
    let conn = db_conn.lock().await;
    let result = conn.query_row_named(
        &sql_to_get_downvotes_total(),
        &[ (":comment_id", &comment_id) ],
        |row| row.get(0)
    )?;
    debug!("Total downvotes for comment_id: {} are: {:?}", &comment_id, &result);
    Ok(result)
}

// Actions on Archive Downvote table
pub fn sql_to_archive_downvote() -> String {
    "INSERT INTO archive_downvote (
            comment_id, 
            user_id,
            remarks, 
            created_on,
            updated_on,
            deleted_on
        ) 
        SELECT 
            comment_id,
            user_id,
            remarks,
            created_on,
            updated_on,
            deleted_on
        FROM
            downvote
        WHERE 
            comment_id = :comment_id 
            AND user_id = :user_id".to_string()
}