suggest/db.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
/* 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 std::{cell::OnceCell, path::Path, sync::Arc};
use interrupt_support::{SqlInterruptHandle, SqlInterruptScope};
use parking_lot::{Mutex, MutexGuard};
use rusqlite::{
named_params,
types::{FromSql, ToSql},
Connection,
};
use sql_support::{open_database, repeat_sql_vars, ConnExt};
use crate::{
config::{SuggestGlobalConfig, SuggestProviderConfig},
error::RusqliteResultExt,
fakespot,
geoname::GeonameCache,
pocket::{split_keyword, KeywordConfidence},
provider::{AmpMatchingStrategy, SuggestionProvider},
query::{full_keywords_to_fts_content, FtsQuery},
rs::{
DownloadedAmoSuggestion, DownloadedAmpSuggestion, DownloadedExposureSuggestion,
DownloadedFakespotSuggestion, DownloadedMdnSuggestion, DownloadedPocketSuggestion,
DownloadedWikipediaSuggestion, Record, SuggestRecordId,
},
schema::{clear_database, SuggestConnectionInitializer},
suggestion::{cook_raw_suggestion_url, FtsMatchInfo, Suggestion},
util::full_keyword,
weather::WeatherCache,
Result, SuggestionQuery,
};
/// The metadata key whose value is a JSON string encoding a
/// `SuggestGlobalConfig`, which contains global Suggest configuration data.
pub const GLOBAL_CONFIG_META_KEY: &str = "global_config";
/// Prefix of metadata keys whose values are JSON strings encoding
/// `SuggestProviderConfig`, which contains per-provider configuration data. The
/// full key is this prefix plus the `SuggestionProvider` value as a u8.
pub const PROVIDER_CONFIG_META_KEY_PREFIX: &str = "provider_config_";
// Default value when Suggestion does not have a value for score
pub const DEFAULT_SUGGESTION_SCORE: f64 = 0.2;
/// The database connection type.
#[derive(Clone, Copy)]
pub(crate) enum ConnectionType {
ReadOnly,
ReadWrite,
}
#[derive(Default, Clone)]
pub struct Sqlite3Extension {
pub library: String,
pub entry_point: Option<String>,
}
/// A thread-safe wrapper around an SQLite connection to the Suggest database,
/// and its interrupt handle.
pub(crate) struct SuggestDb {
pub conn: Mutex<Connection>,
/// An object that's used to interrupt an ongoing database operation.
///
/// When this handle is interrupted, the thread that's currently accessing
/// the database will be told to stop and release the `conn` lock as soon
/// as possible.
pub interrupt_handle: Arc<SqlInterruptHandle>,
}
impl SuggestDb {
/// Opens a read-only or read-write connection to a Suggest database at the
/// given path.
pub fn open(
path: impl AsRef<Path>,
extensions_to_load: &[Sqlite3Extension],
type_: ConnectionType,
) -> Result<Self> {
let conn = open_database::open_database_with_flags(
path,
match type_ {
ConnectionType::ReadWrite => open_database::read_write_flags(),
ConnectionType::ReadOnly => open_database::read_only_flags(),
},
&SuggestConnectionInitializer::new(extensions_to_load),
)?;
Ok(Self::with_connection(conn))
}
fn with_connection(conn: Connection) -> Self {
let interrupt_handle = Arc::new(SqlInterruptHandle::new(&conn));
Self {
conn: Mutex::new(conn),
interrupt_handle,
}
}
/// Accesses the Suggest database for reading.
pub fn read<T>(&self, op: impl FnOnce(&SuggestDao) -> Result<T>) -> Result<T> {
let conn = self.conn.lock();
let scope = self.interrupt_handle.begin_interrupt_scope()?;
let dao = SuggestDao::new(&conn, &scope);
op(&dao)
}
/// Accesses the Suggest database in a transaction for reading and writing.
pub fn write<T>(&self, op: impl FnOnce(&mut SuggestDao) -> Result<T>) -> Result<T> {
let mut conn = self.conn.lock();
let scope = self.interrupt_handle.begin_interrupt_scope()?;
let tx = conn.transaction()?;
let mut dao = SuggestDao::new(&tx, &scope);
let result = op(&mut dao)?;
tx.commit()?;
Ok(result)
}
/// Create a new write scope.
///
/// This enables performing multiple `write()` calls with the same shared interrupt scope.
/// This is important for things like ingestion, where you want the operation to be interrupted
/// if [Self::interrupt_handle::interrupt] is called after the operation starts. Calling
/// [Self::write] multiple times during the operation risks missing a call that happens after
/// between those calls.
pub fn write_scope(&self) -> Result<WriteScope> {
Ok(WriteScope {
conn: self.conn.lock(),
scope: self.interrupt_handle.begin_interrupt_scope()?,
})
}
}
pub(crate) struct WriteScope<'a> {
pub conn: MutexGuard<'a, Connection>,
pub scope: SqlInterruptScope,
}
impl WriteScope<'_> {
/// Accesses the Suggest database in a transaction for reading and writing.
pub fn write<T>(&mut self, op: impl FnOnce(&mut SuggestDao) -> Result<T>) -> Result<T> {
let tx = self.conn.transaction()?;
let mut dao = SuggestDao::new(&tx, &self.scope);
let result = op(&mut dao)?;
tx.commit()?;
Ok(result)
}
/// Accesses the Suggest database in a transaction for reading only
pub fn read<T>(&mut self, op: impl FnOnce(&SuggestDao) -> Result<T>) -> Result<T> {
let tx = self.conn.transaction()?;
let dao = SuggestDao::new(&tx, &self.scope);
let result = op(&dao)?;
tx.commit()?;
Ok(result)
}
pub fn err_if_interrupted(&self) -> Result<()> {
Ok(self.scope.err_if_interrupted()?)
}
}
/// A data access object (DAO) that wraps a connection to the Suggest database
/// with methods for reading and writing suggestions, icons, and metadata.
///
/// Methods that only read from the database take an immutable reference to
/// `self` (`&self`), and methods that write to the database take a mutable
/// reference (`&mut self`).
pub(crate) struct SuggestDao<'a> {
pub conn: &'a Connection,
pub scope: &'a SqlInterruptScope,
pub weather_cache: OnceCell<WeatherCache>,
pub geoname_cache: OnceCell<GeonameCache>,
}
impl<'a> SuggestDao<'a> {
fn new(conn: &'a Connection, scope: &'a SqlInterruptScope) -> Self {
Self {
conn,
scope,
weather_cache: std::cell::OnceCell::new(),
geoname_cache: std::cell::OnceCell::new(),
}
}
// =============== High level API ===============
//
// These methods combine several low-level calls into one logical operation.
pub fn delete_record_data(&mut self, record_id: &SuggestRecordId) -> Result<()> {
// Drop either the icon or suggestions, records only contain one or the other
match record_id.as_icon_id() {
Some(icon_id) => self.drop_icon(icon_id)?,
None => self.drop_suggestions(record_id)?,
};
Ok(())
}
// =============== Low level API ===============
//
// These methods implement CRUD operations
pub fn get_ingested_records(&self) -> Result<Vec<IngestedRecord>> {
let mut stmt = self
.conn
.prepare_cached("SELECT id, collection, type, last_modified FROM ingested_records")?;
let rows = stmt.query_and_then((), IngestedRecord::from_row)?;
rows.collect()
}
pub fn update_ingested_records(
&mut self,
collection: &str,
new_records: &[&Record],
updated_records: &[&Record],
deleted_records: &[&IngestedRecord],
) -> Result<()> {
let mut delete_stmt = self
.conn
.prepare_cached("DELETE FROM ingested_records WHERE collection = ? AND id = ?")?;
for deleted in deleted_records {
delete_stmt.execute((collection, deleted.id.as_str()))?;
}
let mut insert_stmt = self.conn.prepare_cached(
"INSERT OR REPLACE INTO ingested_records(id, collection, type, last_modified) VALUES(?, ?, ?, ?)",
)?;
for record in new_records.iter().chain(updated_records) {
insert_stmt.execute((
record.id.as_str(),
collection,
record.record_type().as_str(),
record.last_modified,
))?;
}
Ok(())
}
/// Update the DB so that we re-ingest all records on the next ingestion.
///
/// We hack this by setting the last_modified time to 1 so that the next time around we always
/// re-ingest the record.
pub fn force_reingest(&mut self) -> Result<()> {
self.conn
.prepare_cached("UPDATE ingested_records SET last_modified=1")?
.execute(())?;
Ok(())
}
pub fn suggestions_table_empty(&self) -> Result<bool> {
Ok(self
.conn
.query_one::<bool>("SELECT NOT EXISTS (SELECT 1 FROM suggestions)")?)
}
/// Fetches Suggestions of type Amp provider that match the given query
pub fn fetch_amp_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
let strategy = query
.provider_constraints
.as_ref()
.and_then(|c| c.amp_alternative_matching.as_ref());
match strategy {
None => self.fetch_amp_suggestions_using_keywords(query, true),
Some(AmpMatchingStrategy::NoKeywordExpansion) => {
self.fetch_amp_suggestions_using_keywords(query, false)
}
Some(AmpMatchingStrategy::FtsAgainstFullKeywords) => {
self.fetch_amp_suggestions_using_fts(query, "full_keywords")
}
Some(AmpMatchingStrategy::FtsAgainstTitle) => {
self.fetch_amp_suggestions_using_fts(query, "title")
}
}
}
pub fn fetch_amp_suggestions_using_keywords(
&self,
query: &SuggestionQuery,
allow_keyword_expansion: bool,
) -> Result<Vec<Suggestion>> {
let keyword_lowercased = &query.keyword.to_lowercase();
let where_extra = if allow_keyword_expansion {
""
} else {
"AND INSTR(CONCAT(fk.full_keyword, ' '), k.keyword) != 0"
};
let suggestions = self.conn.query_rows_and_then_cached(
&format!(
r#"
SELECT
s.id,
k.rank,
s.title,
s.url,
s.provider,
s.score,
fk.full_keyword
FROM
suggestions s
JOIN
keywords k
ON k.suggestion_id = s.id
LEFT JOIN
full_keywords fk
ON k.full_keyword_id = fk.id
WHERE
s.provider = :provider
AND k.keyword = :keyword
{where_extra}
AND NOT EXISTS (SELECT 1 FROM dismissed_suggestions WHERE url=s.url)
"#
),
named_params! {
":keyword": keyword_lowercased,
":provider": SuggestionProvider::Amp,
},
|row| -> Result<Suggestion> {
let suggestion_id: i64 = row.get("id")?;
let title = row.get("title")?;
let raw_url: String = row.get("url")?;
let score: f64 = row.get("score")?;
let full_keyword_from_db: Option<String> = row.get("full_keyword")?;
let keywords: Vec<String> = self.conn.query_rows_and_then_cached(
r#"
SELECT
keyword
FROM
keywords
WHERE
suggestion_id = :suggestion_id
AND rank >= :rank
ORDER BY
rank ASC
"#,
named_params! {
":suggestion_id": suggestion_id,
":rank": row.get::<_, i64>("rank")?,
},
|row| row.get(0),
)?;
self.conn.query_row_and_then(
r#"
SELECT
amp.advertiser,
amp.block_id,
amp.iab_category,
amp.impression_url,
amp.click_url,
i.data AS icon,
i.mimetype AS icon_mimetype
FROM
amp_custom_details amp
LEFT JOIN
icons i ON amp.icon_id = i.id
WHERE
amp.suggestion_id = :suggestion_id
"#,
named_params! {
":suggestion_id": suggestion_id
},
|row| {
let cooked_url = cook_raw_suggestion_url(&raw_url);
let raw_click_url = row.get::<_, String>("click_url")?;
let cooked_click_url = cook_raw_suggestion_url(&raw_click_url);
Ok(Suggestion::Amp {
block_id: row.get("block_id")?,
advertiser: row.get("advertiser")?,
iab_category: row.get("iab_category")?,
title,
url: cooked_url,
raw_url,
full_keyword: full_keyword_from_db
.unwrap_or_else(|| full_keyword(keyword_lowercased, &keywords)),
icon: row.get("icon")?,
icon_mimetype: row.get("icon_mimetype")?,
impression_url: row.get("impression_url")?,
click_url: cooked_click_url,
raw_click_url,
score,
fts_match_info: None,
})
},
)
},
)?;
Ok(suggestions)
}
pub fn fetch_amp_suggestions_using_fts(
&self,
query: &SuggestionQuery,
fts_column: &str,
) -> Result<Vec<Suggestion>> {
let fts_query = query.fts_query();
let match_arg = &fts_query.match_arg;
let suggestions = self.conn.query_rows_and_then_cached(
&format!(
r#"
SELECT
s.id,
s.title,
s.url,
s.provider,
s.score
FROM
suggestions s
JOIN
amp_fts fts
ON fts.rowid = s.id
WHERE
s.provider = :provider
AND amp_fts match '{fts_column}: {match_arg}'
AND NOT EXISTS (SELECT 1 FROM dismissed_suggestions WHERE url=s.url)
ORDER BY rank
LIMIT 1
"#
),
named_params! {
":provider": SuggestionProvider::Amp,
},
|row| -> Result<Suggestion> {
let suggestion_id: i64 = row.get("id")?;
let title: String = row.get("title")?;
let raw_url: String = row.get("url")?;
let score: f64 = row.get("score")?;
self.conn.query_row_and_then(
r#"
SELECT
amp.advertiser,
amp.block_id,
amp.iab_category,
amp.impression_url,
amp.click_url,
i.data AS icon,
i.mimetype AS icon_mimetype
FROM
amp_custom_details amp
LEFT JOIN
icons i ON amp.icon_id = i.id
WHERE
amp.suggestion_id = :suggestion_id
"#,
named_params! {
":suggestion_id": suggestion_id
},
|row| {
let cooked_url = cook_raw_suggestion_url(&raw_url);
let raw_click_url = row.get::<_, String>("click_url")?;
let cooked_click_url = cook_raw_suggestion_url(&raw_click_url);
let match_info = self.fetch_amp_fts_match_info(
&fts_query,
suggestion_id,
fts_column,
&title,
)?;
Ok(Suggestion::Amp {
block_id: row.get("block_id")?,
advertiser: row.get("advertiser")?,
iab_category: row.get("iab_category")?,
title,
url: cooked_url,
raw_url,
full_keyword: query.keyword.clone(),
icon: row.get("icon")?,
icon_mimetype: row.get("icon_mimetype")?,
impression_url: row.get("impression_url")?,
click_url: cooked_click_url,
raw_click_url,
score,
fts_match_info: Some(match_info),
})
},
)
},
)?;
Ok(suggestions)
}
fn fetch_amp_fts_match_info(
&self,
fts_query: &FtsQuery<'_>,
suggestion_id: i64,
fts_column: &str,
title: &str,
) -> Result<FtsMatchInfo> {
let fts_content = match fts_column {
"title" => title.to_lowercase(),
"full_keywords" => {
let full_keyword_list: Vec<String> = self.conn.query_rows_and_then(
"
SELECT fk.full_keyword
FROM full_keywords fk
JOIN keywords k on fk.id == k.full_keyword_id
WHERE k.suggestion_id = ?
",
(suggestion_id,),
|row| row.get(0),
)?;
full_keywords_to_fts_content(full_keyword_list.iter().map(String::as_str))
}
// fts_column comes from the code above and we know there's only 2 possibilities
_ => unreachable!(),
};
let prefix = if fts_query.is_prefix_query {
// If the query was a prefix match query then test if the query without the prefix
// match would have also matched. If not, then this counts as a prefix match.
let sql = "SELECT 1 FROM amp_fts WHERE rowid = ? AND amp_fts MATCH ?";
let params = (&suggestion_id, &fts_query.match_arg_without_prefix_match);
!self.conn.exists(sql, params)?
} else {
// If not, then it definitely wasn't a prefix match
false
};
Ok(FtsMatchInfo {
prefix,
stemming: fts_query.match_required_stemming(&fts_content),
})
}
/// Fetches Suggestions of type Wikipedia provider that match the given query
pub fn fetch_wikipedia_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
let keyword_lowercased = &query.keyword.to_lowercase();
let suggestions = self.conn.query_rows_and_then_cached(
r#"
SELECT
s.id,
k.rank,
s.title,
s.url
FROM
suggestions s
JOIN
keywords k
ON k.suggestion_id = s.id
WHERE
s.provider = :provider
AND k.keyword = :keyword
AND NOT EXISTS (SELECT 1 FROM dismissed_suggestions WHERE url=s.url)
"#,
named_params! {
":keyword": keyword_lowercased,
":provider": SuggestionProvider::Wikipedia
},
|row| -> Result<Suggestion> {
let suggestion_id: i64 = row.get("id")?;
let title = row.get("title")?;
let raw_url = row.get::<_, String>("url")?;
let keywords: Vec<String> = self.conn.query_rows_and_then_cached(
"SELECT keyword FROM keywords
WHERE suggestion_id = :suggestion_id AND rank >= :rank
ORDER BY rank ASC",
named_params! {
":suggestion_id": suggestion_id,
":rank": row.get::<_, i64>("rank")?,
},
|row| row.get(0),
)?;
let (icon, icon_mimetype) = self
.conn
.try_query_row(
"SELECT i.data, i.mimetype
FROM icons i
JOIN wikipedia_custom_details s ON s.icon_id = i.id
WHERE s.suggestion_id = :suggestion_id
LIMIT 1",
named_params! {
":suggestion_id": suggestion_id
},
|row| -> Result<_> {
Ok((
row.get::<_, Option<Vec<u8>>>(0)?,
row.get::<_, Option<String>>(1)?,
))
},
true,
)?
.unwrap_or((None, None));
Ok(Suggestion::Wikipedia {
title,
url: raw_url,
full_keyword: full_keyword(keyword_lowercased, &keywords),
icon,
icon_mimetype,
})
},
)?;
Ok(suggestions)
}
/// Query for suggestions using the keyword prefix and provider
fn map_prefix_keywords<T>(
&self,
query: &SuggestionQuery,
provider: &SuggestionProvider,
mut mapper: impl FnMut(&rusqlite::Row, &str) -> Result<T>,
) -> Result<Vec<T>> {
let keyword_lowercased = &query.keyword.to_lowercase();
let (keyword_prefix, keyword_suffix) = split_keyword(keyword_lowercased);
let suggestions_limit = query.limit.unwrap_or(-1);
self.conn.query_rows_and_then_cached(
r#"
SELECT
s.id,
MAX(k.rank) AS rank,
s.title,
s.url,
s.provider,
s.score,
k.keyword_suffix
FROM
suggestions s
JOIN
prefix_keywords k
ON k.suggestion_id = s.id
WHERE
k.keyword_prefix = :keyword_prefix
AND (k.keyword_suffix BETWEEN :keyword_suffix AND :keyword_suffix || x'FFFF')
AND s.provider = :provider
AND NOT EXISTS (SELECT 1 FROM dismissed_suggestions WHERE url=s.url)
GROUP BY
s.id
ORDER BY
s.score DESC,
rank DESC
LIMIT
:suggestions_limit
"#,
&[
(":keyword_prefix", &keyword_prefix as &dyn ToSql),
(":keyword_suffix", &keyword_suffix as &dyn ToSql),
(":provider", provider as &dyn ToSql),
(":suggestions_limit", &suggestions_limit as &dyn ToSql),
],
|row| mapper(row, keyword_suffix),
)
}
/// Fetches Suggestions of type Amo provider that match the given query
pub fn fetch_amo_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
let suggestions = self
.map_prefix_keywords(
query,
&SuggestionProvider::Amo,
|row, keyword_suffix| -> Result<Option<Suggestion>> {
let suggestion_id: i64 = row.get("id")?;
let title = row.get("title")?;
let raw_url = row.get::<_, String>("url")?;
let score = row.get::<_, f64>("score")?;
let full_suffix = row.get::<_, String>("keyword_suffix")?;
full_suffix
.starts_with(keyword_suffix)
.then(|| {
self.conn.query_row_and_then(
r#"
SELECT
amo.description,
amo.guid,
amo.rating,
amo.icon_url,
amo.number_of_ratings
FROM
amo_custom_details amo
WHERE
amo.suggestion_id = :suggestion_id
"#,
named_params! {
":suggestion_id": suggestion_id
},
|row| {
Ok(Suggestion::Amo {
title,
url: raw_url,
icon_url: row.get("icon_url")?,
description: row.get("description")?,
rating: row.get("rating")?,
number_of_ratings: row.get("number_of_ratings")?,
guid: row.get("guid")?,
score,
})
},
)
})
.transpose()
},
)?
.into_iter()
.flatten()
.collect();
Ok(suggestions)
}
/// Fetches Suggestions of type pocket provider that match the given query
pub fn fetch_pocket_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
let keyword_lowercased = &query.keyword.to_lowercase();
let (keyword_prefix, keyword_suffix) = split_keyword(keyword_lowercased);
let suggestions = self
.conn
.query_rows_and_then_cached(
r#"
SELECT
s.id,
MAX(k.rank) AS rank,
s.title,
s.url,
s.provider,
s.score,
k.confidence,
k.keyword_suffix
FROM
suggestions s
JOIN
prefix_keywords k
ON k.suggestion_id = s.id
WHERE
k.keyword_prefix = :keyword_prefix
AND (k.keyword_suffix BETWEEN :keyword_suffix AND :keyword_suffix || x'FFFF')
AND s.provider = :provider
AND NOT EXISTS (SELECT 1 FROM dismissed_suggestions WHERE url=s.url)
GROUP BY
s.id,
k.confidence
ORDER BY
s.score DESC,
rank DESC
"#,
named_params! {
":keyword_prefix": keyword_prefix,
":keyword_suffix": keyword_suffix,
":provider": SuggestionProvider::Pocket,
},
|row| -> Result<Option<Suggestion>> {
let title = row.get("title")?;
let raw_url = row.get::<_, String>("url")?;
let score = row.get::<_, f64>("score")?;
let confidence = row.get("confidence")?;
let full_suffix = row.get::<_, String>("keyword_suffix")?;
let suffixes_match = match confidence {
KeywordConfidence::Low => full_suffix.starts_with(keyword_suffix),
KeywordConfidence::High => full_suffix == keyword_suffix,
};
if suffixes_match {
Ok(Some(Suggestion::Pocket {
title,
url: raw_url,
score,
is_top_pick: matches!(confidence, KeywordConfidence::High),
}))
} else {
Ok(None)
}
},
)?
.into_iter()
.flatten()
.take(
query
.limit
.and_then(|limit| usize::try_from(limit).ok())
.unwrap_or(usize::MAX),
)
.collect();
Ok(suggestions)
}
/// Fetches suggestions for MDN
pub fn fetch_mdn_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
let suggestions = self
.map_prefix_keywords(
query,
&SuggestionProvider::Mdn,
|row, keyword_suffix| -> Result<Option<Suggestion>> {
let suggestion_id: i64 = row.get("id")?;
let title = row.get("title")?;
let raw_url = row.get::<_, String>("url")?;
let score = row.get::<_, f64>("score")?;
let full_suffix = row.get::<_, String>("keyword_suffix")?;
full_suffix
.starts_with(keyword_suffix)
.then(|| {
self.conn.query_row_and_then(
r#"
SELECT
description
FROM
mdn_custom_details
WHERE
suggestion_id = :suggestion_id
"#,
named_params! {
":suggestion_id": suggestion_id
},
|row| {
Ok(Suggestion::Mdn {
title,
url: raw_url,
description: row.get("description")?,
score,
})
},
)
})
.transpose()
},
)?
.into_iter()
.flatten()
.collect();
Ok(suggestions)
}
/// Fetches Fakespot suggestions
pub fn fetch_fakespot_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
let fts_query = query.fts_query();
let sql = r#"
SELECT
s.id,
s.title,
s.url,
s.score,
f.fakespot_grade,
f.product_id,
f.rating,
f.total_reviews,
i.data,
i.mimetype,
f.keywords,
f.product_type
FROM
suggestions s
JOIN
fakespot_fts fts
ON fts.rowid = s.id
JOIN
fakespot_custom_details f
ON f.suggestion_id = s.id
LEFT JOIN
icons i
ON i.id = f.icon_id
WHERE
fakespot_fts MATCH ?
ORDER BY
s.score DESC
"#
.to_string();
// Store the list of results plus the suggestion id for calculating the FTS match info
let mut results =
self.conn
.query_rows_and_then_cached(&sql, (&fts_query.match_arg,), |row| {
let id: usize = row.get(0)?;
let score = fakespot::FakespotScore::new(
&query.keyword,
row.get(10)?,
row.get(11)?,
row.get(3)?,
)
.as_suggest_score();
Result::Ok((
Suggestion::Fakespot {
title: row.get(1)?,
url: row.get(2)?,
score,
fakespot_grade: row.get(4)?,
product_id: row.get(5)?,
rating: row.get(6)?,
total_reviews: row.get(7)?,
icon: row.get(8)?,
icon_mimetype: row.get(9)?,
match_info: None,
},
id,
))
})?;
// Sort the results, then add the FTS match info to the first one
// For performance reasons, this is only calculated for the result with the highest score.
// We assume that only one that will be shown to the user and therefore the only one we'll
// collect metrics for.
results.sort();
if let Some((suggestion, id)) = results.first_mut() {
match suggestion {
Suggestion::Fakespot {
match_info, title, ..
} => {
*match_info = Some(self.fetch_fakespot_fts_match_info(&fts_query, *id, title)?);
}
_ => unreachable!(),
}
}
Ok(results
.into_iter()
.map(|(suggestion, _)| suggestion)
.collect())
}
fn fetch_fakespot_fts_match_info(
&self,
fts_query: &FtsQuery<'_>,
suggestion_id: usize,
title: &str,
) -> Result<FtsMatchInfo> {
let prefix = if fts_query.is_prefix_query {
// If the query was a prefix match query then test if the query without the prefix
// match would have also matched. If not, then this counts as a prefix match.
let sql = "SELECT 1 FROM fakespot_fts WHERE rowid = ? AND fakespot_fts MATCH ?";
let params = (&suggestion_id, &fts_query.match_arg_without_prefix_match);
!self.conn.exists(sql, params)?
} else {
// If not, then it definitely wasn't a prefix match
false
};
Ok(FtsMatchInfo {
prefix,
stemming: fts_query.match_required_stemming(title),
})
}
/// Fetches exposure suggestions
pub fn fetch_exposure_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
// A single exposure suggestion can be spread across multiple remote
// settings records, for example if it has very many keywords. On ingest
// we will insert one row in `exposure_custom_details` and one row in
// `suggestions` per record, but that's only an implementation detail.
// Logically, and for consumers, there's only ever at most one exposure
// suggestion with a given exposure suggestion type.
//
// Why do insertions this way? It's how other suggestions work, and it
// lets us perform relational operations on suggestions, records, and
// keywords. For example, when a record is deleted we can look up its ID
// in `suggestions`, join the keywords table on the suggestion ID, and
// delete the keywords that were added by that record.
let Some(suggestion_types) = query
.provider_constraints
.as_ref()
.and_then(|c| c.exposure_suggestion_types.as_ref())
else {
return Ok(vec![]);
};
let keyword = query.keyword.to_lowercase();
let params = rusqlite::params_from_iter(
std::iter::once(&SuggestionProvider::Exposure as &dyn ToSql)
.chain(std::iter::once(&keyword as &dyn ToSql))
.chain(suggestion_types.iter().map(|t| t as &dyn ToSql)),
);
self.conn.query_rows_and_then_cached(
&format!(
r#"
SELECT DISTINCT
d.type
FROM
suggestions s
JOIN
exposure_custom_details d
ON d.suggestion_id = s.id
JOIN
keywords k
ON k.suggestion_id = s.id
WHERE
s.provider = ?
AND k.keyword = ?
AND d.type IN ({})
ORDER BY
d.type
"#,
repeat_sql_vars(suggestion_types.len())
),
params,
|row| -> Result<Suggestion> {
Ok(Suggestion::Exposure {
suggestion_type: row.get("type")?,
score: 1.0,
})
},
)
}
pub fn is_exposure_suggestion_ingested(&self, record_id: &SuggestRecordId) -> Result<bool> {
Ok(self.conn.exists(
r#"
SELECT
id
FROM
suggestions
WHERE
record_id = :record_id
"#,
named_params! {
":record_id": record_id.as_str(),
},
)?)
}
pub fn is_amp_fts_data_ingested(&self, record_id: &SuggestRecordId) -> Result<bool> {
Ok(self.conn.exists(
r#"
SELECT 1
FROM suggestions s
JOIN amp_fts fts
ON fts.rowid = s.id
WHERE s.record_id = :record_id
"#,
named_params! {
":record_id": record_id.as_str(),
},
)?)
}
/// Inserts all suggestions from a downloaded AMO attachment into
/// the database.
pub fn insert_amo_suggestions(
&mut self,
record_id: &SuggestRecordId,
suggestions: &[DownloadedAmoSuggestion],
) -> Result<()> {
let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
let mut amo_insert = AmoInsertStatement::new(self.conn)?;
let mut prefix_keyword_insert = PrefixKeywordInsertStatement::new(self.conn)?;
for suggestion in suggestions {
self.scope.err_if_interrupted()?;
let suggestion_id = suggestion_insert.execute(
record_id,
&suggestion.title,
&suggestion.url,
suggestion.score,
SuggestionProvider::Amo,
)?;
amo_insert.execute(suggestion_id, suggestion)?;
for (index, keyword) in suggestion.keywords.iter().enumerate() {
let (keyword_prefix, keyword_suffix) = split_keyword(keyword);
prefix_keyword_insert.execute(
suggestion_id,
None,
keyword_prefix,
keyword_suffix,
index,
)?;
}
}
Ok(())
}
/// Inserts suggestions from an AMP attachment into the database.
pub fn insert_amp_suggestions(
&mut self,
record_id: &SuggestRecordId,
suggestions: &[DownloadedAmpSuggestion],
enable_fts: bool,
) -> Result<()> {
// Prepare statements outside of the loop. This results in a large performance
// improvement on a fresh ingest, since there are so many rows.
let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
let mut amp_insert = AmpInsertStatement::new(self.conn)?;
let mut keyword_insert = KeywordInsertStatement::new(self.conn)?;
let mut fts_insert = AmpFtsInsertStatement::new(self.conn)?;
for suggestion in suggestions {
self.scope.err_if_interrupted()?;
let suggestion_id = suggestion_insert.execute(
record_id,
&suggestion.title,
&suggestion.url,
suggestion.score.unwrap_or(DEFAULT_SUGGESTION_SCORE),
SuggestionProvider::Amp,
)?;
amp_insert.execute(suggestion_id, suggestion)?;
if enable_fts {
fts_insert.execute(
suggestion_id,
&suggestion.full_keywords_fts_column(),
&suggestion.title,
)?;
}
let mut full_keyword_inserter = FullKeywordInserter::new(self.conn, suggestion_id);
for keyword in suggestion.keywords() {
let full_keyword_id = if let Some(full_keyword) = keyword.full_keyword {
Some(full_keyword_inserter.maybe_insert(full_keyword)?)
} else {
None
};
keyword_insert.execute(
suggestion_id,
keyword.keyword,
full_keyword_id,
keyword.rank,
)?;
}
}
Ok(())
}
/// Inserts suggestions from a Wikipedia attachment into the database.
pub fn insert_wikipedia_suggestions(
&mut self,
record_id: &SuggestRecordId,
suggestions: &[DownloadedWikipediaSuggestion],
) -> Result<()> {
// Prepare statements outside of the loop. This results in a large performance
// improvement on a fresh ingest, since there are so many rows.
let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
let mut wiki_insert = WikipediaInsertStatement::new(self.conn)?;
let mut keyword_insert = KeywordInsertStatement::new(self.conn)?;
for suggestion in suggestions {
self.scope.err_if_interrupted()?;
let suggestion_id = suggestion_insert.execute(
record_id,
&suggestion.title,
&suggestion.url,
suggestion.score.unwrap_or(DEFAULT_SUGGESTION_SCORE),
SuggestionProvider::Wikipedia,
)?;
wiki_insert.execute(suggestion_id, suggestion)?;
for keyword in suggestion.keywords() {
// Don't update `full_keywords`, see bug 1876217.
keyword_insert.execute(suggestion_id, keyword.keyword, None, keyword.rank)?;
}
}
Ok(())
}
/// Inserts all suggestions from a downloaded Pocket attachment into
/// the database.
pub fn insert_pocket_suggestions(
&mut self,
record_id: &SuggestRecordId,
suggestions: &[DownloadedPocketSuggestion],
) -> Result<()> {
let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
let mut prefix_keyword_insert = PrefixKeywordInsertStatement::new(self.conn)?;
for suggestion in suggestions {
self.scope.err_if_interrupted()?;
let suggestion_id = suggestion_insert.execute(
record_id,
&suggestion.title,
&suggestion.url,
suggestion.score,
SuggestionProvider::Pocket,
)?;
for ((rank, keyword), confidence) in suggestion
.high_confidence_keywords
.iter()
.enumerate()
.zip(std::iter::repeat(KeywordConfidence::High))
.chain(
suggestion
.low_confidence_keywords
.iter()
.enumerate()
.zip(std::iter::repeat(KeywordConfidence::Low)),
)
{
let (keyword_prefix, keyword_suffix) = split_keyword(keyword);
prefix_keyword_insert.execute(
suggestion_id,
Some(confidence as u8),
keyword_prefix,
keyword_suffix,
rank,
)?;
}
}
Ok(())
}
/// Inserts all suggestions from a downloaded MDN attachment into
/// the database.
pub fn insert_mdn_suggestions(
&mut self,
record_id: &SuggestRecordId,
suggestions: &[DownloadedMdnSuggestion],
) -> Result<()> {
let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
let mut mdn_insert = MdnInsertStatement::new(self.conn)?;
let mut prefix_keyword_insert = PrefixKeywordInsertStatement::new(self.conn)?;
for suggestion in suggestions {
self.scope.err_if_interrupted()?;
let suggestion_id = suggestion_insert.execute(
record_id,
&suggestion.title,
&suggestion.url,
suggestion.score,
SuggestionProvider::Mdn,
)?;
mdn_insert.execute(suggestion_id, suggestion)?;
for (index, keyword) in suggestion.keywords.iter().enumerate() {
let (keyword_prefix, keyword_suffix) = split_keyword(keyword);
prefix_keyword_insert.execute(
suggestion_id,
None,
keyword_prefix,
keyword_suffix,
index,
)?;
}
}
Ok(())
}
/// Inserts all suggestions from a downloaded Fakespot attachment into the database.
pub fn insert_fakespot_suggestions(
&mut self,
record_id: &SuggestRecordId,
suggestions: &[DownloadedFakespotSuggestion],
) -> Result<()> {
let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
let mut fakespot_insert = FakespotInsertStatement::new(self.conn)?;
for suggestion in suggestions {
let suggestion_id = suggestion_insert.execute(
record_id,
&suggestion.title,
&suggestion.url,
suggestion.score,
SuggestionProvider::Fakespot,
)?;
fakespot_insert.execute(suggestion_id, suggestion)?;
}
Ok(())
}
/// Inserts exposure suggestion records data into the database.
pub fn insert_exposure_suggestions(
&mut self,
record_id: &SuggestRecordId,
suggestion_type: &str,
suggestions: &[DownloadedExposureSuggestion],
) -> Result<()> {
// `suggestion.keywords()` can yield duplicates for exposure
// suggestions, so ignore failures on insert in the uniqueness
// constraint on `(suggestion_id, keyword)`.
let mut keyword_insert = KeywordInsertStatement::new_with_or_ignore(self.conn)?;
let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
let mut exposure_insert = ExposureInsertStatement::new(self.conn)?;
for suggestion in suggestions {
self.scope.err_if_interrupted()?;
let suggestion_id = suggestion_insert.execute(
record_id,
"", // title, not used by exposure suggestions
"", // url, not used by exposure suggestions
DEFAULT_SUGGESTION_SCORE,
SuggestionProvider::Exposure,
)?;
exposure_insert.execute(suggestion_id, suggestion_type)?;
// Exposure suggestions don't use `rank` but `(suggestion_id, rank)`
// must be unique since there's an index on that tuple.
for (rank, keyword) in suggestion.keywords().enumerate() {
keyword_insert.execute(suggestion_id, &keyword, None, rank)?;
}
}
Ok(())
}
/// Inserts or replaces an icon for a suggestion into the database.
pub fn put_icon(&mut self, icon_id: &str, data: &[u8], mimetype: &str) -> Result<()> {
self.conn.execute(
"INSERT OR REPLACE INTO icons(
id,
data,
mimetype
)
VALUES(
:id,
:data,
:mimetype
)",
named_params! {
":id": icon_id,
":data": data,
":mimetype": mimetype,
},
)?;
Ok(())
}
pub fn insert_dismissal(&self, url: &str) -> Result<()> {
self.conn.execute(
"INSERT OR IGNORE INTO dismissed_suggestions(url)
VALUES(:url)",
named_params! {
":url": url,
},
)?;
Ok(())
}
pub fn clear_dismissals(&self) -> Result<()> {
self.conn.execute("DELETE FROM dismissed_suggestions", ())?;
Ok(())
}
/// Deletes all suggestions associated with a Remote Settings record from
/// the database.
pub fn drop_suggestions(&mut self, record_id: &SuggestRecordId) -> Result<()> {
// If you update this, you probably need to update
// `schema::clear_database()` too!
//
// Call `err_if_interrupted` before each statement since these have historically taken a
// long time and caused shutdown hangs.
self.scope.err_if_interrupted()?;
self.conn.execute_cached(
"DELETE FROM keywords WHERE suggestion_id IN (SELECT id from suggestions WHERE record_id = :record_id)",
named_params! { ":record_id": record_id.as_str() },
)?;
self.scope.err_if_interrupted()?;
self.conn.execute_cached(
"DELETE FROM full_keywords WHERE suggestion_id IN (SELECT id from suggestions WHERE record_id = :record_id)",
named_params! { ":record_id": record_id.as_str() },
)?;
self.scope.err_if_interrupted()?;
self.conn.execute_cached(
"DELETE FROM prefix_keywords WHERE suggestion_id IN (SELECT id from suggestions WHERE record_id = :record_id)",
named_params! { ":record_id": record_id.as_str() },
)?;
self.scope.err_if_interrupted()?;
self.conn.execute_cached(
"DELETE FROM keywords_metrics WHERE record_id = :record_id",
named_params! { ":record_id": record_id.as_str() },
)?;
self.scope.err_if_interrupted()?;
self.conn.execute_cached(
"
DELETE FROM fakespot_fts
WHERE rowid IN (SELECT id from suggestions WHERE record_id = :record_id)
",
named_params! { ":record_id": record_id.as_str() },
)?;
self.scope.err_if_interrupted()?;
self.conn.execute_cached(
"DELETE FROM suggestions WHERE record_id = :record_id",
named_params! { ":record_id": record_id.as_str() },
)?;
self.scope.err_if_interrupted()?;
self.conn.execute_cached(
"DELETE FROM yelp_subjects WHERE record_id = :record_id",
named_params! { ":record_id": record_id.as_str() },
)?;
self.scope.err_if_interrupted()?;
self.conn.execute_cached(
"DELETE FROM yelp_modifiers WHERE record_id = :record_id",
named_params! { ":record_id": record_id.as_str() },
)?;
self.scope.err_if_interrupted()?;
self.conn.execute_cached(
"DELETE FROM yelp_location_signs WHERE record_id = :record_id",
named_params! { ":record_id": record_id.as_str() },
)?;
self.scope.err_if_interrupted()?;
self.conn.execute_cached(
"DELETE FROM yelp_custom_details WHERE record_id = :record_id",
named_params! { ":record_id": record_id.as_str() },
)?;
self.scope.err_if_interrupted()?;
self.conn.execute_cached(
"DELETE FROM geonames WHERE record_id = :record_id",
named_params! { ":record_id": record_id.as_str() },
)?;
self.scope.err_if_interrupted()?;
self.conn.execute_cached(
"DELETE FROM geonames_metrics WHERE record_id = :record_id",
named_params! { ":record_id": record_id.as_str() },
)?;
// Invalidate these caches since we might have deleted a record their
// contents are based on.
self.weather_cache.take();
self.geoname_cache.take();
Ok(())
}
/// Deletes an icon for a suggestion from the database.
pub fn drop_icon(&mut self, icon_id: &str) -> Result<()> {
self.conn.execute_cached(
"DELETE FROM icons WHERE id = :id",
named_params! { ":id": icon_id },
)?;
Ok(())
}
/// Clears the database, removing all suggestions, icons, and metadata.
pub fn clear(&mut self) -> Result<()> {
Ok(clear_database(self.conn)?)
}
/// Returns the value associated with a metadata key.
pub fn get_meta<T: FromSql>(&self, key: &str) -> Result<Option<T>> {
Ok(self.conn.try_query_one(
"SELECT value FROM meta WHERE key = :key",
named_params! { ":key": key },
true,
)?)
}
/// Sets the value for a metadata key.
pub fn put_meta(&mut self, key: &str, value: impl ToSql) -> Result<()> {
self.conn.execute_cached(
"INSERT OR REPLACE INTO meta(key, value) VALUES(:key, :value)",
named_params! { ":key": key, ":value": value },
)?;
Ok(())
}
/// Stores global Suggest configuration data.
pub fn put_global_config(&mut self, config: &SuggestGlobalConfig) -> Result<()> {
self.put_meta(GLOBAL_CONFIG_META_KEY, serde_json::to_string(config)?)
}
/// Gets the stored global Suggest configuration data or a default config if
/// none is stored.
pub fn get_global_config(&self) -> Result<SuggestGlobalConfig> {
self.get_meta::<String>(GLOBAL_CONFIG_META_KEY)?
.map_or_else(
|| Ok(SuggestGlobalConfig::default()),
|json| Ok(serde_json::from_str(&json)?),
)
}
/// Stores configuration data for a given provider.
pub fn put_provider_config(
&mut self,
provider: SuggestionProvider,
config: &SuggestProviderConfig,
) -> Result<()> {
self.put_meta(
&provider_config_meta_key(provider),
serde_json::to_string(config)?,
)
}
/// Gets the stored configuration data for a given provider or None if none
/// is stored.
pub fn get_provider_config(
&self,
provider: SuggestionProvider,
) -> Result<Option<SuggestProviderConfig>> {
self.get_meta::<String>(&provider_config_meta_key(provider))?
.map_or_else(|| Ok(None), |json| Ok(serde_json::from_str(&json)?))
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct IngestedRecord {
pub id: SuggestRecordId,
pub collection: String,
pub record_type: String,
pub last_modified: u64,
}
impl IngestedRecord {
fn from_row(row: &rusqlite::Row) -> Result<Self> {
Ok(Self {
id: SuggestRecordId::new(row.get("id")?),
collection: row.get("collection")?,
record_type: row.get("type")?,
last_modified: row.get("last_modified")?,
})
}
}
/// Helper struct to get full_keyword_ids for a suggestion
///
/// `FullKeywordInserter` handles repeated full keywords efficiently. The first instance will
/// cause a row to be inserted into the database. Subsequent instances will return the same
/// full_keyword_id.
struct FullKeywordInserter<'a> {
conn: &'a Connection,
suggestion_id: i64,
last_inserted: Option<(&'a str, i64)>,
}
impl<'a> FullKeywordInserter<'a> {
fn new(conn: &'a Connection, suggestion_id: i64) -> Self {
Self {
conn,
suggestion_id,
last_inserted: None,
}
}
fn maybe_insert(&mut self, full_keyword: &'a str) -> rusqlite::Result<i64> {
match self.last_inserted {
Some((s, id)) if s == full_keyword => Ok(id),
_ => {
let full_keyword_id = self.conn.query_row_and_then(
"INSERT INTO full_keywords(
suggestion_id,
full_keyword
)
VALUES(
:suggestion_id,
:keyword
)
RETURNING id",
named_params! {
":keyword": full_keyword,
":suggestion_id": self.suggestion_id,
},
|row| row.get(0),
)?;
self.last_inserted = Some((full_keyword, full_keyword_id));
Ok(full_keyword_id)
}
}
}
}
// ======================== Statement types ========================
//
// During ingestion we can insert hundreds of thousands of rows. These types enable speedups by
// allowing us to prepare a statement outside a loop and use it many times inside the loop.
//
// Each type wraps [Connection::prepare] and [Statement] to provide a simplified interface,
// tailored to a specific query.
//
// This pattern is applicable for whenever we execute the same query repeatedly in a loop.
// The impact scales with the number of loop iterations, which is why we currently don't do this
// for providers like Mdn, Pocket, and Weather, which have relatively small number of records
// compared to Amp/Wikipedia.
pub(crate) struct SuggestionInsertStatement<'conn>(rusqlite::Statement<'conn>);
impl<'conn> SuggestionInsertStatement<'conn> {
pub(crate) fn new(conn: &'conn Connection) -> Result<Self> {
Ok(Self(conn.prepare(
"INSERT INTO suggestions(
record_id,
title,
url,
score,
provider
)
VALUES(?, ?, ?, ?, ?)
RETURNING id",
)?))
}
/// Execute the insert and return the `suggestion_id` for the new row
pub(crate) fn execute(
&mut self,
record_id: &SuggestRecordId,
title: &str,
url: &str,
score: f64,
provider: SuggestionProvider,
) -> Result<i64> {
self.0
.query_row(
(record_id.as_str(), title, url, score, provider as u8),
|row| row.get(0),
)
.with_context("suggestion insert")
}
}
struct AmpInsertStatement<'conn>(rusqlite::Statement<'conn>);
impl<'conn> AmpInsertStatement<'conn> {
fn new(conn: &'conn Connection) -> Result<Self> {
Ok(Self(conn.prepare(
"INSERT INTO amp_custom_details(
suggestion_id,
advertiser,
block_id,
iab_category,
impression_url,
click_url,
icon_id
)
VALUES(?, ?, ?, ?, ?, ?, ?)
",
)?))
}
fn execute(&mut self, suggestion_id: i64, amp: &DownloadedAmpSuggestion) -> Result<()> {
self.0
.execute((
suggestion_id,
&.advertiser,
amp.block_id,
&.iab_category,
&.impression_url,
&.click_url,
&.icon_id,
))
.with_context("amp insert")?;
Ok(())
}
}
struct WikipediaInsertStatement<'conn>(rusqlite::Statement<'conn>);
impl<'conn> WikipediaInsertStatement<'conn> {
fn new(conn: &'conn Connection) -> Result<Self> {
Ok(Self(conn.prepare(
"INSERT INTO wikipedia_custom_details(
suggestion_id,
icon_id
)
VALUES(?, ?)
",
)?))
}
fn execute(
&mut self,
suggestion_id: i64,
wikipedia: &DownloadedWikipediaSuggestion,
) -> Result<()> {
self.0
.execute((suggestion_id, &wikipedia.icon_id))
.with_context("wikipedia insert")?;
Ok(())
}
}
struct AmoInsertStatement<'conn>(rusqlite::Statement<'conn>);
impl<'conn> AmoInsertStatement<'conn> {
fn new(conn: &'conn Connection) -> Result<Self> {
Ok(Self(conn.prepare(
"INSERT INTO amo_custom_details(
suggestion_id,
description,
guid,
icon_url,
rating,
number_of_ratings
)
VALUES(?, ?, ?, ?, ?, ?)
",
)?))
}
fn execute(&mut self, suggestion_id: i64, amo: &DownloadedAmoSuggestion) -> Result<()> {
self.0
.execute((
suggestion_id,
&amo.description,
&amo.guid,
&amo.icon_url,
&amo.rating,
amo.number_of_ratings,
))
.with_context("amo insert")?;
Ok(())
}
}
struct MdnInsertStatement<'conn>(rusqlite::Statement<'conn>);
impl<'conn> MdnInsertStatement<'conn> {
fn new(conn: &'conn Connection) -> Result<Self> {
Ok(Self(conn.prepare(
"INSERT INTO mdn_custom_details(
suggestion_id,
description
)
VALUES(?, ?)
",
)?))
}
fn execute(&mut self, suggestion_id: i64, mdn: &DownloadedMdnSuggestion) -> Result<()> {
self.0
.execute((suggestion_id, &mdn.description))
.with_context("mdn insert")?;
Ok(())
}
}
struct FakespotInsertStatement<'conn>(rusqlite::Statement<'conn>);
impl<'conn> FakespotInsertStatement<'conn> {
fn new(conn: &'conn Connection) -> Result<Self> {
Ok(Self(conn.prepare(
"INSERT INTO fakespot_custom_details(
suggestion_id,
fakespot_grade,
product_id,
keywords,
product_type,
rating,
total_reviews,
icon_id
)
VALUES(?, ?, ?, ?, ?, ?, ?, ?)
",
)?))
}
fn execute(
&mut self,
suggestion_id: i64,
fakespot: &DownloadedFakespotSuggestion,
) -> Result<()> {
let icon_id = fakespot
.product_id
.split_once('-')
.map(|(vendor, _)| format!("fakespot-{vendor}"));
self.0
.execute((
suggestion_id,
&fakespot.fakespot_grade,
&fakespot.product_id,
&fakespot.keywords.to_lowercase(),
&fakespot.product_type.to_lowercase(),
fakespot.rating,
fakespot.total_reviews,
icon_id,
))
.with_context("fakespot insert")?;
Ok(())
}
}
struct ExposureInsertStatement<'conn>(rusqlite::Statement<'conn>);
impl<'conn> ExposureInsertStatement<'conn> {
fn new(conn: &'conn Connection) -> Result<Self> {
Ok(Self(conn.prepare(
"INSERT INTO exposure_custom_details(
suggestion_id,
type
)
VALUES(?, ?)
",
)?))
}
fn execute(&mut self, suggestion_id: i64, suggestion_type: &str) -> Result<()> {
self.0
.execute((suggestion_id, suggestion_type))
.with_context("exposure insert")?;
Ok(())
}
}
pub(crate) struct KeywordInsertStatement<'conn>(rusqlite::Statement<'conn>);
impl<'conn> KeywordInsertStatement<'conn> {
pub(crate) fn new(conn: &'conn Connection) -> Result<Self> {
Ok(Self(conn.prepare(
"INSERT INTO keywords(
suggestion_id,
keyword,
full_keyword_id,
rank
)
VALUES(?, ?, ?, ?)
",
)?))
}
pub(crate) fn new_with_or_ignore(conn: &'conn Connection) -> Result<Self> {
Ok(Self(conn.prepare(
"INSERT OR IGNORE INTO keywords(
suggestion_id,
keyword,
full_keyword_id,
rank
)
VALUES(?, ?, ?, ?)
",
)?))
}
pub(crate) fn execute(
&mut self,
suggestion_id: i64,
keyword: &str,
full_keyword_id: Option<i64>,
rank: usize,
) -> Result<()> {
self.0
.execute((suggestion_id, keyword, full_keyword_id, rank))
.with_context("keyword insert")?;
Ok(())
}
}
struct PrefixKeywordInsertStatement<'conn>(rusqlite::Statement<'conn>);
impl<'conn> PrefixKeywordInsertStatement<'conn> {
fn new(conn: &'conn Connection) -> Result<Self> {
Ok(Self(conn.prepare(
"INSERT INTO prefix_keywords(
suggestion_id,
confidence,
keyword_prefix,
keyword_suffix,
rank
)
VALUES(?, ?, ?, ?, ?)
",
)?))
}
fn execute(
&mut self,
suggestion_id: i64,
confidence: Option<u8>,
keyword_prefix: &str,
keyword_suffix: &str,
rank: usize,
) -> Result<()> {
self.0
.execute((
suggestion_id,
confidence.unwrap_or(0),
keyword_prefix,
keyword_suffix,
rank,
))
.with_context("prefix keyword insert")?;
Ok(())
}
}
pub(crate) struct KeywordMetricsInsertStatement<'conn>(rusqlite::Statement<'conn>);
impl<'conn> KeywordMetricsInsertStatement<'conn> {
pub(crate) fn new(conn: &'conn Connection) -> Result<Self> {
Ok(Self(conn.prepare(
"INSERT INTO keywords_metrics(
record_id,
provider,
max_length,
max_word_count
)
VALUES(?, ?, ?, ?)
",
)?))
}
pub(crate) fn execute(
&mut self,
record_id: &SuggestRecordId,
provider: SuggestionProvider,
max_len: usize,
max_word_count: usize,
) -> Result<()> {
self.0
.execute((record_id.as_str(), provider, max_len, max_word_count))
.with_context("keyword metrics insert")?;
Ok(())
}
}
pub(crate) struct AmpFtsInsertStatement<'conn>(rusqlite::Statement<'conn>);
impl<'conn> AmpFtsInsertStatement<'conn> {
pub(crate) fn new(conn: &'conn Connection) -> Result<Self> {
Ok(Self(conn.prepare(
"INSERT INTO amp_fts(rowid, full_keywords, title)
VALUES(?, ?, ?)
",
)?))
}
pub(crate) fn execute(
&mut self,
suggestion_id: i64,
full_keywords: &str,
title: &str,
) -> Result<()> {
self.0
.execute((suggestion_id, full_keywords, title))
.with_context("amp fts insert")?;
Ok(())
}
}
fn provider_config_meta_key(provider: SuggestionProvider) -> String {
format!("{}{}", PROVIDER_CONFIG_META_KEY_PREFIX, provider as u8)
}