aboutsummaryrefslogtreecommitdiffstats
path: root/filamento/src/db.rs
blob: 36ce7bf69c3ab0828d969ff92dea8712f2f769a8 (plain) (blame)
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
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
use std::{collections::HashSet, path::Path, sync::Arc};

use chrono::{DateTime, Utc};
use jid::JID;
use rusqlite::{Connection, OptionalExtension};
use tokio::sync::{Mutex, MutexGuard};
use uuid::Uuid;

use crate::{
    chat::{Body, Chat, Delivery, Message},
    error::{DatabaseError as Error, DatabaseOpenError},
    presence::Online,
    roster::Contact,
    user::User,
};

#[derive(Clone)]
pub struct Db {
    db: Arc<Mutex<rusqlite::Connection>>,
}

// TODO: turn into trait
impl Db {
    #[cfg(not(target_arch = "wasm32"))]
    pub async fn create_connect_and_migrate(
        path: impl AsRef<Path>,
    ) -> Result<Self, DatabaseOpenError> {
        use rusqlite::Connection;

        if let Some(dir) = path.as_ref().parent() {
            if dir.is_dir() {
            } else {
                tokio::fs::create_dir_all(dir).await?;
            }
            let _file = tokio::fs::OpenOptions::new()
                .append(true)
                .create(true)
                .open(path.as_ref())
                .await?;
        }
        let url = format!(
            "{}",
            path.as_ref()
                .to_str()
                .ok_or(DatabaseOpenError::InvalidPath)?
        );
        // let db = SqlitePool::connect(&url).await?;
        // migrate!().run(&db).await?;
        // Ok(Self { db })
        let db = Connection::open(url)?;
        db.execute_batch(include_str!("../migrations/1.sql"))?;
        Ok(Self {
            db: Arc::new(Mutex::new(db)),
        })
    }

    #[cfg(target_arch = "wasm32")]
    pub async fn create_connect_and_migrate(
        path: impl AsRef<Path>,
    ) -> Result<Self, DatabaseOpenError> {
        let db = Connection::open(path)?;
        db.execute_batch(include_str!("../migrations/1.sql"))?;
        Ok(Self {
            db: Arc::new(Mutex::new(db)),
        })
    }

