places/storage/
history_metadata.rs

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
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use crate::db::{PlacesDb, PlacesTransaction};
use crate::error::*;
use crate::RowId;
use error_support::{breadcrumb, redact_url};
use rusqlite::types::{FromSql, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use sql_support::ConnExt;
use std::vec::Vec;
use sync_guid::Guid as SyncGuid;
use types::Timestamp;
use url::Url;

use lazy_static::lazy_static;

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum DocumentType {
    Regular = 0,
    Media = 1,
}

impl FromSql for DocumentType {
    #[inline]
    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
        Ok(match value.as_i64()? {
            0 => DocumentType::Regular,
            1 => DocumentType::Media,
            other => {
                // seems safe to ignore?
                log::warn!("invalid DocumentType {}", other);
                DocumentType::Regular
            }
        })
    }
}

impl ToSql for DocumentType {
    #[inline]
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
        Ok(ToSqlOutput::from(*self as u32))
    }
}

#[derive(Clone)]
pub struct HistoryHighlightWeights {
    pub view_time: f64,
    pub frequency: f64,
}

#[derive(Clone)]
pub struct HistoryHighlight {
    pub score: f64,
    pub place_id: i32,
    pub url: String,
    pub title: Option<String>,
    pub preview_image_url: Option<String>,
}