    // pub(crate) fn new(db: SqlitePool) -> Self {
    //     // Self { db }
    //     Self {}
    // }
    //
    pub async fn db(&self) -> MutexGuard<'_, Connection> {
        self.db.lock().await
    }

    pub(crate) async fn create_user(&self, user: User) -> Result<(), Error> {
        {
            self.db().await.execute(
                "insert into users ( jid, nick, avatar ) values ( ?1, ?2, ?3 )",
                (user.jid, user.nick, user.avatar),
            )?;
        }
        Ok(())
    }

    pub(crate) async fn read_user(&self, user: JID) -> Result<User, Error> {
        let db = self.db().await;
        let user_opt = db
            .query_row(
                "select jid, nick, avatar from users where jid = ?1",
                [&user],
                |row| {
                    Ok(User {
                        jid: row.get(0)?,
                        nick: row.get(1)?,
                        avatar: row.get(2)?,
                    })
                },
            )
            .optional()?;
        match user_opt {
            Some(user) => Ok(user),
            None => {
                db.execute("insert into users ( jid ) values ( ?1 )", [&user])?;
                Ok(User {
                    jid: user,
                    nick: None,
                    avatar: None,
                })
            }
        }
    }

    /// returns whether or not the nickname was updated
    pub(crate) async fn delete_user_nick(&self, jid: JID) -> Result<bool, Error> {
        let rows_affected;
        {
            rows_affected = self.db().await.execute("insert into users (jid, nick) values (?1, ?2) on conflict do update set nick = ?3 where nick is not ?4", (jid, None::<String>, None::<String>, None::<String>))?;
        }
        if rows_affected > 0 {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// returns whether or not the nickname was updated
    pub(crate) async fn upsert_user_nick(&self, jid: JID, nick: String) -> Result<bool, Error> {
        let rows_affected;
        {
            rows_affected = self.db().await.execute("insert into users (jid, nick) values (?1, ?2) on conflict do update set nick = ?3 where nick is not ?4", (jid, &nick, &nick, &nick))?;
        }
        if rows_affected > 0 {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar
    pub(crate) async fn delete_user_avatar(
        &self,
        jid: JID,
    ) -> Result<(bool, Option<String>), Error> {
        let (old_avatar, rows_affected): (Option<String>, _);
        {
            let db = self.db().await;
            old_avatar = db
                .query_row("select avatar from users where jid = ?1", [&jid], |row| {
                    Ok(row.get(0)?)
                })
                .optional()?;
            rows_affected = db.execute("insert into users (jid, avatar) values (?1, ?2) on conflict do update set avatar = ?3 where avatar is not ?4", (jid, None::<String>, None::<String>, None::<String>))?;
        }
        if rows_affected > 0 {
            Ok((true, old_avatar))
        } else {
            Ok((false, old_avatar))
        }
    }

    /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar
    pub(crate) async fn upsert_user_avatar(
        &self,
        jid: JID,
        avatar: String,
    ) -> Result<(bool, Option<String>), Error> {
        let (old_avatar, rows_affected): (Option<String>, _);
        {
            let db = self.db().await;
            old_avatar = db
                .query_row("select avatar from users where jid = ?1", [&jid], |row| {
                    let avatar: Option<String> = row.get(0)?;
                    Ok(avatar)
                })
                .optional()?
                .unwrap_or_default();
            rows_affected = db.execute("insert into users (jid, avatar) values (?1, ?2) on conflict do update set avatar = ?3 where avatar is not ?4", (jid, &avatar, &avatar, &avatar))?;
        }
        if rows_affected > 0 {
            Ok((true, old_avatar))
        } else {
            Ok((false, old_avatar))
        }
    }

    // TODO: use references everywhere
    pub(crate) async fn update_user(&self, user: User) -> Result<(), Error> {
        self.db().await.execute(
            "update users set nick = ?1, avatar = ?2 where user_jid = ?1",
            (&user.nick, &user.avatar, &user.jid),
        )?;
        Ok(())
    }

    // TODO: should this be allowed? messages need to reference users. should probably only allow delete if every other thing referencing it has been deleted, or if you make clear to the user deleting a user will delete all messages associated with them.
    // pub(crate) async fn delete_user(&self, user: JID) -> Result<(), Error> {}

    /// does not create the underlying user, if underlying user does not exist, create_user() must be called separately
    pub(crate) async fn create_contact(&self, contact: Contact) -> Result<(), Error> {
        let db = self.db().await;
        db.execute(
            "insert into roster ( user_jid, name, subscription ) values ( ?1, ?2, ?3 )",
            (&contact.user_jid, &contact.name, contact.subscription),
        )?;
        for group in contact.groups {
            db.execute(
                "insert into groups (group_name) values (?1) on conflict do nothing",
                [&group],
            )?;
            db.execute(
                "insert into groups_roster (group_name, contact_jid) values (?1, ?2)",
                (group, &contact.user_jid),
            )?;
        }
        Ok(())
    }

    pub(crate) async fn read_contact(&self, contact: JID) -> Result<Contact, Error> {
        let db = self.db().await;
        let mut contact_item = db.query_row(
            "select user_jid, name, subscription from roster where user_jid = ?1",
            [&contact],
            |row| {
                Ok(Contact {
                    user_jid: row.get(0)?,
                    name: row.get(1)?,
                    subscription: row.get(2)?,
                    groups: HashSet::new(),
                })
            },
        )?;
        let groups: Result<HashSet<String>, _> = db
            .prepare("select group_name from groups_roster where contact_jid = ?1")?
            .query_map([&contact], |row| Ok(row.get(0)?))?
            .collect();
        contact_item.groups = groups?;
        Ok(contact_item)
    }

    pub(crate) async fn read_contact_opt(&self, contact: &JID) -> Result<Option<Contact>, Error> {
        let db = self.db().await;
        let contact_item = db
            .query_row(
                "select user_jid, name, subscription from roster where user_jid = ?1",
                [&contact],
                |row| {
                    Ok(Contact {
                        user_jid: row.get(0)?,
                        name: row.get(1)?,
                        subscription: row.get(2)?,
                        groups: HashSet::new(),
                    })
                },
            )
            .optional()?;
        if let Some(mut contact_item) = contact_item {
            let groups: Result<HashSet<String>, _> = db
                .prepare("select group_name from groups_roster where contact_jid = ?1")?
                .query_map([&contact], |row| Ok(row.get(0)?))?
                .collect();
            contact_item.groups = groups?;
            Ok(Some(contact_item))
        } else {
            Ok(None)
        }
    }

    /// does not update the underlying user, to update user, update_user() must be called separately
    pub(crate) async fn update_contact(&self, contact: Contact) -> Result<(), Error> {
        let db = self.db().await;
        db.execute(
            "update roster set name = ?1, subscription = ?2 where user_jid = ?3",
            (&contact.name, &contact.subscription, &contact.user_jid),
        )?;
        db.execute(
            "delete from groups_roster where contact_jid = ?1",
            [&contact.user_jid],
        )?;
        for group in contact.groups {
            db.execute(
                "insert into groups (group_name) values (?1) on conflict do nothing",
                [&group],
            )?;
            db.execute(
                "insert into groups_roster (group_name, contact_jid), values (?1, ?2)",
                (&group, &contact.user_jid),
            )?;
        }
        // TODO: delete orphaned groups from groups table, users etc.
        Ok(())
    }

    pub(crate) async fn upsert_contact(&self, contact: Contact) -> Result<(), Error> {
        let db = self.db().await;
        db.execute(
            "insert into users (jid) values (?1) on conflict do nothing",
            [&contact.user_jid],
        )?;
        db.execute(
            "insert into roster ( user_jid, name, subscription ) values ( ?1, ?2, ?3 ) on conflict do update set name = ?4, subscription = ?5",
            (&contact.user_jid, &contact.name, &contact.subscription, &contact.name, &contact.subscription),
        )?;
        db.execute(
            "delete from groups_roster where contact_jid = ?1",
            [&contact.user_jid],
        )?;
        for group in contact.groups {
            db.execute(
                "insert into groups (group_name) values (?1) on conflict do nothing",
                [&group],
            )?;
            db.execute(
                "insert into groups_roster (group_name, contact_jid) values (?1, ?2)",
                (group, &contact.user_jid),
            )?;
        }
        Ok(())
    }

    pub(crate) async fn delete_contact(&self, contact: JID) -> Result<(), Error> {
        self.db()
            .await
            .execute("delete from roster where user_jid = ?1", [&contact])?;
        Ok(())
    }

    pub(crate) async fn replace_cached_roster(&self, roster: Vec<Contact>) -> Result<(), Error> {
        {
            self.db().await.execute("delete from roster", [])?;
        }
        for contact in roster {
            self.upsert_contact(contact).await?;
        }
        Ok(())
    }

    pub(crate) async fn read_cached_roster(&self) -> Result<Vec<Contact>, Error> {
        let db = self.db().await;
        let mut roster: Vec<_> = db
            .prepare("select user_jid, name, subscription from roster")?
            .query_map([], |row| {
                Ok(Contact {
                    user_jid: row.get(0)?,
                    name: row.get(1)?,
                    subscription: row.get(2)?,
                    groups: HashSet::new(),
                })
            })?
            .collect::<Result<Vec<_>, _>>()?;
        for contact in &mut roster {
            let groups: Result<HashSet<String>, _> = db
                .prepare("select group_name from groups_roster where contact_jid = ?1")?
                .query_map([&contact.user_jid], |row| Ok(row.get(0)?))?
                .collect();
            contact.groups = groups?;
        }
        Ok(roster)
    }

    pub(crate) async fn read_cached_roster_with_users(
        &self,
    ) -> Result<Vec<(Contact, User)>, Error> {
        let db = self.db().await;
        let mut roster: Vec<(Contact, User)> = db.prepare("select user_jid, name, subscription, jid, nick, avatar from roster join users on jid = user_jid")?.query_map([], |row| {
            Ok((
                Contact {
                    user_jid: row.get(0)?,
                    name: row.get(1)?,
                    subscription: row.get(2)?,
                    groups: HashSet::new(),
                },
                User {
                    jid: row.get(3)?,
                    nick: row.get(4)?,
                    avatar: row.get(5)?,
                }
            ))
        })?.collect::<Result<Vec<_>, _>>()?;
        for (contact, _) in &mut roster {
            let groups: Result<HashSet<String>, _> = db
                .prepare("select group_name from groups_roster where contact_jid = ?1")?
                .query_map([&contact.user_jid], |row| Ok(row.get(0)?))?
                .collect();
            contact.groups = groups?;
        }
        Ok(roster)
    }

    pub(crate) async fn create_chat(&self, chat: Chat) -> Result<(), Error> {
        let id = Uuid::new_v4();
        let jid = chat.correspondent();
        self.db().await.execute(
            "insert into chats (id, correspondent, have_chatted) values (?1, ?2, ?3)",
            (id, jid, chat.have_chatted),
        )?;
        Ok(())
    }

    // TODO: what happens if a correspondent changes from a user to a contact? maybe just have correspondent be a user, then have the client make the user show up as a contact in ui if they are in the loaded roster.

    pub(crate) async fn read_chat(&self, chat: JID) -> Result<Chat, Error> {
        let chat = self.db().await.query_row(
            "select correspondent, have_chatted from chats where correspondent = ?1",
            [&chat],
            |row| {
                Ok(Chat {
                    correspondent: row.get(0)?,
                    have_chatted: row.get(1)?,
                })
            },
        )?;
        Ok(chat)
    }

    pub(crate) async fn mark_chat_as_chatted(&self, chat: JID) -> Result<(), Error> {
        self.db().await.execute(
            "update chats set have_chatted = true where correspondent = ?1",
            [chat],
        )?;
        Ok(())
    }

    pub(crate) async fn update_chat_correspondent(
        &self,
        old_chat: Chat,
        new_correspondent: JID,
    ) -> Result<Chat, Error> {
        let new_jid = &new_correspondent;
        let old_jid = old_chat.correspondent();
        let chat = self.db().await.query_row(
            "update chats set correspondent = ?1 where correspondent = ?2 returning correspondent, have_chatted",
            [new_jid, old_jid],
            |row| Ok(Chat {
                correspondent: row.get(0)?,
                have_chatted: row.get(1)?,
            })
        )?;
        Ok(chat)
    }

    // pub(crate) async fn update_chat

    pub(crate) async fn delete_chat(&self, chat: JID) -> Result<(), Error> {
        self.db()
            .await
            .execute("delete from chats where correspondent = ?1", [chat])?;
        Ok(())
    }

    /// TODO: sorting and filtering (for now there is no sorting)
    pub(crate) async fn read_chats(&self) -> Result<Vec<Chat>, Error> {
        let chats = self
            .db()
            .await
            .prepare("select correspondent, have_chatted from chats")?
            .query_map([], |row| {
                Ok(Chat {
                    correspondent: row.get(0)?,
                    have_chatted: row.get(1)?,
                })
            })?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(chats)
    }

    /// chats ordered by date of last message
    // greatest-n-per-group
    pub(crate) async fn read_chats_ordered(&self) -> Result<Vec<Chat>, Error> {
        let chats = self
            .db()
            .await
            .prepare("select c.correspondent, c.have_chatted, m.* from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc")?
            .query_map([], |row| {
                Ok(Chat {
                    correspondent: row.get(0)?,
                    have_chatted: row.get(1)?,
                })
            })?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(chats)
    }

    /// chats ordered by date of last message
    // greatest-n-per-group
    pub(crate) async fn read_chats_ordered_with_latest_messages(
        &self,
    ) -> Result<Vec<(Chat, Message)>, Error> {
        let chats = self
            .db()
            .await
            .prepare("select c.correspondent, c.have_chatted, m.id, m.from_jid, m.delivery, m.timestamp, m.body from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc")?
            .query_map([], |row| {
                Ok((
                    Chat {
                        correspondent: row.get(0)?,
                        have_chatted: row.get(1)?,
                    },
                    Message {
                        id: row.get(2)?,
                        from: row.get(3)?,
                        delivery: row.get(4)?,
                        timestamp: row.get(5)?,
                        body: Body {
                            body: row.get(6)?,
                        },
                    }
                ))
            })?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(chats)
    }

    /// chats ordered by date of last message
    // greatest-n-per-group
    pub(crate) async fn read_chats_ordered_with_latest_messages_and_users(
        &self,
    ) -> Result<Vec<((Chat, User), (Message, User))>, Error> {
        let chats = self
            .db()
            .await
            .prepare("select c.id as chat_id, c.correspondent as chat_correspondent, c.have_chatted as chat_have_chatted, m.id as message_id, m.body as message_body, m.delivery as message_delivery, m.timestamp as message_timestamp, m.from_jid as message_from_jid, cu.jid as chat_user_jid, cu.nick as chat_user_nick, cu.avatar as chat_user_avatar, mu.jid as message_user_jid, mu.nick as message_user_nick, mu.avatar as message_user_avatar from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp join users as cu on cu.jid = c.correspondent join users as mu on mu.jid = m.from_jid order by m.timestamp desc")?
            .query_map([], |row| {
                Ok((
                    (
                        Chat {
                            correspondent: row.get("chat_correspondent")?,
                            have_chatted: row.get("chat_have_chatted")?,
                        },
                        User {
                            jid: row.get("chat_user_jid")?,
                            nick: row.get("chat_user_nick")?,
                            avatar: row.get("chat_user_avatar")?,
                        }
                    ),
                    (
                        Message {
                            id: row.get("message_id")?,
                            from: row.get("message_from_jid")?,
                            delivery: row.get("message_delivery")?,
                            timestamp: row.get("message_timestamp")?,
                            body: Body {
                                body: row.get("message_body")?,
                            },
                        },
                        User {
                            jid: row.get("message_user_jid")?,
                            nick: row.get("message_user_nick")?,
                            avatar: row.get("message_user_avatar")?,
                        }
                    ),
                ))
            })?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(chats)
    }

    async fn read_chat_id(&self, chat: JID) -> Result<Uuid, Error> {
        let chat_id = self.db().await.query_row(
            "select id from chats where correspondent = ?1",
            [chat],
            |row| Ok(row.get(0)?),
        )?;
        Ok(chat_id)
    }

    async fn read_chat_id_opt(&self, chat: JID) -> Result<Option<Uuid>, Error> {
        let chat_id = self
            .db()
            .await
            .query_row(
                "select id from chats where correspondent = ?1",
                [chat],
                |row| Ok(row.get(0)?),
            )
            .optional()?;
        Ok(chat_id)
    }

    /// if the chat doesn't already exist, it must be created by calling create_chat() before running this function.
    pub(crate) async fn create_message(
        &self,
        message: Message,
        chat: JID,
        from: JID,
    ) -> Result<(), Error> {
        let from_jid = from.as_bare();
        let chat_id = self.read_chat_id(chat).await?;
        self.db().await.execute("insert into messages (id, body, chat_id, from_jid, from_resource, timestamp, delivery) values (?1, ?2, ?3, ?4, ?5, ?6, ?7)", (&message.id, &message.body.body, &chat_id, &from_jid, &from.resourcepart, &message.timestamp, &message.delivery))?;
        Ok(())
    }

    pub(crate) async fn upsert_chat_and_user(&self, chat: &JID) -> Result<bool, Error> {
        let bare_chat = chat.as_bare();
        let db = self.db().await;
        db.execute(
            "insert into users (jid) values (?1) on conflict do nothing",
            [&chat],
        )?;
        let id = Uuid::new_v4();
        db.execute("insert into chats (id, correspondent, have_chatted) values (?1, ?2, ?3) on conflict do nothing", (id, &bare_chat, false))?;
        let chat = db.query_row(
            "select correspondent, have_chatted from chats where correspondent = ?1",
            [&bare_chat],
            |row| {
                Ok(Chat {
                    correspondent: row.get(0)?,
                    have_chatted: row.get(1)?,
                })
            },
        )?;
        Ok(chat.have_chatted)
    }

    /// create direct message from incoming. MUST upsert chat and user
    pub(crate) async fn create_message_with_user_resource(
        &self,
        message: Message,
        // TODO: enforce two kinds of jid. bare and full
        // must be bare jid
        chat: JID,
        // full jid
        from: JID,
    ) -> Result<(), Error> {
        let from_jid = from.as_bare();
        if let Some(resource) = &from.resourcepart {
            self.db().await.execute(
                "insert into resources (bare_jid, resource) values (?1, ?2) on conflict do nothing",
                (&from_jid, resource),
            )?;
        }
        self.create_message(message, chat, from).await?;
        Ok(())
    }

    // pub(crate) async fn read_message(&self, message: Uuid) -> Result<Message, Error> {
    //     Ok(Message {
    //         id: Uuid,
    //         from: todo!(),
    //         delivery: todo!(),
    //         timestamp: todo!(),
    //         body: todo!(),
    //     })
    // }

    // TODO: message updates/edits pub(crate) async fn update_message(&self, message: Message) -> Result<(), Error> {}

    pub(crate) async fn delete_message(&self, message: Uuid) -> Result<(), Error> {
        self.db()
            .await
            .execute("delete from messages where id = ?1", [message])?;
        Ok(())
    }

    // TODO: paging
    pub(crate) async fn read_message_history(&self, chat: JID) -> Result<Vec<Message>, Error> {
        let chat_id = self.read_chat_id(chat).await?;
        let messages = self
            .db()
            .await
            .prepare(
                "select id, from_jid, delivery, timestamp, body from messages where chat_id = ?1",
            )?
            .query_map([chat_id], |row| {
                Ok(Message {
                    id: row.get(0)?,
                    // TODO: full from
                    from: row.get(1)?,
                    delivery: row.get(2)?,
                    timestamp: row.get(3)?,
                    body: Body { body: row.get(4)? },
                })
            })?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(messages)
    }

    pub(crate) async fn read_message_history_with_users(
        &self,
        chat: JID,
    ) -> Result<Vec<(Message, User)>, Error> {
        let chat_id = self.read_chat_id(chat).await?;
        let messages = self
            .db()
            .await
            .prepare(
                "select id, from_jid, delivery, timestamp, body, jid, nick, avatar from messages join users on jid = from_jid where chat_id = ? order by timestamp asc",
            )?
            .query_map([chat_id], |row| {
                Ok((
                    Message {
                        id: row.get(0)?,
                        // TODO: full from
                        from: row.get(1)?,
                        delivery: row.get(2)?,
                        timestamp: row.get(3)?,
                        body: Body { body: row.get(4)? },
                    },
                    User {
                        jid: row.get(5)?,
                        nick: row.get(6)?,
                        avatar: row.get(7)?,
                    }
                ))
            })?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(messages)
    }

    pub(crate) async fn read_cached_status(&self) -> Result<Online, Error> {
        let status = self.db().await.query_row(
            "select show, message from cached_status where id = 0",
            [],
            |row| {
                Ok(Online {
                    show: row.get(0)?,
                    status: row.get(1)?,
                    priority: None,
                })
            },
        )?;
        Ok(status)
    }

    pub(crate) async fn upsert_cached_status(&self, status: Online) -> Result<(), Error> {
        self.db().await.execute("insert into cached_status (id, show, message) values (0, ?1, ?2) on conflict do update set show = ?3, message = ?4", (status.show, &status.status, status.show, &status.status))?;
        Ok(())
    }

    pub(crate) async fn delete_cached_status(&self) -> Result<(), Error> {
        self.db().await.execute(
            "update cached_status set show = null, message = null where id = 0",
            [],
        )?;
        Ok(())
    }

    pub(crate) async fn read_capabilities(&self, node: &str) -> Result<String, Error> {
        let capabilities = self.db().await.query_row(
            "select capabilities from capability_hash_nodes where node = ?1",
            [node],
            |row| Ok(row.get(0)?),
        )?;
        Ok(capabilities)
    }

    pub(crate) async fn upsert_capabilities(
        &self,
        node: &str,
        capabilities: &str,
    ) -> Result<(), Error> {
        let now = Utc::now();
        self.db().await.execute("insert into capability_hash_nodes (node, timestamp, capabilities) values (?1, ?2, ?3) on conflict do update set timestamp = ?, capabilities = ?", (node, now, capabilities, now, capabilities))?;
        Ok(())
    }

    // pub(crate) async fn create_user(&self, user: User) -> Result<(), Error> {
    //     sqlx::query!(
    //         "insert into users ( jid, nick ) values ( ?, ? )",
    //         user.jid,
    //         user.nick,
    //     )
    //     .execute(&self.db)
    //     .await?;
    //     Ok(())
    // }

    // pub(crate) async fn read_user(&self, user: JID) -> Result<User, Error> {
    //     sqlx::query!(
    //         "insert into users ( jid ) values ( ? ) on conflict do nothing",
    //         user
    //     )
    //     .execute(&self.db)
    //     .await?;
    //     let user: User = sqlx::query_as("select * from users where jid = ?")
    //         .bind(user)
    //         .fetch_one(&self.db)
    //         .await?;
    //     Ok(user)
    // }

    // /// returns whether or not the nickname was updated
    // pub(crate) async fn delete_user_nick(&self, jid: JID) -> Result<bool, Error> {
    //     if sqlx::query!(
    //         "insert into users (jid, nick) values (?, ?) on conflict do update set nick = ? where nick is not ?",
    //         jid,
    //         None::<String>,
    //         None::<String>,
    //         None::<String>,
    //     )
    //     .execute(&self.db)
    //     .await?
    //     .rows_affected()
    //         > 0
    //     {
    //         Ok(true)
    //     } else {
    //         Ok(false)
    //     }
    // }

    // /// returns whether or not the nickname was updated
    // pub(crate) async fn upsert_user_nick(&self, jid: JID, nick: String) -> Result<bool, Error> {
    //     let rows_affected = sqlx::query!(
    //         "insert into users (jid, nick) values (?, ?) on conflict do update set nick = ? where nick is not ?",
    //         jid,
    //         nick,
    //         nick,
    //         nick
    //     )
    //     .execute(&self.db)
    //     .await?
    //     .rows_affected();
    //     tracing::debug!("rows affected: {}", rows_affected);
    //     if rows_affected > 0 {
    //         Ok(true)
    //     } else {
    //         Ok(false)
    //     }
    // }

    // /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar
    // pub(crate) async fn delete_user_avatar(
    //     &self,
    //     jid: JID,
    // ) -> Result<(bool, Option<String>), Error> {
    //     #[derive(sqlx::FromRow)]
    //     struct AvatarRow {
    //         avatar: Option<String>,
    //     }
    //     let old_avatar: Option<String> = sqlx::query_as("select avatar from users where jid = ?")
    //         .bind(jid.clone())
    //         .fetch_optional(&self.db)
    //         .await?
    //         .map(|row: AvatarRow| row.avatar)
    //         .unwrap_or(None);
    //     if sqlx::query!(
    //         "insert into users (jid, avatar) values (?, ?) on conflict do update set avatar = ? where avatar is not ?",
    //         jid,
    //         None::<String>,
    //         None::<String>,
    //         None::<String>,
    //     )
    //     .execute(&self.db)
    //     .await?
    //     .rows_affected()
    //         > 0
    //     {
    //         Ok((true, old_avatar))
    //     } else {
    //         Ok((false, old_avatar))
    //     }
    // }

    // /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar
    // pub(crate) async fn upsert_user_avatar(
    //     &self,
    //     jid: JID,
    //     avatar: String,
    // ) -> Result<(bool, Option<String>), Error> {
    //     #[derive(sqlx::FromRow)]
    //     struct AvatarRow {
    //         avatar: Option<String>,
    //     }
    //     let old_avatar: Option<String> = sqlx::query_as("select avatar from users where jid = ?")
    //         .bind(jid.clone())
    //         .fetch_optional(&self.db)
    //         .await?
    //         .map(|row: AvatarRow| row.avatar)
    //         .unwrap_or(None);
    //     if sqlx::query!(
    //         "insert into users (jid, avatar) values (?, ?) on conflict do update set avatar = ? where avatar is not ?",
    //         jid,
    //         avatar,
    //         avatar,
    //         avatar,
    //     )
    //     .execute(&self.db)
    //     .await?
    //     .rows_affected()
    //         > 0
    //     {
    //         Ok((true, old_avatar))
    //     } else {
    //         Ok((false, old_avatar))
    //     }
    // }

    // pub(crate) async fn update_user(&self, user: User) -> Result<(), Error> {
    //     sqlx::query!(
    //         "update users set nick = ? where jid = ?",
    //         user.nick,
    //         user.jid
    //     )
    //     .execute(&self.db)
    //     .await?;
    //     Ok(())
    // }

    // // TODO: should this be allowed? messages need to reference users. should probably only allow delete if every other thing referencing it has been deleted, or if you make clear to the user deleting a user will delete all messages associated with them.
    // // pub(crate) async fn delete_user(&self, user: JID) -> Result<(), Error> {}

    // /// does not create the underlying user, if underlying user does not exist, create_user() must be called separately
    // pub(crate) async fn create_contact(&self, contact: Contact) -> Result<(), Error> {
    //     sqlx::query!(
    //         "insert into roster ( user_jid, name, subscription ) values ( ?, ?, ? )",
    //         contact.user_jid,
    //         contact.name,
    //         contact.subscription
    //     )
    //     .execute(&self.db)
    //     .await?;
    //     // TODO: abstract this out in to add_to_group() function ?
    //     for group in contact.groups {
    //         sqlx::query!(
    //             "insert into groups (group_name) values (?) on conflict do nothing",
    //             group
    //         )
    //         .execute(&self.db)
    //         .await?;
    //         sqlx::query!(
    //             "insert into groups_roster (group_name, contact_jid) values (?, ?)",
    //             group,
    //             contact.user_jid
    //         )
    //         .execute(&self.db)
    //         .await?;
    //     }
    //     Ok(())
    // }

    // pub(crate) async fn read_contact(&self, contact: JID) -> Result<Contact, Error> {
    //     let mut contact: Contact = sqlx::query_as("select * from roster where user_jid = ?")
    //         .bind(contact)
    //         .fetch_one(&self.db)
    //         .await?;
    //     #[derive(sqlx::FromRow)]
    //     struct Row {
    //         group_name: String,
    //     }
    //     let groups: Vec<Row> =
    //         sqlx::query_as("select group_name from groups_roster where contact_jid = ?")
    //             .bind(&contact.user_jid)
    //             .fetch_all(&self.db)
    //             .await?;
    //     contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name));
    //     Ok(contact)
    // }

    // pub(crate) async fn read_contact_opt(&self, contact: &JID) -> Result<Option<Contact>, Error> {
    //     let contact: Option<Contact> =
    //         sqlx::query_as("select * from roster join users on jid = user_jid where jid = ?")
    //             .bind(contact)
    //             .fetch_optional(&self.db)
    //             .await?;
    //     if let Some(mut contact) = contact {
    //         #[derive(sqlx::FromRow)]
    //         struct Row {
    //             group_name: String,
    //         }
    //         let groups: Vec<Row> =
    //             sqlx::query_as("select group_name from groups_roster where contact_jid = ?")
    //                 .bind(&contact.user_jid)
    //                 .fetch_all(&self.db)
    //                 .await?;
    //         contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name));
    //         Ok(Some(contact))
    //     } else {
    //         Ok(None)
    //     }
    // }

    // /// does not update the underlying user, to update user, update_user() must be called separately
    // pub(crate) async fn update_contact(&self, contact: Contact) -> Result<(), Error> {
    //     sqlx::query!(
    //         "update roster set name = ?, subscription = ? where user_jid = ?",
    //         contact.name,
    //         contact.subscription,
    //         contact.user_jid
    //     )
    //     .execute(&self.db)
    //     .await?;
    //     sqlx::query!(
    //         "delete from groups_roster where contact_jid = ?",
    //         contact.user_jid
    //     )
    //     .execute(&self.db)
    //     .await?;
    //     // TODO: delete orphaned groups from groups table
    //     for group in contact.groups {
    //         sqlx::query!(
    //             "insert into groups (group_name) values (?) on conflict do nothing",
    //             group
    //         )
    //         .execute(&self.db)
    //         .await?;
    //         sqlx::query!(
    //             "insert into groups_roster (group_name, contact_jid) values (?, ?)",
    //             group,
    //             contact.user_jid
    //         )
    //         .execute(&self.db)
    //         .await?;
    //     }
    //     Ok(())
    // }

    // pub(crate) async fn upsert_contact(&self, contact: Contact) -> Result<(), Error> {
    //     sqlx::query!(
    //         "insert into users ( jid ) values ( ? ) on conflict do nothing",
    //         contact.user_jid,
    //     )
    //     .execute(&self.db)
    //     .await?;
    //     sqlx::query!(
    //         "insert into roster ( user_jid, name, subscription ) values ( ?, ?, ? ) on conflict do update set name = ?, subscription = ?",
    //         contact.user_jid,
    //         contact.name,
    //         contact.subscription,
    //         contact.name,
    //         contact.subscription
    //     )
    //     .execute(&self.db)
    //     .await?;
    //     sqlx::query!(
    //         "delete from groups_roster where contact_jid = ?",
    //         contact.user_jid
    //     )
    //     .execute(&self.db)
    //     .await?;
    //     // TODO: delete orphaned groups from groups table
    //     for group in contact.groups {
    //         sqlx::query!(
    //             "insert into groups (group_name) values (?) on conflict do nothing",
    //             group
    //         )
    //         .execute(&self.db)
    //         .await?;
    //         sqlx::query!(
    //             "insert into groups_roster (group_name, contact_jid) values (?, ?)",
    //             group,
    //             contact.user_jid
    //         )
    //         .execute(&self.db)
    //         .await?;
    //     }
    //     Ok(())
    // }

    // pub(crate) async fn delete_contact(&self, contact: JID) -> Result<(), Error> {
    //     sqlx::query!("delete from roster where user_jid = ?", contact)
    //         .execute(&self.db)
    //         .await?;
    //     // TODO: delete orphaned groups from groups table
    //     Ok(())
    // }

    // pub(crate) async fn replace_cached_roster(&self, roster: Vec<Contact>) -> Result<(), Error> {
    //     sqlx::query!("delete from roster").execute(&self.db).await?;
    //     for contact in roster {
    //         self.upsert_contact(contact).await?;
    //     }
    //     Ok(())
    // }

    // pub(crate) async fn read_cached_roster(&self) -> Result<Vec<Contact>, Error> {
    //     let mut roster: Vec<Contact> = sqlx::query_as("select * from roster")
    //         .fetch_all(&self.db)
    //         .await?;
    //     for contact in &mut roster {
    //         #[derive(sqlx::FromRow)]
    //         struct Row {
    //             group_name: String,
    //         }
    //         let groups: Vec<Row> =
    //             sqlx::query_as("select group_name from groups_roster where contact_jid = ?")
    //                 .bind(&contact.user_jid)
    //                 .fetch_all(&self.db)
    //                 .await?;
    //         contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name));
    //     }
    //     Ok(roster)
    // }

    // pub(crate) async fn read_cached_roster_with_users(
    //     &self,
    // ) -> Result<Vec<(Contact, User)>, Error> {
    //     #[derive(sqlx::FromRow)]
    //     struct Row {
    //         #[sqlx(flatten)]
    //         contact: Contact,
    //         #[sqlx(flatten)]
    //         user: User,
    //     }
    //     let mut roster: Vec<Row> =
    //         sqlx::query_as("select * from roster join users on jid = user_jid")
    //             .fetch_all(&self.db)
    //             .await?;
    //     for row in &mut roster {
    //         #[derive(sqlx::FromRow)]
    //         struct Row {
    //             group_name: String,
    //         }
    //         let groups: Vec<Row> =
    //             sqlx::query_as("select group_name from groups_roster where contact_jid = ?")
    //                 .bind(&row.contact.user_jid)
    //                 .fetch_all(&self.db)
    //                 .await?;
    //         row.contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name));
    //     }
    //     let roster = roster
    //         .into_iter()
    //         .map(|row| (row.contact, row.user))
    //         .collect();
    //     Ok(roster)
    // }

    // pub(crate) async fn create_chat(&self, chat: Chat) -> Result<(), Error> {
    //     let id = Uuid::new_v4();
    //     let jid = chat.correspondent();
    //     sqlx::query!(
    //         "insert into chats (id, correspondent, have_chatted) values (?, ?, ?)",
    //         id,
    //         jid,
    //         chat.have_chatted,
    //     )
    //     .execute(&self.db)
    //     .await?;
    //     Ok(())
    // }

    // // TODO: what happens if a correspondent changes from a user to a contact? maybe just have correspondent be a user, then have the client make the user show up as a contact in ui if they are in the loaded roster.

    // pub(crate) async fn read_chat(&self, chat: JID) -> Result<Chat, Error> {
    //     // check if the chat correponding with the jid exists
    //     let chat: Chat = sqlx::query_as("select correspondent from chats where correspondent = ?")
    //         .bind(chat)
    //         .fetch_one(&self.db)
    //         .await?;
    //     Ok(chat)
    // }

    // pub(crate) async fn mark_chat_as_chatted(&self, chat: JID) -> Result<(), Error> {
    //     let jid = chat.as_bare();
    //     sqlx::query!(
    //         "update chats set have_chatted = true where correspondent = ?",
    //         jid
    //     )
    //     .execute(&self.db)
    //     .await?;
    //     Ok(())
    // }

    // pub(crate) async fn update_chat_correspondent(
    //     &self,
    //     old_chat: Chat,
    //     new_correspondent: JID,
    // ) -> Result<Chat, Error> {
    //     // TODO: update other chat data if it differs (for now there is only correspondent so doesn't matter)
    //     let new_jid = &new_correspondent;
    //     let old_jid = old_chat.correspondent();
    //     sqlx::query!(
    //         "update chats set correspondent = ? where correspondent = ?",
    //         new_jid,
    //         old_jid,
    //     )
    //     .execute(&self.db)
    //     .await?;
    //     let chat = self.read_chat(new_correspondent).await?;
    //     Ok(chat)
    // }

    // // pub(crate) async fn update_chat

    // pub(crate) async fn delete_chat(&self, chat: JID) -> Result<(), Error> {
    //     sqlx::query!("delete from chats where correspondent = ?", chat)
    //         .execute(&self.db)
    //         .await?;
    //     Ok(())
    // }

    // /// TODO: sorting and filtering (for now there is no sorting)
    // pub(crate) async fn read_chats(&self) -> Result<Vec<Chat>, Error> {
    //     let chats: Vec<Chat> = sqlx::query_as("select * from chats")
    //         .fetch_all(&self.db)
    //         .await?;
    //     Ok(chats)
    // }

    // /// chats ordered by date of last message
    // // greatest-n-per-group
    // pub(crate) async fn read_chats_ordered(&self) -> Result<Vec<Chat>, Error> {
    //     let chats = sqlx::query_as("select c.*, m.* from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc")
    //         .fetch_all(&self.db)
    //         .await?;
    //     Ok(chats)
    // }

    // /// chats ordered by date of last message
    // // greatest-n-per-group
    // pub(crate) async fn read_chats_ordered_with_latest_messages(
    //     &self,
    // ) -> Result<Vec<(Chat, Message)>, Error> {
    //     #[derive(sqlx::FromRow)]
    //     pub struct RowChat {
    //         chat_correspondent: JID,
    //         chat_have_chatted: bool,
    //     }
    //     impl From<RowChat> for Chat {
    //         fn from(value: RowChat) -> Self {
    //             Self {
    //                 correspondent: value.chat_correspondent,
    //                 have_chatted: value.chat_have_chatted,
    //             }
    //         }
    //     }
    //     #[derive(sqlx::FromRow)]
    //     pub struct RowMessage {
    //         message_id: Uuid,
    //         message_body: String,
    //         message_delivery: Option<Delivery>,
    //         message_timestamp: DateTime<Utc>,
    //         message_from_jid: JID,
    //     }
    //     impl From<RowMessage> for Message {
    //         fn from(value: RowMessage) -> Self {
    //             Self {
    //                 id: value.message_id,
    //                 from: value.message_from_jid,
    //                 delivery: value.message_delivery,
    //                 timestamp: value.message_timestamp,
    //                 body: Body {
    //                     body: value.message_body,
    //                 },
    //             }
    //         }
    //     }

    //     #[derive(sqlx::FromRow)]
    //     pub struct ChatWithMessageRow {
    //         #[sqlx(flatten)]
    //         pub chat: RowChat,
    //         #[sqlx(flatten)]
    //         pub message: RowMessage,
    //     }

    //     pub struct ChatWithMessage {
    //         chat: Chat,
    //         message: Message,
    //     }

    //     impl From<ChatWithMessageRow> for ChatWithMessage {
    //         fn from(value: ChatWithMessageRow) -> Self {
    //             Self {
    //                 chat: value.chat.into(),
    //                 message: value.message.into(),
    //             }
    //         }
    //     }

    //     // TODO: sometimes chats have no messages.
    //     let chats: Vec<ChatWithMessageRow> = sqlx::query_as("select c.*, m.* from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc")
    //         .fetch_all(&self.db)
    //         .await?;

    //     let chats = chats
    //         .into_iter()
    //         .map(|chat_with_message_row| {
    //             let chat_with_message: ChatWithMessage = chat_with_message_row.into();
    //             (chat_with_message.chat, chat_with_message.message)
    //         })
    //         .collect();

    //     Ok(chats)
    // }

    // /// chats ordered by date of last message
    // // greatest-n-per-group
    // pub(crate) async fn read_chats_ordered_with_latest_messages_and_users(
    //     &self,
    // ) -> Result<Vec<((Chat, User), (Message, User))>, Error> {
    //     #[derive(sqlx::FromRow)]
    //     pub struct RowChat {
    //         chat_correspondent: JID,
    //         chat_have_chatted: bool,
    //     }
    //     impl From<RowChat> for Chat {
    //         fn from(value: RowChat) -> Self {
    //             Self {
    //                 correspondent: value.chat_correspondent,
    //                 have_chatted: value.chat_have_chatted,
    //             }
    //         }
    //     }
    //     #[derive(sqlx::FromRow)]
    //     pub struct RowMessage {
    //         message_id: Uuid,
    //         message_body: String,
    //         message_delivery: Option<Delivery>,
    //         message_timestamp: DateTime<Utc>,
    //         message_from_jid: JID,
    //     }
    //     impl From<RowMessage> for Message {
    //         fn from(value: RowMessage) -> Self {
    //             Self {
    //                 id: value.message_id,
    //                 from: value.message_from_jid,
    //                 delivery: value.message_delivery,
    //                 timestamp: value.message_timestamp,
    //                 body: Body {
    //                     body: value.message_body,
    //                 },
    //             }
    //         }
    //     }
    //     #[derive(sqlx::FromRow)]
    //     pub struct RowChatUser {
    //         chat_user_jid: JID,
    //         chat_user_nick: Option<String>,
    //         chat_user_avatar: Option<String>,
    //     }
    //     impl From<RowChatUser> for User {
    //         fn from(value: RowChatUser) -> Self {
    //             Self {
    //                 jid: value.chat_user_jid,
    //                 nick: value.chat_user_nick,
    //                 avatar: value.chat_user_avatar,
    //             }
    //         }
    //     }
    //     #[derive(sqlx::FromRow)]
    //     pub struct RowMessageUser {
    //         message_user_jid: JID,
    //         message_user_nick: Option<String>,
    //         message_user_avatar: Option<String>,
    //     }
    //     impl From<RowMessageUser> for User {
    //         fn from(value: RowMessageUser) -> Self {
    //             Self {
    //                 jid: value.message_user_jid,
    //                 nick: value.message_user_nick,
    //                 avatar: value.message_user_avatar,
    //             }
    //         }
    //     }
    //     #[derive(sqlx::FromRow)]
    //     pub struct ChatWithMessageAndUsersRow {
    //         #[sqlx(flatten)]
    //         pub chat: RowChat,
    //         #[sqlx(flatten)]
    //         pub chat_user: RowChatUser,
    //         #[sqlx(flatten)]
    //         pub message: RowMessage,
    //         #[sqlx(flatten)]
    //         pub message_user: RowMessageUser,
    //     }

    //     impl From<ChatWithMessageAndUsersRow> for ChatWithMessageAndUsers {
    //         fn from(value: ChatWithMessageAndUsersRow) -> Self {
    //             Self {
    //                 chat: value.chat.into(),
    //                 chat_user: value.chat_user.into(),
    //                 message: value.message.into(),
    //                 message_user: value.message_user.into(),
    //             }
    //         }
    //     }

    //     pub struct ChatWithMessageAndUsers {
    //         chat: Chat,
    //         chat_user: User,
    //         message: Message,
    //         message_user: User,
    //     }

    //     let chats: Vec<ChatWithMessageAndUsersRow> = sqlx::query_as("select c.id as chat_id, c.correspondent as chat_correspondent, c.have_chatted as chat_have_chatted, m.id as message_id, m.body as message_body, m.delivery as message_delivery, m.timestamp as message_timestamp, m.from_jid as message_from_jid, cu.jid as chat_user_jid, cu.nick as chat_user_nick, cu.avatar as chat_user_avatar, mu.jid as message_user_jid, mu.nick as message_user_nick, mu.avatar as message_user_avatar from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp join users as cu on cu.jid = c.correspondent join users as mu on mu.jid = m.from_jid order by m.timestamp desc")
    //         .fetch_all(&self.db)
    //         .await?;

    //     let chats = chats
    //         .into_iter()
    //         .map(|chat_with_message_and_users_row| {
    //             let chat_with_message_and_users: ChatWithMessageAndUsers =
    //                 chat_with_message_and_users_row.into();
    //             (
    //                 (
    //                     chat_with_message_and_users.chat,
    //                     chat_with_message_and_users.chat_user,
    //                 ),
    //                 (
    //                     chat_with_message_and_users.message,
    //                     chat_with_message_and_users.message_user,
    //                 ),
    //             )
    //         })
    //         .collect();

    //     Ok(chats)
    // }

    // async fn read_chat_id(&self, chat: JID) -> Result<Uuid, Error> {
    //     #[derive(sqlx::FromRow)]
    //     struct Row {
    //         id: Uuid,
    //     }
    //     let chat = chat.as_bare();
    //     let chat_id: Row = sqlx::query_as("select id from chats where correspondent = ?")
    //         .bind(chat)
    //         .fetch_one(&self.db)
    //         .await?;
    //     let chat_id = chat_id.id;
    //     Ok(chat_id)
    // }

    // async fn read_chat_id_opt(&self, chat: JID) -> Result<Option<Uuid>, Error> {
    //     #[derive(sqlx::FromRow)]
    //     struct Row {
    //         id: Uuid,
    //     }
    //     let chat_id: Option<Row> = sqlx::query_as("select id from chats where correspondent = ?")
    //         .bind(chat)
    //         .fetch_optional(&self.db)
    //         .await?;
    //     let chat_id = chat_id.map(|row| row.id);
    //     Ok(chat_id)
    // }

    // /// if the chat doesn't already exist, it must be created by calling create_chat() before running this function.
    // pub(crate) async fn create_message(
    //     &self,
    //     message: Message,
    //     chat: JID,
    //     from: JID,
    // ) -> Result<(), Error> {
    //     // TODO: one query
    //     let from_jid = from.as_bare();
    //     let chat_id = self.read_chat_id(chat).await?;
    //     sqlx::query!("insert into messages (id, body, chat_id, from_jid, from_resource, timestamp) values (?, ?, ?, ?, ?, ?)", message.id, message.body.body, chat_id, from_jid, from.resourcepart, message.timestamp).execute(&self.db).await?;
    //     Ok(())
    // }

    // pub(crate) async fn upsert_chat_and_user(&self, chat: &JID) -> Result<bool, Error> {
    //     let bare_chat = chat.as_bare();
    //     sqlx::query!(
    //         "insert into users (jid) values (?) on conflict do nothing",
    //         bare_chat,
    //     )
    //     .execute(&self.db)
    //     .await?;
    //     let id = Uuid::new_v4();
    //     let chat: Chat = sqlx::query_as("insert into chats (id, correspondent, have_chatted) values (?, ?, ?) on conflict do nothing; select * from chats where correspondent = ?")
    //         .bind(id)
    //         .bind(bare_chat.clone())
    //         .bind(false)
    //         .bind(bare_chat)
    //         .fetch_one(&self.db)
    //         .await?;
    //     tracing::debug!("CHECKING chat: {:?}", chat);
    //     Ok(chat.have_chatted)
    // }

    // /// MUST upsert chat beforehand
    // pub(crate) async fn create_message_with_self_resource(
    //     &self,
    //     message: Message,
    //     chat: JID,
    //     // full jid
    //     from: JID,
    // ) -> Result<(), Error> {
    //     let from_jid = from.as_bare();
    //     if let Some(resource) = &from.resourcepart {
    //         sqlx::query!(
    //             "insert into resources (bare_jid, resource) values (?, ?) on conflict do nothing",
    //             from_jid,
    //             resource
    //         )
    //         .execute(&self.db)
    //         .await?;
    //     }
    //     self.create_message(message, chat, from).await?;
    //     Ok(())
    // }

    // /// create direct message from incoming. MUST upsert chat and user
    // pub(crate) async fn create_message_with_user_resource(
    //     &self,
    //     message: Message,
    //     chat: JID,
    //     // full jid
    //     from: JID,
    // ) -> Result<(), Error> {
    //     let bare_chat = chat.as_bare();
    //     let resource = &chat.resourcepart;
    //     if let Some(resource) = resource {
    //         sqlx::query!(
    //             "insert into resources (bare_jid, resource) values (?, ?) on conflict do nothing",
    //             bare_chat,
    //             resource
    //         )
    //         .execute(&self.db)
    //         .await?;
    //     }
    //     self.create_message(message, chat, from).await?;
    //     Ok(())
    // }

    // pub(crate) async fn read_message(&self, message: Uuid) -> Result<Message, Error> {
    //     let message: Message = sqlx::query_as("select * from messages where id = ?")
    //         .bind(message)
    //         .fetch_one(&self.db)
    //         .await?;
    //     Ok(message)
    // }

    // // TODO: message updates/edits pub(crate) async fn update_message(&self, message: Message) -> Result<(), Error> {}

    // pub(crate) async fn delete_message(&self, message: Uuid) -> Result<(), Error> {
    //     sqlx::query!("delete from messages where id = ?", message)
    //         .execute(&self.db)
    //         .await?;
    //     Ok(())
    // }

    // // TODO: paging
    // pub(crate) async fn read_message_history(&self, chat: JID) -> Result<Vec<Message>, Error> {
    //     let chat_id = self.read_chat_id(chat).await?;
    //     let messages: Vec<Message> =
    //         sqlx::query_as("select * from messages where chat_id = ? order by timestamp asc")
    //             .bind(chat_id)
    //             .fetch_all(&self.db)
    //             .await?;
    //     Ok(messages)
    // }

    // pub(crate) async fn read_message_history_with_users(
    //     &self,
    //     chat: JID,
    // ) -> Result<Vec<(Message, User)>, Error> {
    //     let chat_id = self.read_chat_id(chat).await?;
    //     #[derive(sqlx::FromRow)]
    //     pub struct Row {
    //         #[sqlx(flatten)]
    //         user: User,
    //         #[sqlx(flatten)]
    //         message: Message,
    //     }
    //     let messages: Vec<Row> =
    //         sqlx::query_as("select * from messages join users on jid = from_jid where chat_id = ? order by timestamp asc")
    //             .bind(chat_id)
    //             .fetch_all(&self.db)
    //             .await?;
    //     let messages = messages
    //         .into_iter()
    //         .map(|row| (row.message, row.user))
    //         .collect();
    //     Ok(messages)
    // }

    // pub(crate) async fn read_cached_status(&self) -> Result<Online, Error> {
    //     let online: Online = sqlx::query_as("select * from cached_status where id = 0")
    //         .fetch_one(&self.db)
    //         .await?;
    //     Ok(online)
    // }

    // pub(crate) async fn upsert_cached_status(&self, status: Online) -> Result<(), Error> {
    //     sqlx::query!(
    //         "insert into cached_status (id, show, message) values (0, ?, ?) on conflict do update set show = ?, message = ?",
    //         status.show,
    //         status.status,
    //         status.show,
    //         status.status
    //     ).execute(&self.db).await?;
    //     Ok(())
    // }

    // pub(crate) async fn delete_cached_status(&self) -> Result<(), Error> {
    //     sqlx::query!("update cached_status set show = null, message = null where id = 0")
    //         .execute(&self.db)
    //         .await?;
    //     Ok(())
    // }

    // pub(crate) async fn read_capabilities(&self, node: &str) -> Result<String, Error> {
    //     #[derive(sqlx::FromRow)]
    //     struct Row {
    //         capabilities: String,
    //     }
    //     let row: Row =
    //         sqlx::query_as("select capabilities from capability_hash_nodes where node = ?")
    //             .bind(node)
    //             .fetch_one(&self.db)
    //             .await?;
    //     Ok(row.capabilities)
    // }

    // pub(crate) async fn upsert_capabilities(
    //     &self,
    //     node: &str,
    //     capabilities: &str,
    // ) -> Result<(), Error> {
    //     let now = Utc::now();
    //     sqlx::query!(
    //         "insert into capability_hash_nodes (node, timestamp, capabilities) values (?, ?, ?) on conflict do update set timestamp = ?, capabilities = ?", node, now, capabilities, now, capabilities
    //     ).execute(&self.db).await?;
    //     Ok(())
    // }
}