impl HistoryHighlight {
    pub(crate) fn from_row(row: &rusqlite::Row<'_>) -> Result<Self> {
        Ok(Self {
            score: row.get("score")?,
            place_id: row.get("place_id")?,
            url: row.get("url")?,
            title: row.get("title")?,
            preview_image_url: row.get("preview_image_url")?,
        })
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HistoryMetadataObservation {
    pub url: String,
    pub view_time: Option<i32>,
    pub search_term: Option<String>,
    pub document_type: Option<DocumentType>,
    pub referrer_url: Option<String>,
    pub title: Option<String>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HistoryMetadataPageMissingBehavior {
    InsertPage,
    IgnoreObservation,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NoteHistoryMetadataObservationOptions {
    pub if_page_missing: HistoryMetadataPageMissingBehavior,
}

impl Default for NoteHistoryMetadataObservationOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl NoteHistoryMetadataObservationOptions {
    pub fn new() -> Self {
        Self {
            if_page_missing: HistoryMetadataPageMissingBehavior::IgnoreObservation,
        }
    }

    pub fn if_page_missing(self, if_page_missing: HistoryMetadataPageMissingBehavior) -> Self {
        Self { if_page_missing }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HistoryMetadata {
    pub url: String,
    pub title: Option<String>,
    pub preview_image_url: Option<String>,
    pub created_at: i64,
    pub updated_at: i64,
    pub total_view_time: i32,
    pub search_term: Option<String>,
    pub document_type: DocumentType,
    pub referrer_url: Option<String>,
}

impl HistoryMetadata {
    pub(crate) fn from_row(row: &rusqlite::Row<'_>) -> Result<Self> {
        let created_at: Timestamp = row.get("created_at")?;
        let updated_at: Timestamp = row.get("updated_at")?;

        // Guard against invalid data in the db.
        // Certain client bugs allowed accumulating values that are too large to fit into i32,
        // leading to overflow failures. While this data will expire and will be deleted
        // by clients via `delete_older_than`, we still want to ensure we won't crash in case of
        // encountering it.
        // See `apply_metadata_observation` for where we guard against observing invalid view times.
        let total_view_time: i64 = row.get("total_view_time")?;
        let total_view_time = match i32::try_from(total_view_time) {
            Ok(tvt) => tvt,
            Err(_) => i32::MAX,
        };

        Ok(Self {
            url: row.get("url")?,
            title: row.get("title")?,
            preview_image_url: row.get("preview_image_url")?,
            created_at: created_at.0 as i64,
            updated_at: updated_at.0 as i64,
            total_view_time,
            search_term: row.get("search_term")?,
            document_type: row.get("document_type")?,
            referrer_url: row.get("referrer_url")?,
        })
    }
}

enum PlaceEntry {
    Existing(i64),
    CreateFor(Url, Option<String>),
}

trait WhereArg {
    fn to_where_arg(&self, db_field: &str) -> String;
}

impl PlaceEntry {
    fn fetch(url: &str, tx: &PlacesTransaction<'_>, title: Option<String>) -> Result<Self> {
        let url = Url::parse(url).inspect_err(|_e| {
            breadcrumb!(
                "PlaceEntry::fetch -- Error parsing url: {}",
                redact_url(url)
            );
        })?;
        let place_id = tx.try_query_one(
            "SELECT id FROM moz_places WHERE url_hash = hash(:url) AND url = :url",
            &[(":url", &url.as_str())],
            true,
        )?;

        Ok(match place_id {
            Some(id) => PlaceEntry::Existing(id),
            None => PlaceEntry::CreateFor(url, title),
        })
    }
}

impl WhereArg for PlaceEntry {
    fn to_where_arg(&self, db_field: &str) -> String {
        match self {
            PlaceEntry::Existing(id) => format!("{} = {}", db_field, id),
            PlaceEntry::CreateFor(_, _) => panic!("WhereArg: place entry must exist"),
        }
    }
}

impl WhereArg for Option<PlaceEntry> {
    fn to_where_arg(&self, db_field: &str) -> String {
        match self {
            Some(entry) => entry.to_where_arg(db_field),
            None => format!("{} IS NULL", db_field),
        }
    }
}

trait DatabaseId {
    fn get_or_insert(&self, tx: &PlacesTransaction<'_>) -> Result<i64>;
}

impl DatabaseId for PlaceEntry {
    fn get_or_insert(&self, tx: &PlacesTransaction<'_>) -> Result<i64> {
        Ok(match self {
            PlaceEntry::Existing(id) => *id,
            PlaceEntry::CreateFor(url, title) => {
                let sql = "INSERT INTO moz_places (guid, url, title, url_hash)
                VALUES (:guid, :url, :title, hash(:url))";

                let guid = SyncGuid::random();

                tx.execute_cached(
                    sql,
                    &[
                        (":guid", &guid as &dyn rusqlite::ToSql),
                        (":title", &title),
                        (":url", &url.as_str()),
                    ],
                )?;
                tx.conn().last_insert_rowid()
            }
        })
    }
}

enum SearchQueryEntry {
    Existing(i64),
    CreateFor(String),
}

impl DatabaseId for SearchQueryEntry {
    fn get_or_insert(&self, tx: &PlacesTransaction<'_>) -> Result<i64> {
        Ok(match self {
            SearchQueryEntry::Existing(id) => *id,
            SearchQueryEntry::CreateFor(term) => {
                tx.execute_cached(
                    "INSERT INTO moz_places_metadata_search_queries(term) VALUES (:term)",
                    &[(":term", &term)],
                )?;
                tx.conn().last_insert_rowid()
            }
        })
    }
}

impl SearchQueryEntry {
    fn from(search_term: &str, tx: &PlacesTransaction<'_>) -> Result<Self> {
        let lowercase_term = search_term.to_lowercase();
        Ok(
            match tx.try_query_one(
                "SELECT id FROM moz_places_metadata_search_queries WHERE term = :term",
                &[(":term", &lowercase_term)],
                true,
            )? {
                Some(id) => SearchQueryEntry::Existing(id),
                None => SearchQueryEntry::CreateFor(lowercase_term),
            },
        )
    }
}

impl WhereArg for SearchQueryEntry {
    fn to_where_arg(&self, db_field: &str) -> String {
        match self {
            SearchQueryEntry::Existing(id) => format!("{} = {}", db_field, id),
            SearchQueryEntry::CreateFor(_) => panic!("WhereArg: search query entry must exist"),
        }
    }
}

impl WhereArg for Option<SearchQueryEntry> {
    fn to_where_arg(&self, db_field: &str) -> String {
        match self {
            Some(entry) => entry.to_where_arg(db_field),
            None => format!("{} IS NULL", db_field),
        }
    }
}

struct HistoryMetadataCompoundKey {
    place_entry: PlaceEntry,
    referrer_entry: Option<PlaceEntry>,
    search_query_entry: Option<SearchQueryEntry>,
}

struct MetadataObservation {
    document_type: Option<DocumentType>,
    view_time: Option<i32>,
}

impl HistoryMetadataCompoundKey {
    fn can_debounce(&self) -> Option<i64> {
        match self.place_entry {
            PlaceEntry::Existing(id) => {
                if (match self.search_query_entry {
                    None | Some(SearchQueryEntry::Existing(_)) => true,
                    Some(SearchQueryEntry::CreateFor(_)) => false,
                } && match self.referrer_entry {
                    None | Some(PlaceEntry::Existing(_)) => true,
                    Some(PlaceEntry::CreateFor(_, _)) => false,
                }) {
                    Some(id)
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    // Looks up matching metadata records, by the compound key and time window.
    fn lookup(&self, tx: &PlacesTransaction<'_>, newer_than: i64) -> Result<Option<i64>> {
        Ok(match self.can_debounce() {
            Some(id) => {
                let search_query_id = match self.search_query_entry {
                    None | Some(SearchQueryEntry::CreateFor(_)) => None,
                    Some(SearchQueryEntry::Existing(id)) => Some(id),
                };

                let referrer_place_id = match self.referrer_entry {
                    None | Some(PlaceEntry::CreateFor(_, _)) => None,
                    Some(PlaceEntry::Existing(id)) => Some(id),
                };

                tx.try_query_one::<i64, _>(
                    "SELECT id FROM moz_places_metadata
                        WHERE
                            place_id IS :place_id AND
                            referrer_place_id IS :referrer_place_id AND
                            search_query_id IS :search_query_id AND
                            updated_at >= :newer_than
                        ORDER BY updated_at DESC LIMIT 1",
                    rusqlite::named_params! {
                        ":place_id": id,
                        ":search_query_id": search_query_id,
                        ":referrer_place_id": referrer_place_id,
                        ":newer_than": newer_than
                    },
                    true,
                )?
            }
            None => None,
        })
    }
}

const DEBOUNCE_WINDOW_MS: i64 = 2 * 60 * 1000; // 2 minutes
const MAX_QUERY_RESULTS: i32 = 1000;

const COMMON_METADATA_SELECT: &str = "
SELECT
    m.id as metadata_id, p.url as url, p.title as title, p.preview_image_url as preview_image_url,
    m.created_at as created_at, m.updated_at as updated_at, m.total_view_time as total_view_time,
    m.document_type as document_type, o.url as referrer_url, s.term as search_term
FROM moz_places_metadata m
LEFT JOIN moz_places p ON m.place_id = p.id
LEFT JOIN moz_places_metadata_search_queries s ON m.search_query_id = s.id
LEFT JOIN moz_places o ON o.id = m.referrer_place_id";

// Highlight query returns moz_places entries ranked by a "highlight score".
// This score takes into account two factors:
// 1) frequency of visits to a page,
// 2) cumulative view time of a page.
//
// Eventually, we could consider combining this with `moz_places.frecency` as a basis for (1), that assumes we have a populated moz_historyvisits table.
// Currently, iOS doesn't use 'places' library to track visits, so iOS clients won't have meaningful frecency scores.
//
// Instead, we use moz_places_metadata entries to compute both (1) and (2).
// This has several nice properties:
// - it works on clients that only use 'metadata' APIs, not 'places'
// - since metadata is capped by clients to a certain time window (via `delete_older_than`), the scores will be computed for the same time window
// - we debounce metadata observations to the same "key" if they're close in time.
// -- this is an equivalent of saying that if a page was visited multiple times in quick succession, treat that as a single visit while accumulating the view time
// -- the assumption we're making is that this better matches user perception of their browsing activity
//
// The score is computed as a weighted sum of two probabilities:
// - at any given moment in my browsing sessions for the past X days, how likely am I to be looking at a page?
// - for any given visit during my browsing sessions for the past X days, how likely am I to visit a page?
//
// This kind of scoring is fairly intuitive and simple to reason about at the product level.
//
// An alternative way to arrive at the same ranking would be to normalize the values to compare data of different dimensions, time vs frequency.
// We can normalize view time and frequency into a 0-1 scale before computing weighted scores.
// (select place_id, (normal_frequency * 1.0 + normal_view_time * 1.0) as score from
//     (select place_id, cast(count(*) - min_f as REAL) / cast(range_f as REAL) as normal_frequency, cast(sum(total_view_time) - min_v as REAL) / cast(max_v as REAL) as normal_view_time from moz_places_metadata,
//     (select min(frequency) as min_f, max(frequency) as max_f, max(frequency) - min(frequency) as range_f
//         from (select count(*) as frequency from moz_places_metadata group by place_id)
//     ),
//     (select min(view_time) as min_v, max(view_time) as max_v, max(view_time) - min(view_time) as range_v
//         from (select sum(total_view_time) as view_time from moz_places_metadata where total_view_time > 0 group by place_id)
//     ) where total_view_time > 0 group by place_id)) ranked
//
// Note that while it's tempting to use built-in window functions such percent_rank, they're not sufficient.
// The built-in functions concern themselves with absolute ranking, not taking into account magnitudes of differences between values.
// For example, given two entries we'll know that one is larger than another, but not by how much.
const HIGHLIGHTS_QUERY: &str = "
SELECT
    IFNULL(ranked.score, 0.0) AS score, p.id AS place_id, p.url AS url, p.title AS title, p.preview_image_url AS preview_image_url
FROM moz_places p
INNER JOIN
    (
        SELECT place_id, :view_time_weight * view_time_prob + :frequency_weight * frequency_prob AS score FROM (
            SELECT
                place_id,
                CAST(count(*) AS REAL) / total_count AS frequency_prob,
                CAST(sum(total_view_time) AS REAL) / all_view_time AS view_time_prob
                FROM (
                    SELECT place_id, count(*) OVER () AS total_count, total_view_time, sum(total_view_time) OVER () AS all_view_time FROM moz_places_metadata
                )
            GROUP BY place_id
        )
    ) ranked
ON p.id = ranked.place_id
ORDER BY ranked.score DESC
LIMIT :limit";

lazy_static! {
    static ref GET_LATEST_SQL: String = format!(
        "{common_select_sql}
        WHERE p.url_hash = hash(:url) AND p.url = :url
        ORDER BY updated_at DESC, metadata_id DESC
        LIMIT 1",
        common_select_sql = COMMON_METADATA_SELECT
    );
    static ref GET_BETWEEN_SQL: String = format!(
        "{common_select_sql}
        WHERE updated_at BETWEEN :start AND :end
        ORDER BY updated_at DESC
        LIMIT {max_limit}",
        common_select_sql = COMMON_METADATA_SELECT,
        max_limit = MAX_QUERY_RESULTS
    );
    static ref GET_SINCE_SQL: String = format!(
        "{common_select_sql}
        WHERE updated_at >= :start
        ORDER BY updated_at DESC
        LIMIT {max_limit}",
        common_select_sql = COMMON_METADATA_SELECT,
        max_limit = MAX_QUERY_RESULTS
    );
    static ref QUERY_SQL: String = format!(
        "{common_select_sql}
        WHERE
            p.url LIKE :query OR
            p.title LIKE :query OR
            search_term LIKE :query
        ORDER BY total_view_time DESC
        LIMIT :limit",
        common_select_sql = COMMON_METADATA_SELECT
    );
}

pub fn get_latest_for_url(db: &PlacesDb, url: &Url) -> Result<Option<HistoryMetadata>> {
    let metadata = db.try_query_row(
        GET_LATEST_SQL.as_str(),
        &[(":url", &url.as_str())],
        HistoryMetadata::from_row,
        true,
    )?;
    Ok(metadata)
}

pub fn get_between(db: &PlacesDb, start: i64, end: i64) -> Result<Vec<HistoryMetadata>> {
    db.query_rows_and_then_cached(
        GET_BETWEEN_SQL.as_str(),
        rusqlite::named_params! {
            ":start": start,
            ":end": end,
        },
        HistoryMetadata::from_row,
    )
}

pub fn get_since(db: &PlacesDb, start: i64) -> Result<Vec<HistoryMetadata>> {
    db.query_rows_and_then_cached(
        GET_SINCE_SQL.as_str(),
        rusqlite::named_params! {
            ":start": start
        },
        HistoryMetadata::from_row,
    )
}

pub fn get_highlights(
    db: &PlacesDb,
    weights: HistoryHighlightWeights,
    limit: i32,
) -> Result<Vec<HistoryHighlight>> {
    db.query_rows_and_then_cached(
        HIGHLIGHTS_QUERY,
        rusqlite::named_params! {
            ":view_time_weight": weights.view_time,
            ":frequency_weight": weights.frequency,
            ":limit": limit
        },
        HistoryHighlight::from_row,
    )
}

pub fn query(db: &PlacesDb, query: &str, limit: i32) -> Result<Vec<HistoryMetadata>> {
    db.query_rows_and_then_cached(
        QUERY_SQL.as_str(),
        rusqlite::named_params! {
            ":query": format!("%{}%", query),
            ":limit": limit
        },
        HistoryMetadata::from_row,
    )
}

pub fn delete_older_than(db: &PlacesDb, older_than: i64) -> Result<()> {
    db.execute_cached(
        "DELETE FROM moz_places_metadata
         WHERE updated_at < :older_than",
        &[(":older_than", &older_than)],
    )?;
    Ok(())
}

pub fn delete_between(db: &PlacesDb, start: i64, end: i64) -> Result<()> {
    db.execute_cached(
        "DELETE FROM moz_places_metadata
        WHERE updated_at > :start and updated_at < :end",
        &[(":start", &start), (":end", &end)],
    )?;
    Ok(())
}

/// Delete all metadata for the specified place id.
pub fn delete_all_metadata_for_page(db: &PlacesDb, place_id: RowId) -> Result<()> {
    db.execute_cached(
        "DELETE FROM moz_places_metadata
         WHERE place_id = :place_id",
        &[(":place_id", &place_id)],
    )?;
    Ok(())
}

pub fn delete_metadata(
    db: &PlacesDb,
    url: &Url,
    referrer_url: Option<&Url>,
    search_term: Option<&str>,
) -> Result<()> {
    let tx = db.begin_transaction()?;

    // Only delete entries that exactly match the key (url+referrer+search_term) we were passed-in.
    // Do nothing if we were asked to delete a key which doesn't match what's in the database.
    // e.g. referrer_url.is_some(), but a correspodning moz_places entry doesn't exist.
    // In practice this shouldn't happen, or it may imply API misuse, but in either case we shouldn't
    // delete things we were not asked to delete.
    let place_entry = PlaceEntry::fetch(url.as_str(), &tx, None)?;
    let place_entry = match place_entry {
        PlaceEntry::Existing(_) => place_entry,
        PlaceEntry::CreateFor(_, _) => {
            tx.rollback()?;
            return Ok(());
        }
    };
    let referrer_entry = match referrer_url {
        Some(referrer_url) if !referrer_url.as_str().is_empty() => {
            Some(PlaceEntry::fetch(referrer_url.as_str(), &tx, None)?)
        }
        _ => None,
    };
    let referrer_entry = match referrer_entry {
        Some(PlaceEntry::Existing(_)) | None => referrer_entry,
        Some(PlaceEntry::CreateFor(_, _)) => {
            tx.rollback()?;
            return Ok(());
        }
    };
    let search_query_entry = match search_term {
        Some(search_term) if !search_term.is_empty() => {
            Some(SearchQueryEntry::from(search_term, &tx)?)
        }
        _ => None,
    };
    let search_query_entry = match search_query_entry {
        Some(SearchQueryEntry::Existing(_)) | None => search_query_entry,
        Some(SearchQueryEntry::CreateFor(_)) => {
            tx.rollback()?;
            return Ok(());
        }
    };

    let sql = format!(
        "DELETE FROM moz_places_metadata WHERE {} AND {} AND {}",
        place_entry.to_where_arg("place_id"),
        referrer_entry.to_where_arg("referrer_place_id"),
        search_query_entry.to_where_arg("search_query_id")
    );

    tx.execute_cached(&sql, [])?;
    tx.commit()?;

    Ok(())
}

pub fn apply_metadata_observation(
    db: &PlacesDb,
    observation: HistoryMetadataObservation,
    options: NoteHistoryMetadataObservationOptions,
) -> Result<()> {
    if let Some(view_time) = observation.view_time {
        // Consider any view_time observations that are higher than 24hrs to be invalid.
        // This guards against clients passing us wildly inaccurate view_time observations,
        // likely resulting from some measurement bug. If we detect such cases, we fail so
        // that the client has a chance to discover its mistake.
        // When recording a view time, we increment the stored value directly in SQL, which
        // doesn't allow for error detection unless we run an additional SELECT statement to
        // query current cumulative view time and see if incrementing it will result in an
        // overflow. This check is a simpler way to achieve the same goal (detect invalid inputs).
        if view_time > 1000 * 60 * 60 * 24 {
            return Err(InvalidMetadataObservation::ViewTimeTooLong.into());
        }
    }

    // Begin a write transaction. We do this before any other work (e.g. SELECTs) to avoid racing against
    // other writers. Even though we expect to only have a single application writer, a sync writer
    // can come in at any time and change data we depend on, such as moz_places
    // and moz_origins, leaving us in a potentially inconsistent state.
    let tx = db.begin_transaction()?;

    let place_entry = PlaceEntry::fetch(&observation.url, &tx, observation.title.clone())?;
    let result = apply_metadata_observation_impl(&tx, place_entry, observation, options);

    // Inserting into moz_places has side-effects (temp tables are populated via triggers and need to be flushed).
    // This call "finalizes" these side-effects.
    super::delete_pending_temp_tables(db)?;
    match result {
        Ok(_) => tx.commit()?,
        Err(_) => tx.rollback()?,
    };

    result
}

fn apply_metadata_observation_impl(
    tx: &PlacesTransaction<'_>,
    place_entry: PlaceEntry,
    observation: HistoryMetadataObservation,
    options: NoteHistoryMetadataObservationOptions,
) -> Result<()> {
    let referrer_entry = match observation.referrer_url {
        Some(referrer_url) if !referrer_url.is_empty() => {
            Some(PlaceEntry::fetch(&referrer_url, tx, None)?)
        }
        Some(_) | None => None,
    };
    let search_query_entry = match observation.search_term {
        Some(search_term) if !search_term.is_empty() => {
            Some(SearchQueryEntry::from(&search_term, tx)?)
        }
        Some(_) | None => None,
    };

    let compound_key = HistoryMetadataCompoundKey {
        place_entry,
        referrer_entry,
        search_query_entry,
    };

    let observation = MetadataObservation {
        document_type: observation.document_type,
        view_time: observation.view_time,
    };

    let now = Timestamp::now().as_millis() as i64;
    let newer_than = now - DEBOUNCE_WINDOW_MS;
    let matching_metadata = compound_key.lookup(tx, newer_than)?;

    // If a matching record exists, update it; otherwise, insert a new one.
    match matching_metadata {
        Some(metadata_id) => {
            // If document_type isn't part of the observation, make sure we don't accidentally erase what's currently set.
            match observation {
                MetadataObservation {
                    document_type: Some(dt),
                    view_time,
                } => {
                    tx.execute_cached(
                        "UPDATE
                            moz_places_metadata
                        SET
                            document_type = :document_type,
                            total_view_time = total_view_time + :view_time_delta,
                            updated_at = :updated_at
                        WHERE id = :id",
                        rusqlite::named_params! {
                            ":id": metadata_id,
                            ":document_type": dt,
                            ":view_time_delta": view_time.unwrap_or(0),
                            ":updated_at": now
                        },
                    )?;
                }
                MetadataObservation {
                    document_type: None,
                    view_time,
                } => {
                    tx.execute_cached(
                        "UPDATE
                            moz_places_metadata
                        SET
                            total_view_time = total_view_time + :view_time_delta,
                            updated_at = :updated_at
                        WHERE id = :id",
                        rusqlite::named_params! {
                            ":id": metadata_id,
                            ":view_time_delta": view_time.unwrap_or(0),
                            ":updated_at": now
                        },
                    )?;
                }
            }
            Ok(())
        }
        None => insert_metadata_in_tx(tx, compound_key, observation, options),
    }
}

fn insert_metadata_in_tx(
    tx: &PlacesTransaction<'_>,
    key: HistoryMetadataCompoundKey,
    observation: MetadataObservation,
    options: NoteHistoryMetadataObservationOptions,
) -> Result<()> {
    let now = Timestamp::now();

    let referrer_place_id = match key.referrer_entry {
        None => None,
        Some(entry) => Some(entry.get_or_insert(tx)?),
    };

    let search_query_id = match key.search_query_entry {
        None => None,
        Some(entry) => Some(entry.get_or_insert(tx)?),
    };

    // Heavy lifting around moz_places inserting (e.g. updating moz_origins, frecency, etc) is performed via triggers.
    // This lets us simply INSERT here without worrying about the rest.
    let place_id = match (key.place_entry, options.if_page_missing) {
        (PlaceEntry::Existing(id), _) => id,
        (PlaceEntry::CreateFor(_, _), HistoryMetadataPageMissingBehavior::IgnoreObservation) => {
            return Ok(())
        }
        (
            ref entry @ PlaceEntry::CreateFor(_, _),
            HistoryMetadataPageMissingBehavior::InsertPage,
        ) => entry.get_or_insert(tx)?,
    };

    let sql = "INSERT INTO moz_places_metadata
        (place_id, created_at, updated_at, total_view_time, search_query_id, document_type, referrer_place_id)
    VALUES
        (:place_id, :created_at, :updated_at, :total_view_time, :search_query_id, :document_type, :referrer_place_id)";

    tx.execute_cached(
        sql,
        &[
            (":place_id", &place_id as &dyn rusqlite::ToSql),
            (":created_at", &now),
            (":updated_at", &now),
            (":search_query_id", &search_query_id),
            (":referrer_place_id", &referrer_place_id),
            (
                ":document_type",
                &observation.document_type.unwrap_or(DocumentType::Regular),
            ),
            (":total_view_time", &observation.view_time.unwrap_or(0)),
        ],
    )?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api::places_api::ConnectionType;
    use crate::observation::VisitObservation;
    use crate::storage::bookmarks::{
        get_raw_bookmark, insert_bookmark, BookmarkPosition, BookmarkRootGuid, InsertableBookmark,
        InsertableItem,
    };
    use crate::storage::fetch_page_info;
    use crate::storage::history::{
        apply_observation, delete_everything, delete_visits_between, delete_visits_for,
        get_visit_count, url_to_guid,
    };
    use crate::types::VisitType;
    use crate::VisitTransitionSet;
    use pretty_assertions::assert_eq;
    use std::{thread, time};

    macro_rules! assert_table_size {
        ($conn:expr, $table:expr, $count:expr) => {
            assert_eq!(
                $count,
                $conn
                    .try_query_one::<i64, _>(
                        format!("SELECT count(*) FROM {table}", table = $table).as_str(),
                        [],
                        true
                    )
                    .expect("select works")
                    .expect("got count")
            );
        };
    }

    macro_rules! assert_history_metadata_record {
        ($record:expr, url $url:expr, total_time $tvt:expr, search_term $search_term:expr, document_type $document_type:expr, referrer_url $referrer_url:expr, title $title:expr, preview_image_url $preview_image_url:expr) => {
            assert_eq!(String::from($url), $record.url, "url must match");
            assert_eq!($tvt, $record.total_view_time, "total_view_time must match");
            assert_eq!($document_type, $record.document_type, "is_media must match");

            let meta = $record.clone(); // ugh... not sure why this `clone` is necessary.

            match $search_term as Option<&str> {
                Some(t) => assert_eq!(
                    String::from(t),
                    meta.search_term.expect("search_term must be Some"),
                    "search_term must match"
                ),
                None => assert_eq!(
                    true,
                    meta.search_term.is_none(),
                    "search_term expected to be None"
                ),
            };
            match $referrer_url as Option<&str> {
                Some(t) => assert_eq!(
                    String::from(t),
                    meta.referrer_url.expect("referrer_url must be Some"),
                    "referrer_url must match"
                ),
                None => assert_eq!(
                    true,
                    meta.referrer_url.is_none(),
                    "referrer_url expected to be None"
                ),
            };
            match $title as Option<&str> {
                Some(t) => assert_eq!(
                    String::from(t),
                    meta.title.expect("title must be Some"),
                    "title must match"
                ),
                None => assert_eq!(true, meta.title.is_none(), "title expected to be None"),
            };
            match $preview_image_url as Option<&str> {
                Some(t) => assert_eq!(
                    String::from(t),
                    meta.preview_image_url
                        .expect("preview_image_url must be Some"),
                    "preview_image_url must match"
                ),
                None => assert_eq!(
                    true,
                    meta.preview_image_url.is_none(),
                    "preview_image_url expected to be None"
                ),
            };
        };
    }

    macro_rules! assert_total_after_observation {
        ($conn:expr, total_records_after $total_records:expr, total_view_time_after $total_view_time:expr, url $url:expr, view_time $view_time:expr, search_term $search_term:expr, document_type $document_type:expr, referrer_url $referrer_url:expr, title $title:expr) => {
            note_observation!($conn,
                url $url,
                view_time $view_time,
                search_term $search_term,
                document_type $document_type,
                referrer_url $referrer_url,
                title $title
            );

            assert_table_size!($conn, "moz_places_metadata", $total_records);
            let updated = get_latest_for_url($conn, &Url::parse($url).unwrap()).unwrap().unwrap();
            assert_eq!($total_view_time, updated.total_view_time, "total view time must match");
        }
    }

    macro_rules! note_observation {
        ($conn:expr, url $url:expr, view_time $view_time:expr, search_term $search_term:expr, document_type $document_type:expr, referrer_url $referrer_url:expr, title $title:expr) => {
            note_observation!(
                $conn,
                NoteHistoryMetadataObservationOptions::new()
                    .if_page_missing(HistoryMetadataPageMissingBehavior::InsertPage),
                url $url,
                view_time $view_time,
                search_term $search_term,
                document_type $document_type,
                referrer_url $referrer_url,
                title $title
            )
        };
        ($conn:expr, $options:expr, url $url:expr, view_time $view_time:expr, search_term $search_term:expr, document_type $document_type:expr, referrer_url $referrer_url:expr, title $title:expr) => {
            apply_metadata_observation(
                $conn,
                HistoryMetadataObservation {
                    url: String::from($url),
                    view_time: $view_time,
                    search_term: $search_term.map(|s: &str| s.to_string()),
                    document_type: $document_type,
                    referrer_url: $referrer_url.map(|s: &str| s.to_string()),
                    title: $title.map(|s: &str| s.to_string()),
                },
                $options,
            )
            .unwrap();
        };
    }

    macro_rules! assert_after_observation {
        ($conn:expr, total_records_after $total_records:expr, total_view_time_after $total_view_time:expr, url $url:expr, view_time $view_time:expr, search_term $search_term:expr, document_type $document_type:expr, referrer_url $referrer_url:expr, title $title:expr, assertion $assertion:expr) => {
            // can set title on creating a new record
            assert_total_after_observation!($conn,
                total_records_after $total_records,
                total_view_time_after $total_view_time,
                url $url,
                view_time $view_time,
                search_term $search_term,
                document_type $document_type,
                referrer_url $referrer_url,
                title $title
            );

            let m = get_latest_for_url(
                $conn,
                &Url::parse(&String::from($url)).unwrap(),
            )
            .unwrap()
            .unwrap();
            #[allow(clippy::redundant_closure_call)]
            $assertion(m);
        }
    }

    #[test]
    fn test_note_observation() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).unwrap();

        assert_table_size!(&conn, "moz_places_metadata", 0);

        assert_total_after_observation!(&conn,
            total_records_after 1,
            total_view_time_after 1500,
            url "http://mozilla.com/",
            view_time Some(1500),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );

        // debounced! total time was updated
        assert_total_after_observation!(&conn,
            total_records_after 1,
            total_view_time_after 2500,
            url "http://mozilla.com/",
            view_time Some(1000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );

        // different document type, record updated
        assert_total_after_observation!(&conn,
            total_records_after 1,
            total_view_time_after 3500,
            url "http://mozilla.com/",
            view_time Some(1000),
            search_term None,
            document_type Some(DocumentType::Media),
            referrer_url None,
            title None
        );

        // referrer set
        assert_total_after_observation!(&conn,
            total_records_after 2,
            total_view_time_after 2000,
            url "http://mozilla.com/",
            view_time Some(2000),
            search_term None,
            document_type Some(DocumentType::Media),
            referrer_url Some("https://news.website"),
            title None
        );

        // search term and referrer are set
        assert_total_after_observation!(&conn,
            total_records_after 3,
            total_view_time_after 1100,
            url "http://mozilla.com/",
            view_time Some(1100),
            search_term Some("firefox"),
            document_type Some(DocumentType::Media),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=firefox"),
            title None
        );

        // debounce!
        assert_total_after_observation!(&conn,
            total_records_after 3,
            total_view_time_after 6100,
            url "http://mozilla.com/",
            view_time Some(5000),
            search_term Some("firefox"),
            document_type Some(DocumentType::Media),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=firefox"),
            title None
        );

        // different url now
        assert_total_after_observation!(&conn,
            total_records_after 4,
            total_view_time_after 3000,
            url "http://mozilla.com/another",
            view_time Some(3000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://news.website/tech"),
            title None
        );

        // shared origin for both url and referrer
        assert_total_after_observation!(&conn,
            total_records_after 5,
            total_view_time_after 100000,
            url "https://www.youtube.com/watch?v=tpiyEe_CqB4",
            view_time Some(100000),
            search_term Some("cute cat"),
            document_type Some(DocumentType::Media),
            referrer_url Some("https://www.youtube.com/results?search_query=cute+cat"),
            title None
        );

        // empty search term/referrer url are treated the same as None
        assert_total_after_observation!(&conn,
            total_records_after 6,
            total_view_time_after 80000,
            url "https://www.youtube.com/watch?v=daff43jif3",
            view_time Some(80000),
            search_term Some(""),
            document_type Some(DocumentType::Media),
            referrer_url Some(""),
            title None
        );

        assert_total_after_observation!(&conn,
            total_records_after 6,
            total_view_time_after 90000,
            url "https://www.youtube.com/watch?v=daff43jif3",
            view_time Some(10000),
            search_term None,
            document_type Some(DocumentType::Media),
            referrer_url None,
            title None
        );

        // document type recording
        assert_total_after_observation!(&conn,
            total_records_after 7,
            total_view_time_after 0,
            url "https://www.youtube.com/watch?v=fds32fds",
            view_time None,
            search_term None,
            document_type Some(DocumentType::Media),
            referrer_url None,
            title None
        );

        // now, update the view time as a separate call
        assert_total_after_observation!(&conn,
            total_records_after 7,
            total_view_time_after 1338,
            url "https://www.youtube.com/watch?v=fds32fds",
            view_time Some(1338),
            search_term None,
            document_type None,
            referrer_url None,
            title None
        );

        // and again, bump the view time
        assert_total_after_observation!(&conn,
            total_records_after 7,
            total_view_time_after 2000,
            url "https://www.youtube.com/watch?v=fds32fds",
            view_time Some(662),
            search_term None,
            document_type None,
            referrer_url None,
            title None
        );

        // now try the other way - record view time first, document type after.
        // and again, bump the view time
        assert_after_observation!(&conn,
            total_records_after 8,
            total_view_time_after 662,
            url "https://www.youtube.com/watch?v=dasdg34d",
            view_time Some(662),
            search_term None,
            document_type None,
            referrer_url None,
            title None,
            assertion |m: HistoryMetadata| { assert_eq!(DocumentType::Regular, m.document_type) }
        );

        assert_after_observation!(&conn,
            total_records_after 8,
            total_view_time_after 662,
            url "https://www.youtube.com/watch?v=dasdg34d",
            view_time None,
            search_term None,
            document_type Some(DocumentType::Media),
            referrer_url None,
            title None,
            assertion |m: HistoryMetadata| { assert_eq!(DocumentType::Media, m.document_type) }
        );

        // document type not overwritten (e.g. remains 1, not default 0).
        assert_after_observation!(&conn,
            total_records_after 8,
            total_view_time_after 675,
            url "https://www.youtube.com/watch?v=dasdg34d",
            view_time Some(13),
            search_term None,
            document_type None,
            referrer_url None,
            title None,
            assertion |m: HistoryMetadata| { assert_eq!(DocumentType::Media, m.document_type) }
        );

        // can set title on creating a new record
        assert_after_observation!(&conn,
            total_records_after 9,
            total_view_time_after 13,
            url "https://www.youtube.com/watch?v=dasdsada",
            view_time Some(13),
            search_term None,
            document_type None,
            referrer_url None,
            title Some("hello!"),
            assertion |m: HistoryMetadata| { assert_eq!(Some(String::from("hello!")), m.title) }
        );

        // can not update title after
        assert_after_observation!(&conn,
            total_records_after 9,
            total_view_time_after 26,
            url "https://www.youtube.com/watch?v=dasdsada",
            view_time Some(13),
            search_term None,
            document_type None,
            referrer_url None,
            title Some("world!"),
            assertion |m: HistoryMetadata| { assert_eq!(Some(String::from("hello!")), m.title) }
        );
    }

    #[test]
    fn test_note_observation_invalid_view_time() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");

        note_observation!(&conn,
            url "https://www.mozilla.org/",
            view_time None,
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );

        // 48 hrs is clearly a bad view to observe.
        assert!(apply_metadata_observation(
            &conn,
            HistoryMetadataObservation {
                url: String::from("https://www.mozilla.org"),
                view_time: Some(1000 * 60 * 60 * 24 * 2),
                search_term: None,
                document_type: None,
                referrer_url: None,
                title: None
            },
            NoteHistoryMetadataObservationOptions::new(),
        )
        .is_err());

        // 12 hrs is assumed to be "plausible".
        assert!(apply_metadata_observation(
            &conn,
            HistoryMetadataObservation {
                url: String::from("https://www.mozilla.org"),
                view_time: Some(1000 * 60 * 60 * 12),
                search_term: None,
                document_type: None,
                referrer_url: None,
                title: None
            },
            NoteHistoryMetadataObservationOptions::new(),
        )
        .is_ok());
    }

    #[test]
    fn test_get_between() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");

        assert_eq!(0, get_between(&conn, 0, 0).unwrap().len());

        let beginning = Timestamp::now().as_millis() as i64;
        note_observation!(&conn,
            url "http://mozilla.com/another",
            view_time Some(3000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://news.website/tech"),
            title None
        );
        let after_meta1 = Timestamp::now().as_millis() as i64;

        assert_eq!(0, get_between(&conn, 0, beginning - 1).unwrap().len());
        assert_eq!(1, get_between(&conn, 0, after_meta1).unwrap().len());

        thread::sleep(time::Duration::from_millis(10));

        note_observation!(&conn,
            url "http://mozilla.com/video/",
            view_time Some(1000),
            search_term None,
            document_type Some(DocumentType::Media),
            referrer_url None,
            title None
        );
        let after_meta2 = Timestamp::now().as_millis() as i64;

        assert_eq!(1, get_between(&conn, beginning, after_meta1).unwrap().len());
        assert_eq!(2, get_between(&conn, beginning, after_meta2).unwrap().len());
        assert_eq!(
            1,
            get_between(&conn, after_meta1, after_meta2).unwrap().len()
        );
        assert_eq!(
            0,
            get_between(&conn, after_meta2, after_meta2 + 1)
                .unwrap()
                .len()
        );
    }

    #[test]
    fn test_get_since() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");

        assert_eq!(0, get_since(&conn, 0).unwrap().len());

        let beginning = Timestamp::now().as_millis() as i64;
        note_observation!(&conn,
            url "http://mozilla.com/another",
            view_time Some(3000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://news.website/tech"),
            title None
        );
        let after_meta1 = Timestamp::now().as_millis() as i64;

        assert_eq!(1, get_since(&conn, 0).unwrap().len());
        assert_eq!(1, get_since(&conn, beginning).unwrap().len());
        assert_eq!(0, get_since(&conn, after_meta1).unwrap().len());

        // thread::sleep(time::Duration::from_millis(50));

        note_observation!(&conn,
            url "http://mozilla.com/video/",
            view_time Some(1000),
            search_term None,
            document_type Some(DocumentType::Media),
            referrer_url None,
            title None
        );
        let after_meta2 = Timestamp::now().as_millis() as i64;
        assert_eq!(2, get_since(&conn, beginning).unwrap().len());
        assert_eq!(1, get_since(&conn, after_meta1).unwrap().len());
        assert_eq!(0, get_since(&conn, after_meta2).unwrap().len());
    }

    #[test]
    fn test_get_highlights() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");

        // Empty database is fine.
        assert_eq!(
            0,
            get_highlights(
                &conn,
                HistoryHighlightWeights {
                    view_time: 1.0,
                    frequency: 1.0
                },
                10
            )
            .unwrap()
            .len()
        );

        // Database with "normal" history but no metadata observations is fine.
        apply_observation(
            &conn,
            VisitObservation::new(
                Url::parse("https://www.reddit.com/r/climbing").expect("Should parse URL"),
            )
            .with_visit_type(VisitType::Link)
            .with_at(Timestamp::now()),
        )
        .expect("Should apply observation");
        assert_eq!(
            0,
            get_highlights(
                &conn,
                HistoryHighlightWeights {
                    view_time: 1.0,
                    frequency: 1.0
                },
                10
            )
            .unwrap()
            .len()
        );

        // three observation to url1, each recording a second of view time.
        note_observation!(&conn,
            url "http://mozilla.com/1",
            view_time Some(1000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://news.website/tech"),
            title None
        );

        note_observation!(&conn,
            url "http://mozilla.com/1",
            view_time Some(1000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://news.website/tech"),
            title None
        );

        note_observation!(&conn,
            url "http://mozilla.com/1",
            view_time Some(1000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://news.website/tech"),
            title None
        );

        // one observation to url2 for 3.5s of view time.
        note_observation!(&conn,
            url "http://mozilla.com/2",
            view_time Some(3500),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://news.website/tech"),
            title None
        );

        // The three visits to /2 got "debounced" into a single metadata entry (since they were made in quick succession).
        // We'll calculate the scoring as follows:
        // - for /1: 1.0 * 1/2 + 1.0 * 3000/6500 = 0.9615...
        // - for /2: 1.0 * 1/2 + 1.0 * 3500/6500 = 1.0384...
        // (above, 1/2 means 1 entry out of 2 entries total).

        let even_weights = HistoryHighlightWeights {
            view_time: 1.0,
            frequency: 1.0,
        };
        let highlights1 = get_highlights(&conn, even_weights.clone(), 10).unwrap();
        assert_eq!(2, highlights1.len());
        assert_eq!("http://mozilla.com/2", highlights1[0].url);

        // Since we have an equal amount of metadata entries, providing a very high view_time weight won't change the ranking.
        let frequency_heavy_weights = HistoryHighlightWeights {
            view_time: 1.0,
            frequency: 100.0,
        };
        let highlights2 = get_highlights(&conn, frequency_heavy_weights, 10).unwrap();
        assert_eq!(2, highlights2.len());
        assert_eq!("http://mozilla.com/2", highlights2[0].url);

        // Now, make an observation for url /1, but with a different metadata key.
        // It won't debounce, producing an additional entry for /1.
        // Total view time for /1 is now 3100 (vs 3500 for /2).
        note_observation!(&conn,
            url "http://mozilla.com/1",
            view_time Some(100),
            search_term Some("test search"),
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://news.website/tech"),
            title None
        );

        // Since we now have 2 metadata entries for /1, it ranks higher with even weights.
        let highlights3 = get_highlights(&conn, even_weights, 10).unwrap();
        assert_eq!(2, highlights3.len());
        assert_eq!("http://mozilla.com/1", highlights3[0].url);

        // With a high-enough weight for view_time, we can flip this order.
        // Even though we had 2x entries for /1, it now ranks second due to its lower total view time (3100 vs 3500).
        let view_time_heavy_weights = HistoryHighlightWeights {
            view_time: 6.0,
            frequency: 1.0,
        };
        let highlights4 = get_highlights(&conn, view_time_heavy_weights, 10).unwrap();
        assert_eq!(2, highlights4.len());
        assert_eq!("http://mozilla.com/2", highlights4[0].url);
    }

    #[test]
    fn test_get_highlights_no_viewtime() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");

        // Make sure we work if the only observations for a URL have a view time of zero.
        note_observation!(&conn,
            url "http://mozilla.com/1",
            view_time Some(0),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://news.website/tech"),
            title None
        );
        let highlights = get_highlights(
            &conn,
            HistoryHighlightWeights {
                view_time: 1.0,
                frequency: 1.0,
            },
            2,
        )
        .unwrap();
        assert_eq!(highlights.len(), 1);
        assert_eq!(highlights[0].score, 0.0);
    }

    #[test]
    fn test_query() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");
        let now = Timestamp::now();

        // need a history observation to get a title query working.
        let observation1 = VisitObservation::new(Url::parse("https://www.cbc.ca/news/politics/federal-budget-2021-freeland-zimonjic-1.5991021").unwrap())
                .with_at(now)
                .with_title(Some(String::from("Budget vows to build &#x27;for the long term&#x27; as it promises child care cash, projects massive deficits | CBC News")))
                .with_preview_image_url(Some(Url::parse("https://i.cbc.ca/1.5993583.1618861792!/cpImage/httpImage/image.jpg_gen/derivatives/16x9_620/fedbudget-20210419.jpg").unwrap()))
                .with_is_remote(false)
                .with_visit_type(VisitType::Link);
        apply_observation(&conn, observation1).unwrap();

        note_observation!(
            &conn,
            url "https://www.cbc.ca/news/politics/federal-budget-2021-freeland-zimonjic-1.5991021",
            view_time Some(20000),
            search_term Some("cbc federal budget 2021"),
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://yandex.ru/search/?text=cbc%20federal%20budget%202021&lr=21512"),
            title None
        );

        note_observation!(
            &conn,
            url "https://stackoverflow.com/questions/37777675/how-to-create-a-formatted-string-out-of-a-literal-in-rust",
            view_time Some(20000),
            search_term Some("rust string format"),
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://yandex.ru/search/?lr=21512&text=rust%20string%20format"),
            title None
        );

        note_observation!(
            &conn,
            url "https://www.sqlite.org/lang_corefunc.html#instr",
            view_time Some(20000),
            search_term Some("sqlite like"),
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=sqlite+like"),
            title None
        );

        note_observation!(
            &conn,
            url "https://www.youtube.com/watch?v=tpiyEe_CqB4",
            view_time Some(100000),
            search_term Some("cute cat"),
            document_type Some(DocumentType::Media),
            referrer_url Some("https://www.youtube.com/results?search_query=cute+cat"),
            title None
        );

        // query by title
        let meta = query(&conn, "child care", 10).expect("query should work");
        assert_eq!(1, meta.len(), "expected exactly one result");
        assert_history_metadata_record!(meta[0],
            url "https://www.cbc.ca/news/politics/federal-budget-2021-freeland-zimonjic-1.5991021",
            total_time 20000,
            search_term Some("cbc federal budget 2021"),
            document_type DocumentType::Regular,
            referrer_url Some("https://yandex.ru/search/?text=cbc%20federal%20budget%202021&lr=21512"),
            title Some("Budget vows to build &#x27;for the long term&#x27; as it promises child care cash, projects massive deficits | CBC News"),
            preview_image_url Some("https://i.cbc.ca/1.5993583.1618861792!/cpImage/httpImage/image.jpg_gen/derivatives/16x9_620/fedbudget-20210419.jpg")
        );

        // query by search term
        let meta = query(&conn, "string format", 10).expect("query should work");
        assert_eq!(1, meta.len(), "expected exactly one result");
        assert_history_metadata_record!(meta[0],
            url "https://stackoverflow.com/questions/37777675/how-to-create-a-formatted-string-out-of-a-literal-in-rust",
            total_time 20000,
            search_term Some("rust string format"),
            document_type DocumentType::Regular,
            referrer_url Some("https://yandex.ru/search/?lr=21512&text=rust%20string%20format"),
            title None,
            preview_image_url None
        );

        // query by url
        let meta = query(&conn, "instr", 10).expect("query should work");
        assert_history_metadata_record!(meta[0],
            url "https://www.sqlite.org/lang_corefunc.html#instr",
            total_time 20000,
            search_term Some("sqlite like"),
            document_type DocumentType::Regular,
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=sqlite+like"),
            title None,
            preview_image_url None
        );

        // by url, referrer domain is different
        let meta = query(&conn, "youtube", 10).expect("query should work");
        assert_history_metadata_record!(meta[0],
            url "https://www.youtube.com/watch?v=tpiyEe_CqB4",
            total_time 100000,
            search_term Some("cute cat"),
            document_type DocumentType::Media,
            referrer_url Some("https://www.youtube.com/results?search_query=cute+cat"),
            title None,
            preview_image_url None
        );
    }

    #[test]
    fn test_delete_metadata() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");

        // url  |   search_term |   referrer
        // 1    |    1          |   1
        // 1    |    1          |   0
        // 1    |    0          |   1
        // 1    |    0          |   0

        note_observation!(&conn,
            url "http://mozilla.com/1",
            view_time Some(20000),
            search_term Some("1 with search"),
            document_type Some(DocumentType::Regular),
            referrer_url Some("http://mozilla.com/"),
            title None
        );

        note_observation!(&conn,
            url "http://mozilla.com/1",
            view_time Some(20000),
            search_term Some("1 with search"),
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );

        note_observation!(&conn,
            url "http://mozilla.com/1",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("http://mozilla.com/"),
            title None
        );

        note_observation!(&conn,
            url "http://mozilla.com/1",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );

        note_observation!(&conn,
            url "http://mozilla.com/2",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );

        note_observation!(&conn,
            url "http://mozilla.com/2",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("http://mozilla.com/"),
            title None
        );

        thread::sleep(time::Duration::from_millis(10));
        // same observation a bit later:
        note_observation!(&conn,
            url "http://mozilla.com/2",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("http://mozilla.com/"),
            title None
        );

        assert_eq!(6, get_since(&conn, 0).expect("get worked").len());
        delete_metadata(
            &conn,
            &Url::parse("http://mozilla.com/1").unwrap(),
            None,
            None,
        )
        .expect("delete metadata");
        assert_eq!(5, get_since(&conn, 0).expect("get worked").len());

        delete_metadata(
            &conn,
            &Url::parse("http://mozilla.com/1").unwrap(),
            Some(&Url::parse("http://mozilla.com/").unwrap()),
            None,
        )
        .expect("delete metadata");
        assert_eq!(4, get_since(&conn, 0).expect("get worked").len());

        delete_metadata(
            &conn,
            &Url::parse("http://mozilla.com/1").unwrap(),
            Some(&Url::parse("http://mozilla.com/").unwrap()),
            Some("1 with search"),
        )
        .expect("delete metadata");
        assert_eq!(3, get_since(&conn, 0).expect("get worked").len());

        delete_metadata(
            &conn,
            &Url::parse("http://mozilla.com/1").unwrap(),
            None,
            Some("1 with search"),
        )
        .expect("delete metadata");
        assert_eq!(2, get_since(&conn, 0).expect("get worked").len());

        // key doesn't match, do nothing
        delete_metadata(
            &conn,
            &Url::parse("http://mozilla.com/2").unwrap(),
            Some(&Url::parse("http://wrong-referrer.com").unwrap()),
            Some("2 with search"),
        )
        .expect("delete metadata");
        assert_eq!(2, get_since(&conn, 0).expect("get worked").len());
    }

    #[test]
    fn test_delete_older_than() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");

        let beginning = Timestamp::now().as_millis() as i64;

        note_observation!(&conn,
            url "http://mozilla.com/1",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );
        let after_meta1 = Timestamp::now().as_millis() as i64;

        thread::sleep(time::Duration::from_millis(10));

        note_observation!(&conn,
            url "http://mozilla.com/2",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );

        thread::sleep(time::Duration::from_millis(10));

        note_observation!(&conn,
            url "http://mozilla.com/3",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );
        let after_meta3 = Timestamp::now().as_millis() as i64;

        // deleting nothing.
        delete_older_than(&conn, beginning).expect("delete worked");
        assert_eq!(3, get_since(&conn, beginning).expect("get worked").len());

        // boundary condition, should only delete the first one.
        delete_older_than(&conn, after_meta1).expect("delete worked");
        assert_eq!(2, get_since(&conn, beginning).expect("get worked").len());
        assert_eq!(
            None,
            get_latest_for_url(&conn, &Url::parse("http://mozilla.com/1").expect("url"))
                .expect("get")
        );

        // delete everything now.
        delete_older_than(&conn, after_meta3).expect("delete worked");
        assert_eq!(0, get_since(&conn, beginning).expect("get worked").len());
    }

    #[test]
    fn test_delete_between() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");

        let beginning = Timestamp::now().as_millis() as i64;
        thread::sleep(time::Duration::from_millis(10));

        note_observation!(&conn,
            url "http://mozilla.com/1",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );

        thread::sleep(time::Duration::from_millis(10));

        note_observation!(&conn,
            url "http://mozilla.com/2",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );
        let after_meta2 = Timestamp::now().as_millis() as i64;

        thread::sleep(time::Duration::from_millis(10));

        note_observation!(&conn,
            url "http://mozilla.com/3",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );
        let after_meta3 = Timestamp::now().as_millis() as i64;

        // deleting meta 3
        delete_between(&conn, after_meta2, after_meta3).expect("delete worked");
        assert_eq!(2, get_since(&conn, beginning).expect("get worked").len());
        assert_eq!(
            None,
            get_latest_for_url(&conn, &Url::parse("http://mozilla.com/3").expect("url"))
                .expect("get")
        );
    }

    #[test]
    fn test_metadata_deletes_do_not_affect_places() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");

        note_observation!(
            &conn,
            url "https://www.mozilla.org/first/",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox"),
            title None
        );

        note_observation!(
            &conn,
            url "https://www.mozilla.org/",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox"),
            title None
        );
        let after_meta_added = Timestamp::now().as_millis() as i64;

        // Delete all metadata.
        delete_older_than(&conn, after_meta_added).expect("delete older than worked");

        // Query places. Records there should not have been affected by the delete above.
        // 2 for metadata entries + 1 for referrer url.
        assert_table_size!(&conn, "moz_places", 3);
    }

    #[test]
    fn test_delete_history_also_deletes_metadata_bookmarked() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");
        // Item 1 - bookmarked with regular visits and history metadata
        let url = Url::parse("https://www.mozilla.org/bookmarked").unwrap();
        let bm_guid: SyncGuid = "bookmarkAAAA".into();
        let bm = InsertableBookmark {
            parent_guid: BookmarkRootGuid::Unfiled.into(),
            position: BookmarkPosition::Append,
            date_added: None,
            last_modified: None,
            guid: Some(bm_guid.clone()),
            url: url.clone(),
            title: Some("bookmarked page".to_string()),
        };
        insert_bookmark(&conn, InsertableItem::Bookmark { b: bm }).expect("bookmark should insert");
        let obs = VisitObservation::new(url.clone()).with_visit_type(VisitType::Link);
        apply_observation(&conn, obs).expect("Should apply visit");
        note_observation!(
            &conn,
            url url.to_string(),
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox"),
            title None
        );

        // Check the DB is what we expect before deleting.
        assert_eq!(
            get_visit_count(&conn, VisitTransitionSet::empty()).unwrap(),
            1
        );
        let place_guid = url_to_guid(&conn, &url)
            .expect("is valid")
            .expect("should exist");

        delete_visits_for(&conn, &place_guid).expect("should work");
        // bookmark must still exist.
        assert!(get_raw_bookmark(&conn, &bm_guid).unwrap().is_some());
        // place exists but has no visits.
        let pi = fetch_page_info(&conn, &url)
            .expect("should work")
            .expect("should exist");
        assert!(pi.last_visit_id.is_none());
        // and no metadata observations.
        assert!(get_latest_for_url(&conn, &url)
            .expect("should work")
            .is_none());
    }

    #[test]
    fn test_delete_history_also_deletes_metadata_not_bookmarked() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");
        // Item is not bookmarked, but has regular visit and a metadata observation.
        let url = Url::parse("https://www.mozilla.org/not-bookmarked").unwrap();
        let obs = VisitObservation::new(url.clone()).with_visit_type(VisitType::Link);
        apply_observation(&conn, obs).expect("Should apply visit");
        note_observation!(
            &conn,
            url url.to_string(),
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox"),
            title None
        );

        // Check the DB is what we expect before deleting.
        assert_eq!(
            get_visit_count(&conn, VisitTransitionSet::empty()).unwrap(),
            1
        );
        let place_guid = url_to_guid(&conn, &url)
            .expect("is valid")
            .expect("should exist");

        delete_visits_for(&conn, &place_guid).expect("should work");
        // place no longer exists.
        assert!(fetch_page_info(&conn, &url).expect("should work").is_none());
        assert!(get_latest_for_url(&conn, &url)
            .expect("should work")
            .is_none());
    }

    #[test]
    fn test_delete_history_also_deletes_metadata_no_visits() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");
        // Item is not bookmarked, no regular visits but a metadata observation.
        let url = Url::parse("https://www.mozilla.org/no-visits").unwrap();
        note_observation!(
            &conn,
            url url.to_string(),
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox"),
            title None
        );

        // Check the DB is what we expect before deleting.
        assert_eq!(
            get_visit_count(&conn, VisitTransitionSet::empty()).unwrap(),
            0
        );
        let place_guid = url_to_guid(&conn, &url)
            .expect("is valid")
            .expect("should exist");

        delete_visits_for(&conn, &place_guid).expect("should work");
        // place no longer exists.
        assert!(fetch_page_info(&conn, &url).expect("should work").is_none());
        assert!(get_latest_for_url(&conn, &url)
            .expect("should work")
            .is_none());
    }

    #[test]
    fn test_delete_between_also_deletes_metadata() -> Result<()> {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");

        let now = Timestamp::now();
        let url = Url::parse("https://www.mozilla.org/").unwrap();
        let other_url =
            Url::parse("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox")
                .unwrap();
        let start_timestamp = Timestamp(now.as_millis() - 1000_u64);
        let end_timestamp = Timestamp(now.as_millis() + 1000_u64);
        let observation1 = VisitObservation::new(url.clone())
            .with_at(start_timestamp)
            .with_title(Some(String::from("Test page 0")))
            .with_is_remote(false)
            .with_visit_type(VisitType::Link);

        let observation2 = VisitObservation::new(other_url)
            .with_at(end_timestamp)
            .with_title(Some(String::from("Test page 1")))
            .with_is_remote(false)
            .with_visit_type(VisitType::Link);

        apply_observation(&conn, observation1).expect("Should apply visit");
        apply_observation(&conn, observation2).expect("Should apply visit");

        note_observation!(
            &conn,
            url "https://www.mozilla.org/",
            view_time Some(20000),
            search_term Some("mozilla firefox"),
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox"),
            title None
        );
        assert_eq!(
            "https://www.mozilla.org/",
            get_latest_for_url(&conn, &url)?.unwrap().url
        );
        delete_visits_between(&conn, start_timestamp, end_timestamp)?;
        assert_eq!(None, get_latest_for_url(&conn, &url)?);
        Ok(())
    }

    #[test]
    fn test_places_delete_triggers_with_bookmarks() {
        // The cleanup functionality lives as a TRIGGER in `create_shared_triggers`.
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");

        let now = Timestamp::now();
        let url = Url::parse("https://www.mozilla.org/").unwrap();
        let parent_url =
            Url::parse("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox")
                .unwrap();

        let observation1 = VisitObservation::new(url.clone())
            .with_at(now)
            .with_title(Some(String::from("Test page 0")))
            .with_is_remote(false)
            .with_visit_type(VisitType::Link);

        let observation2 = VisitObservation::new(parent_url.clone())
            .with_at(now)
            .with_title(Some(String::from("Test page 1")))
            .with_is_remote(false)
            .with_visit_type(VisitType::Link);

        apply_observation(&conn, observation1).expect("Should apply visit");
        apply_observation(&conn, observation2).expect("Should apply visit");

        assert_table_size!(&conn, "moz_bookmarks", 5);

        // add bookmark for the page we have a metadata entry
        insert_bookmark(
            &conn,
            InsertableItem::Bookmark {
                b: InsertableBookmark {
                    parent_guid: BookmarkRootGuid::Unfiled.into(),
                    position: BookmarkPosition::Append,
                    date_added: None,
                    last_modified: None,
                    guid: Some(SyncGuid::from("cccccccccccc")),
                    url,
                    title: None,
                },
            },
        )
        .expect("bookmark insert worked");

        // add another bookmark to the "parent" of our metadata entry
        insert_bookmark(
            &conn,
            InsertableItem::Bookmark {
                b: InsertableBookmark {
                    parent_guid: BookmarkRootGuid::Unfiled.into(),
                    position: BookmarkPosition::Append,
                    date_added: None,
                    last_modified: None,
                    guid: Some(SyncGuid::from("ccccccccccca")),
                    url: parent_url,
                    title: None,
                },
            },
        )
        .expect("bookmark insert worked");

        assert_table_size!(&conn, "moz_bookmarks", 7);
        assert_table_size!(&conn, "moz_origins", 2);

        note_observation!(
            &conn,
            url "https://www.mozilla.org/",
            view_time Some(20000),
            search_term Some("mozilla firefox"),
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox"),
            title None
        );

        assert_table_size!(&conn, "moz_origins", 2);

        // this somehow deletes 1 origin record, and our metadata
        delete_everything(&conn).expect("places wipe succeeds");

        assert_table_size!(&conn, "moz_places_metadata", 0);
        assert_table_size!(&conn, "moz_places_metadata_search_queries", 0);
    }

    #[test]
    fn test_places_delete_triggers() {
        // The cleanup functionality lives as a TRIGGER in `create_shared_triggers`.
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");

        let now = Timestamp::now();
        let observation1 = VisitObservation::new(Url::parse("https://www.mozilla.org/").unwrap())
            .with_at(now)
            .with_title(Some(String::from("Test page 1")))
            .with_is_remote(false)
            .with_visit_type(VisitType::Link);
        let observation2 =
            VisitObservation::new(Url::parse("https://www.mozilla.org/another/").unwrap())
                .with_at(Timestamp(now.as_millis() + 10000))
                .with_title(Some(String::from("Test page 3")))
                .with_is_remote(false)
                .with_visit_type(VisitType::Link);
        let observation3 =
            VisitObservation::new(Url::parse("https://www.mozilla.org/first/").unwrap())
                .with_at(Timestamp(now.as_millis() - 10000))
                .with_title(Some(String::from("Test page 0")))
                .with_is_remote(true)
                .with_visit_type(VisitType::Link);
        apply_observation(&conn, observation1).expect("Should apply visit");
        apply_observation(&conn, observation2).expect("Should apply visit");
        apply_observation(&conn, observation3).expect("Should apply visit");

        note_observation!(
            &conn,
            url "https://www.mozilla.org/first/",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox"),
            title None
        );

        note_observation!(
            &conn,
            url "https://www.mozilla.org/",
            view_time Some(20000),
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox"),
            title None
        );

        note_observation!(
            &conn,
            url "https://www.mozilla.org/",
            view_time Some(20000),
            search_term Some("mozilla"),
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox"),
            title None
        );

        note_observation!(
            &conn,
            url "https://www.mozilla.org/",
            view_time Some(25000),
            search_term Some("firefox"),
            document_type Some(DocumentType::Media),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox"),
            title None
        );

        note_observation!(
            &conn,
            url "https://www.mozilla.org/another/",
            view_time Some(20000),
            search_term Some("mozilla"),
            document_type Some(DocumentType::Regular),
            referrer_url Some("https://www.google.com/search?client=firefox-b-d&q=mozilla+firefox"),
            title None
        );

        // double-check that we have the 'firefox' search query entry.
        assert!(conn
            .try_query_one::<i64, _>(
                "SELECT id FROM moz_places_metadata_search_queries WHERE term = :term",
                rusqlite::named_params! { ":term": "firefox" },
                true
            )
            .expect("select works")
            .is_some());

        // Delete our first page & its visits. Note that /another/ page will remain in place.
        delete_visits_between(
            &conn,
            Timestamp(now.as_millis() - 1000),
            Timestamp(now.as_millis() + 1000),
        )
        .expect("delete worked");

        let meta1 =
            get_latest_for_url(&conn, &Url::parse("https://www.mozilla.org/").expect("url"))
                .expect("get worked");
        let meta2 = get_latest_for_url(
            &conn,
            &Url::parse("https://www.mozilla.org/another/").expect("url"),
        )
        .expect("get worked");

        assert!(meta1.is_none(), "expected metadata to have been deleted");
        // Verify that if a history metadata entry was entered **after** the visit
        // then we delete the range of the metadata, and not the visit. The metadata
        // is still deleted
        assert!(meta2.is_none(), "expected metadata to been deleted");

        // The 'mozilla' search query entry is deleted since the delete cascades.
        assert!(
            conn.try_query_one::<i64, _>(
                "SELECT id FROM moz_places_metadata_search_queries WHERE term = :term",
                rusqlite::named_params! { ":term": "mozilla" },
                true
            )
            .expect("select works")
            .is_none(),
            "search_query records with related metadata should have been deleted"
        );

        // don't have the 'firefox' search query entry either, nothing points to it.
        assert!(
            conn.try_query_one::<i64, _>(
                "SELECT id FROM moz_places_metadata_search_queries WHERE term = :term",
                rusqlite::named_params! { ":term": "firefox" },
                true
            )
            .expect("select works")
            .is_none(),
            "search_query records without related metadata should have been deleted"
        );

        // now, let's wipe places, and make sure none of the metadata stuff remains.
        delete_everything(&conn).expect("places wipe succeeds");

        assert_table_size!(&conn, "moz_places_metadata", 0);
        assert_table_size!(&conn, "moz_places_metadata_search_queries", 0);
    }

    #[test]
    fn test_if_page_missing_behavior() {
        let conn = PlacesDb::open_in_memory(ConnectionType::ReadWrite).expect("memory db");

        note_observation!(
            &conn,
            NoteHistoryMetadataObservationOptions::new()
                .if_page_missing(HistoryMetadataPageMissingBehavior::IgnoreObservation),
            url "https://www.example.com/",
            view_time None,
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );

        let observations = get_since(&conn, 0).expect("should get all metadata observations");
        assert_eq!(observations, &[]);

        let visit_observation =
            VisitObservation::new(Url::parse("https://www.example.com/").unwrap())
                .with_at(Timestamp::now());
        apply_observation(&conn, visit_observation).expect("should apply visit observation");

        note_observation!(
            &conn,
            NoteHistoryMetadataObservationOptions::new()
                .if_page_missing(HistoryMetadataPageMissingBehavior::IgnoreObservation),
            url "https://www.example.com/",
            view_time None,
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );

        let observations = get_since(&conn, 0).expect("should get all metadata observations");
        assert_eq!(
            observations
                .into_iter()
                .map(|m| m.url)
                .collect::<Vec<String>>(),
            &["https://www.example.com/"]
        );

        note_observation!(
            &conn,
            NoteHistoryMetadataObservationOptions::new()
                .if_page_missing(HistoryMetadataPageMissingBehavior::InsertPage),
            url "https://www.example.org/",
            view_time None,
            search_term None,
            document_type Some(DocumentType::Regular),
            referrer_url None,
            title None
        );

        let observations = get_since(&conn, 0).expect("should get all metadata observations");
        assert_eq!(
            observations
                .into_iter()
                .map(|m| m.url)
                .collect::<Vec<String>>(),
            &[
                "https://www.example.org/", // Newest first.
                "https://www.example.com/",
            ],
        );
    }
}