Debian Codegraph @

third_party/rust/suggest/src/db.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
4 */
5
6 use std::{cell::OnceCell, path::Path, sync::Arc};
7
8 use interrupt_support::{SqlInterruptHandle, SqlInterruptScope};
9 use parking_lot::{Mutex, MutexGuard};
10 use rusqlite::{
11 named_params,
12 types::{FromSql, ToSql},
13 Connection,
14 };
15 use sql_support::{open_database, repeat_sql_vars, ConnExt};
16
17 use crate::{
18 config::{SuggestGlobalConfig, SuggestProviderConfig},
19 error::RusqliteResultExt,
20 fakespot,
21 geoname::GeonameCache,
22 pocket::{split_keyword, KeywordConfidence},
23 provider::{AmpMatchingStrategy, SuggestionProvider},
24 query::{full_keywords_to_fts_content, FtsQuery},
25 rs::{
26 DownloadedAmoSuggestion, DownloadedAmpSuggestion, DownloadedDynamicRecord,
27 DownloadedDynamicSuggestion, DownloadedFakespotSuggestion, DownloadedMdnSuggestion,
28 DownloadedPocketSuggestion, DownloadedWikipediaSuggestion, Record, SuggestRecordId,
29 SuggestRecordType,
30 },
31 schema::{clear_database, SuggestConnectionInitializer},
32 suggestion::{cook_raw_suggestion_url, FtsMatchInfo, Suggestion},
33 util::full_keyword,
34 weather::WeatherCache,
35 Result, SuggestionQuery,
36 };
37
38 /// The metadata key whose value is a JSON string encoding a
39 /// `SuggestGlobalConfig`, which contains global Suggest configuration data.
40 pub const GLOBAL_CONFIG_META_KEY: &str = "global_config";
41 /// Prefix of metadata keys whose values are JSON strings encoding
42 /// `SuggestProviderConfig`, which contains per-provider configuration data. The
43 /// full key is this prefix plus the `SuggestionProvider` value as a u8.
44 pub const PROVIDER_CONFIG_META_KEY_PREFIX: &str = "provider_config_";
45
46 // Default value when Suggestion does not have a value for score
47 pub const DEFAULT_SUGGESTION_SCORE: f64 = 0.2;
48
49 /// The database connection type.
50 #[derive(Clone, Copy)]
51 pub(crate) enum ConnectionType {
52 ReadOnly,
53 ReadWrite,
54 }
55
56 #[derive(Default, Clone)]
57 pub struct Sqlite3Extension {
58 pub library: String,
59 pub entry_point: Option<String>,
60 }
61
62 /// A thread-safe wrapper around an SQLite connection to the Suggest database,
63 /// and its interrupt handle.
64 pub(crate) struct SuggestDb {
65 pub conn: Mutex<Connection>,
66
67 /// An object that's used to interrupt an ongoing database operation.
68 ///
69 /// When this handle is interrupted, the thread that's currently accessing
70 /// the database will be told to stop and release the `conn` lock as soon
71 /// as possible.
72 pub interrupt_handle: Arc<SqlInterruptHandle>,
73 }
74
75 impl SuggestDb {
76 /// Opens a read-only or read-write connection to a Suggest database at the
77 /// given path.
78 pub fn open(
79 path: impl AsRef<Path>,
80 extensions_to_load: &[Sqlite3Extension],
81 type_: ConnectionType,
82 ) -> Result<Self> {
83 let conn = open_database::open_database_with_flags(
84 path,
85 match type_ {
86 ConnectionType::ReadWrite => open_database::read_write_flags(),
87 ConnectionType::ReadOnly => open_database::read_only_flags(),
88 },
89 &SuggestConnectionInitializer::new(extensions_to_load),
90 )?;
91 Ok(Self::with_connection(conn))
92 }
93
94 fn with_connection(conn: Connection) -> Self {
95 let interrupt_handle = Arc::new(SqlInterruptHandle::new(&conn));
96 Self {
97 conn: Mutex::new(conn),
98 interrupt_handle,
99 }
100 }
101
102 /// Accesses the Suggest database for reading.
103 pub fn read<T>(&self, op: impl FnOnce(&SuggestDao) -> Result<T>) -> Result<T> {
104 let conn = self.conn.lock();
105 let scope = self.interrupt_handle.begin_interrupt_scope()?;
106 let dao = SuggestDao::new(&conn, &scope);
107 op(&dao)
108 }
109
110 /// Accesses the Suggest database in a transaction for reading and writing.
111 pub fn write<T>(&self, op: impl FnOnce(&mut SuggestDao) -> Result<T>) -> Result<T> {
112 let mut conn = self.conn.lock();
113 let scope = self.interrupt_handle.begin_interrupt_scope()?;
114 let tx = conn.transaction()?;
115 let mut dao = SuggestDao::new(&tx, &scope);
116 let result = op(&mut dao)?;
117 tx.commit()?;
118 Ok(result)
119 }
120
121 /// Create a new write scope.
122 ///
123 /// This enables performing multiple `write()` calls with the same shared interrupt scope.
124 /// This is important for things like ingestion, where you want the operation to be interrupted
125 /// if [Self::interrupt_handle::interrupt] is called after the operation starts. Calling
126 /// [Self::write] multiple times during the operation risks missing a call that happens after
127 /// between those calls.
128 pub fn write_scope(&self) -> Result<WriteScope> {
129 Ok(WriteScope {
130 conn: self.conn.lock(),
131 scope: self.interrupt_handle.begin_interrupt_scope()?,
132 })
133 }
134 }
135
136 pub(crate) struct WriteScope<'a> {
137 pub conn: MutexGuard<'a, Connection>,
138 pub scope: SqlInterruptScope,
139 }
140
141 impl WriteScope<'_> {
142 /// Accesses the Suggest database in a transaction for reading and writing.
143 pub fn write<T>(&mut self, op: impl FnOnce(&mut SuggestDao) -> Result<T>) -> Result<T> {
144 let tx = self.conn.transaction()?;
145 let mut dao = SuggestDao::new(&tx, &self.scope);
146 let result = op(&mut dao)?;
147 tx.commit()?;
148 Ok(result)
149 }
150
151 /// Accesses the Suggest database in a transaction for reading only
152 pub fn read<T>(&mut self, op: impl FnOnce(&SuggestDao) -> Result<T>) -> Result<T> {
153 let tx = self.conn.transaction()?;
154 let dao = SuggestDao::new(&tx, &self.scope);
155 let result = op(&dao)?;
156 tx.commit()?;
157 Ok(result)
158 }
159
160 pub fn err_if_interrupted(&self) -> Result<()> {
161 Ok(self.scope.err_if_interrupted()?)
162 }
163 }
164
165 /// A data access object (DAO) that wraps a connection to the Suggest database
166 /// with methods for reading and writing suggestions, icons, and metadata.
167 ///
168 /// Methods that only read from the database take an immutable reference to
169 /// `self` (`&self`), and methods that write to the database take a mutable
170 /// reference (`&mut self`).
171 pub(crate) struct SuggestDao<'a> {
172 pub conn: &'a Connection,
173 pub scope: &'a SqlInterruptScope,
174 pub weather_cache: OnceCell<WeatherCache>,
175 pub geoname_cache: OnceCell<GeonameCache>,
176 }
177
178 impl<'a> SuggestDao<'a> {
179 fn new(conn: &'a Connection, scope: &'a SqlInterruptScope) -> Self {
180 Self {
181 conn,
182 scope,
183 weather_cache: std::cell::OnceCell::new(),
184 geoname_cache: std::cell::OnceCell::new(),
185 }
186 }
187
188 // =============== High level API ===============
189 //
190 // These methods combine several low-level calls into one logical operation.
191
192 pub fn delete_record_data(&mut self, record_id: &SuggestRecordId) -> Result<()> {
193 // Drop either the icon or suggestions, records only contain one or the other
194 match record_id.as_icon_id() {
195 Some(icon_id) => self.drop_icon(icon_id)?,
196 None => self.drop_suggestions(record_id)?,
197 };
198 Ok(())
199 }
200
201 // =============== Low level API ===============
202 //
203 // These methods implement CRUD operations
204
205 pub fn get_ingested_records(&self) -> Result<Vec<IngestedRecord>> {
206 let mut stmt = self
207 .conn
208 .prepare_cached("SELECT id, collection, type, last_modified FROM ingested_records")?;
209 let rows = stmt.query_and_then((), IngestedRecord::from_row)?;
210 rows.collect()
211 }
212
213 pub fn update_ingested_records(
214 &mut self,
215 collection: &str,
216 new_records: &[&Record],
217 updated_records: &[&Record],
218 deleted_records: &[&IngestedRecord],
219 ) -> Result<()> {
220 let mut delete_stmt = self
221 .conn
222 .prepare_cached("DELETE FROM ingested_records WHERE collection = ? AND id = ?")?;
223 for deleted in deleted_records {
224 delete_stmt.execute((collection, deleted.id.as_str()))?;
225 }
226
227 let mut insert_stmt = self.conn.prepare_cached(
228 "INSERT OR REPLACE INTO ingested_records(id, collection, type, last_modified) VALUES(?, ?, ?, ?)",
229 )?;
230 for record in new_records.iter().chain(updated_records) {
231 insert_stmt.execute((
232 record.id.as_str(),
233 collection,
234 record.record_type().as_str(),
235 record.last_modified,
236 ))?;
237 }
238 Ok(())
239 }
240
241 /// Update the DB so that we re-ingest all records on the next ingestion.
242 ///
243 /// We hack this by setting the last_modified time to 1 so that the next time around we always
244 /// re-ingest the record.
245 pub fn force_reingest(&mut self) -> Result<()> {
246 self.conn
247 .prepare_cached("UPDATE ingested_records SET last_modified=1")?
248 .execute(())?;
249 Ok(())
250 }
251
252 pub fn suggestions_table_empty(&self) -> Result<bool> {
253 Ok(self
254 .conn
255 .query_one::<bool>("SELECT NOT EXISTS (SELECT 1 FROM suggestions)")?)
256 }
257
258 /// Fetches Suggestions of type Amp provider that match the given query
259 pub fn fetch_amp_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
260 let strategy = query
261 .provider_constraints
262 .as_ref()
263 .and_then(|c| c.amp_alternative_matching.as_ref());
264 match strategy {
265 None => self.fetch_amp_suggestions_using_keywords(query, true),
266 Some(AmpMatchingStrategy::NoKeywordExpansion) => {
267 self.fetch_amp_suggestions_using_keywords(query, false)
268 }
269 Some(AmpMatchingStrategy::FtsAgainstFullKeywords) => {
270 self.fetch_amp_suggestions_using_fts(query, "full_keywords")
271 }
272 Some(AmpMatchingStrategy::FtsAgainstTitle) => {
273 self.fetch_amp_suggestions_using_fts(query, "title")
274 }
275 }
276 }
277
278 pub fn fetch_amp_suggestions_using_keywords(
279 &self,
280 query: &SuggestionQuery,
281 allow_keyword_expansion: bool,
282 ) -> Result<Vec<Suggestion>> {
283 let keyword_lowercased = &query.keyword.to_lowercase();
284 let where_extra = if allow_keyword_expansion {
285 ""
286 } else {
287 "AND INSTR(CONCAT(fk.full_keyword, ' '), k.keyword) != 0"
288 };
289 let suggestions = self.conn.query_rows_and_then_cached(
290 &format!(
291 r#"
292 SELECT
293 s.id,
294 k.rank,
295 s.title,
296 s.url,
297 s.provider,
298 s.score,
299 fk.full_keyword
300 FROM
301 suggestions s
302 JOIN
303 keywords k
304 ON k.suggestion_id = s.id
305 LEFT JOIN
306 full_keywords fk
307 ON k.full_keyword_id = fk.id
308 WHERE
309 s.provider = :provider
310 AND k.keyword = :keyword
311 {where_extra}
312 AND NOT EXISTS (
313 -- For AMP suggestions dismissed with the deprecated URL-based dismissal API,
314 -- `dismissed_suggestions.url` will be the suggestion URL. With the new
315 -- `Suggestion`-based API, it will be the full keyword.
316 SELECT 1 FROM dismissed_suggestions WHERE url IN (fk.full_keyword, s.url)
317 )
318 "#
319 ),
320 named_params! {
321 ":keyword": keyword_lowercased,
322 ":provider": SuggestionProvider::Amp,
323 },
324 |row| -> Result<Suggestion> {
325 let suggestion_id: i64 = row.get("id")?;
326 let title = row.get("title")?;
327 let raw_url: String = row.get("url")?;
328 let score: f64 = row.get("score")?;
329 let full_keyword_from_db: Option<String> = row.get("full_keyword")?;
330
331 self.conn.query_row_and_then(
332 r#"
333 SELECT
334 amp.advertiser,
335 amp.block_id,
336 amp.iab_category,
337 amp.impression_url,
338 amp.click_url,
339 i.data AS icon,
340 i.mimetype AS icon_mimetype
341 FROM
342 amp_custom_details amp
343 LEFT JOIN
344 icons i ON amp.icon_id = i.id
345 WHERE
346 amp.suggestion_id = :suggestion_id
347 "#,
348 named_params! {
349 ":suggestion_id": suggestion_id
350 },
351 |row| {
352 let cooked_url = cook_raw_suggestion_url(&raw_url);
353 let raw_click_url = row.get::<_, String>("click_url")?;
354 let cooked_click_url = cook_raw_suggestion_url(&raw_click_url);
355
356 Ok(Suggestion::Amp {
357 block_id: row.get("block_id")?,
358 advertiser: row.get("advertiser")?,
359 iab_category: row.get("iab_category")?,
360 title,
361 url: cooked_url,
362 raw_url,
363 full_keyword: full_keyword_from_db.unwrap_or_default(),
364 icon: row.get("icon")?,
365 icon_mimetype: row.get("icon_mimetype")?,
366 impression_url: row.get("impression_url")?,
367 click_url: cooked_click_url,
368 raw_click_url,
369 score,
370 fts_match_info: None,
371 })
372 },
373 )
374 },
375 )?;
376 Ok(suggestions)
377 }
378
379 pub fn fetch_amp_suggestions_using_fts(
380 &self,
381 query: &SuggestionQuery,
382 fts_column: &str,
383 ) -> Result<Vec<Suggestion>> {
384 let fts_query = query.fts_query();
385 let match_arg = &fts_query.match_arg;
386 let suggestions = self.conn.query_rows_and_then_cached(
387 &format!(
388 r#"
389 SELECT
390 s.id,
391 s.title,
392 s.url,
393 s.provider,
394 s.score
395 FROM
396 suggestions s
397 JOIN
398 amp_fts fts
399 ON fts.rowid = s.id
400 WHERE
401 s.provider = :provider
402 AND amp_fts match '{fts_column}: {match_arg}'
403 AND NOT EXISTS (SELECT 1 FROM dismissed_suggestions WHERE url=s.url)
404 ORDER BY rank
405 LIMIT 1
406 "#
407 ),
408 named_params! {
409 ":provider": SuggestionProvider::Amp,
410 },
411 |row| -> Result<Suggestion> {
412 let suggestion_id: i64 = row.get("id")?;
413 let title: String = row.get("title")?;
414 let raw_url: String = row.get("url")?;
415 let score: f64 = row.get("score")?;
416
417 self.conn.query_row_and_then(
418 r#"
419 SELECT
420 amp.advertiser,
421 amp.block_id,
422 amp.iab_category,
423 amp.impression_url,
424 amp.click_url,
425 i.data AS icon,
426 i.mimetype AS icon_mimetype
427 FROM
428 amp_custom_details amp
429 LEFT JOIN
430 icons i ON amp.icon_id = i.id
431 WHERE
432 amp.suggestion_id = :suggestion_id
433 "#,
434 named_params! {
435 ":suggestion_id": suggestion_id
436 },
437 |row| {
438 let cooked_url = cook_raw_suggestion_url(&raw_url);
439 let raw_click_url = row.get::<_, String>("click_url")?;
440 let cooked_click_url = cook_raw_suggestion_url(&raw_click_url);
441 let match_info = self.fetch_amp_fts_match_info(
442 &fts_query,
443 suggestion_id,
444 fts_column,
445 &title,
446 )?;
447
448 Ok(Suggestion::Amp {
449 block_id: row.get("block_id")?,
450 advertiser: row.get("advertiser")?,
451 iab_category: row.get("iab_category")?,
452 title,
453 url: cooked_url,
454 raw_url,
455 full_keyword: query.keyword.clone(),
456 icon: row.get("icon")?,
457 icon_mimetype: row.get("icon_mimetype")?,
458 impression_url: row.get("impression_url")?,
459 click_url: cooked_click_url,
460 raw_click_url,
461 score,
462 fts_match_info: Some(match_info),
463 })
464 },
465 )
466 },
467 )?;
468 Ok(suggestions)
469 }
470
471 fn fetch_amp_fts_match_info(
472 &self,
473 fts_query: &FtsQuery<'_>,
474 suggestion_id: i64,
475 fts_column: &str,
476 title: &str,
477 ) -> Result<FtsMatchInfo> {
478 let fts_content = match fts_column {
479 "title" => title.to_lowercase(),
480 "full_keywords" => {
481 let full_keyword_list: Vec<String> = self.conn.query_rows_and_then(
482 "
483 SELECT fk.full_keyword
484 FROM full_keywords fk
485 JOIN keywords k on fk.id == k.full_keyword_id
486 WHERE k.suggestion_id = ?
487 ",
488 (suggestion_id,),
489 |row| row.get(0),
490 )?;
491 full_keywords_to_fts_content(full_keyword_list.iter().map(String::as_str))
492 }
493 // fts_column comes from the code above and we know there's only 2 possibilities
494 _ => unreachable!(),
495 };
496
497 let prefix = if fts_query.is_prefix_query {
498 // If the query was a prefix match query then test if the query without the prefix
499 // match would have also matched. If not, then this counts as a prefix match.
500 let sql = "SELECT 1 FROM amp_fts WHERE rowid = ? AND amp_fts MATCH ?";
501 let params = (&suggestion_id, &fts_query.match_arg_without_prefix_match);
502 !self.conn.exists(sql, params)?
503 } else {
504 // If not, then it definitely wasn't a prefix match
505 false
506 };
507
508 Ok(FtsMatchInfo {
509 prefix,
510 stemming: fts_query.match_required_stemming(&fts_content),
511 })
512 }
513
514 /// Fetches Suggestions of type Wikipedia provider that match the given query
515 pub fn fetch_wikipedia_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
516 let keyword_lowercased = &query.keyword.to_lowercase();
517 let suggestions = self.conn.query_rows_and_then_cached(
518 r#"
519 SELECT
520 s.id,
521 k.rank,
522 s.title,
523 s.url
524 FROM
525 suggestions s
526 JOIN
527 keywords k
528 ON k.suggestion_id = s.id
529 WHERE
530 s.provider = :provider
531 AND k.keyword = :keyword
532 AND NOT EXISTS (SELECT 1 FROM dismissed_suggestions WHERE url=s.url)
533 "#,
534 named_params! {
535 ":keyword": keyword_lowercased,
536 ":provider": SuggestionProvider::Wikipedia
537 },
538 |row| -> Result<Suggestion> {
539 let suggestion_id: i64 = row.get("id")?;
540 let title = row.get("title")?;
541 let raw_url = row.get::<_, String>("url")?;
542
543 let keywords: Vec<String> = self.conn.query_rows_and_then_cached(
544 "SELECT keyword FROM keywords
545 WHERE suggestion_id = :suggestion_id AND rank >= :rank
546 ORDER BY rank ASC",
547 named_params! {
548 ":suggestion_id": suggestion_id,
549 ":rank": row.get::<_, i64>("rank")?,
550 },
551 |row| row.get(0),
552 )?;
553 let (icon, icon_mimetype) = self
554 .conn
555 .try_query_row(
556 "SELECT i.data, i.mimetype
557 FROM icons i
558 JOIN wikipedia_custom_details s ON s.icon_id = i.id
559 WHERE s.suggestion_id = :suggestion_id
560 LIMIT 1",
561 named_params! {
562 ":suggestion_id": suggestion_id
563 },
564 |row| -> Result<_> {
565 Ok((
566 row.get::<_, Option<Vec<u8>>>(0)?,
567 row.get::<_, Option<String>>(1)?,
568 ))
569 },
570 true,
571 )?
572 .unwrap_or((None, None));
573
574 Ok(Suggestion::Wikipedia {
575 title,
576 url: raw_url,
577 full_keyword: full_keyword(keyword_lowercased, &keywords),
578 icon,
579 icon_mimetype,
580 })
581 },
582 )?;
583 Ok(suggestions)
584 }
585
586 /// Query for suggestions using the keyword prefix and provider
587 fn map_prefix_keywords<T>(
588 &self,
589 query: &SuggestionQuery,
590 provider: &SuggestionProvider,
591 mut mapper: impl FnMut(&rusqlite::Row, &str) -> Result<T>,
592 ) -> Result<Vec<T>> {
593 let keyword_lowercased = &query.keyword.to_lowercase();
594 let (keyword_prefix, keyword_suffix) = split_keyword(keyword_lowercased);
595 let suggestions_limit = query.limit.unwrap_or(-1);
596 self.conn.query_rows_and_then_cached(
597 r#"
598 SELECT
599 s.id,
600 MAX(k.rank) AS rank,
601 s.title,
602 s.url,
603 s.provider,
604 s.score,
605 k.keyword_suffix
606 FROM
607 suggestions s
608 JOIN
609 prefix_keywords k
610 ON k.suggestion_id = s.id
611 WHERE
612 k.keyword_prefix = :keyword_prefix
613 AND (k.keyword_suffix BETWEEN :keyword_suffix AND :keyword_suffix || x'FFFF')
614 AND s.provider = :provider
615 AND NOT EXISTS (SELECT 1 FROM dismissed_suggestions WHERE url=s.url)
616 GROUP BY
617 s.id
618 ORDER BY
619 s.score DESC,
620 rank DESC
621 LIMIT
622 :suggestions_limit
623 "#,
624 &[
625 (":keyword_prefix", &keyword_prefix as &dyn ToSql),
626 (":keyword_suffix", &keyword_suffix as &dyn ToSql),
627 (":provider", provider as &dyn ToSql),
628 (":suggestions_limit", &suggestions_limit as &dyn ToSql),
629 ],
630 |row| mapper(row, keyword_suffix),
631 )
632 }
633
634 /// Fetches Suggestions of type Amo provider that match the given query
635 pub fn fetch_amo_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
636 let suggestions = self
637 .map_prefix_keywords(
638 query,
639 &SuggestionProvider::Amo,
640 |row, keyword_suffix| -> Result<Option<Suggestion>> {
641 let suggestion_id: i64 = row.get("id")?;
642 let title = row.get("title")?;
643 let raw_url = row.get::<_, String>("url")?;
644 let score = row.get::<_, f64>("score")?;
645
646 let full_suffix = row.get::<_, String>("keyword_suffix")?;
647 full_suffix
648 .starts_with(keyword_suffix)
649 .then(|| {
650 self.conn.query_row_and_then(
651 r#"
652 SELECT
653 amo.description,
654 amo.guid,
655 amo.rating,
656 amo.icon_url,
657 amo.number_of_ratings
658 FROM
659 amo_custom_details amo
660 WHERE
661 amo.suggestion_id = :suggestion_id
662 "#,
663 named_params! {
664 ":suggestion_id": suggestion_id
665 },
666 |row| {
667 Ok(Suggestion::Amo {
668 title,
669 url: raw_url,
670 icon_url: row.get("icon_url")?,
671 description: row.get("description")?,
672 rating: row.get("rating")?,
673 number_of_ratings: row.get("number_of_ratings")?,
674 guid: row.get("guid")?,
675 score,
676 })
677 },
678 )
679 })
680 .transpose()
681 },
682 )?
683 .into_iter()
684 .flatten()
685 .collect();
686 Ok(suggestions)
687 }
688
689 /// Fetches Suggestions of type pocket provider that match the given query
690 pub fn fetch_pocket_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
691 let keyword_lowercased = &query.keyword.to_lowercase();
692 let (keyword_prefix, keyword_suffix) = split_keyword(keyword_lowercased);
693 let suggestions = self
694 .conn
695 .query_rows_and_then_cached(
696 r#"
697 SELECT
698 s.id,
699 MAX(k.rank) AS rank,
700 s.title,
701 s.url,
702 s.provider,
703 s.score,
704 k.confidence,
705 k.keyword_suffix
706 FROM
707 suggestions s
708 JOIN
709 prefix_keywords k
710 ON k.suggestion_id = s.id
711 WHERE
712 k.keyword_prefix = :keyword_prefix
713 AND (k.keyword_suffix BETWEEN :keyword_suffix AND :keyword_suffix || x'FFFF')
714 AND s.provider = :provider
715 AND NOT EXISTS (SELECT 1 FROM dismissed_suggestions WHERE url=s.url)
716 GROUP BY
717 s.id,
718 k.confidence
719 ORDER BY
720 s.score DESC,
721 rank DESC
722 "#,
723 named_params! {
724 ":keyword_prefix": keyword_prefix,
725 ":keyword_suffix": keyword_suffix,
726 ":provider": SuggestionProvider::Pocket,
727 },
728 |row| -> Result<Option<Suggestion>> {
729 let title = row.get("title")?;
730 let raw_url = row.get::<_, String>("url")?;
731 let score = row.get::<_, f64>("score")?;
732 let confidence = row.get("confidence")?;
733 let full_suffix = row.get::<_, String>("keyword_suffix")?;
734 let suffixes_match = match confidence {
735 KeywordConfidence::Low => full_suffix.starts_with(keyword_suffix),
736 KeywordConfidence::High => full_suffix == keyword_suffix,
737 };
738 if suffixes_match {
739 Ok(Some(Suggestion::Pocket {
740 title,
741 url: raw_url,
742 score,
743 is_top_pick: matches!(confidence, KeywordConfidence::High),
744 }))
745 } else {
746 Ok(None)
747 }
748 },
749 )?
750 .into_iter()
751 .flatten()
752 .take(
753 query
754 .limit
755 .and_then(|limit| usize::try_from(limit).ok())
756 .unwrap_or(usize::MAX),
757 )
758 .collect();
759 Ok(suggestions)
760 }
761
762 /// Fetches suggestions for MDN
763 pub fn fetch_mdn_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
764 let suggestions = self
765 .map_prefix_keywords(
766 query,
767 &SuggestionProvider::Mdn,
768 |row, keyword_suffix| -> Result<Option<Suggestion>> {
769 let suggestion_id: i64 = row.get("id")?;
770 let title = row.get("title")?;
771 let raw_url = row.get::<_, String>("url")?;
772 let score = row.get::<_, f64>("score")?;
773
774 let full_suffix = row.get::<_, String>("keyword_suffix")?;
775 full_suffix
776 .starts_with(keyword_suffix)
777 .then(|| {
778 self.conn.query_row_and_then(
779 r#"
780 SELECT
781 description
782 FROM
783 mdn_custom_details
784 WHERE
785 suggestion_id = :suggestion_id
786 "#,
787 named_params! {
788 ":suggestion_id": suggestion_id
789 },
790 |row| {
791 Ok(Suggestion::Mdn {
792 title,
793 url: raw_url,
794 description: row.get("description")?,
795 score,
796 })
797 },
798 )
799 })
800 .transpose()
801 },
802 )?
803 .into_iter()
804 .flatten()
805 .collect();
806
807 Ok(suggestions)
808 }
809
810 /// Fetches Fakespot suggestions
811 pub fn fetch_fakespot_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
812 let fts_query = query.fts_query();
813 let sql = r#"
814 SELECT
815 s.id,
816 s.title,
817 s.url,
818 s.score,
819 f.fakespot_grade,
820 f.product_id,
821 f.rating,
822 f.total_reviews,
823 i.data,
824 i.mimetype,
825 f.keywords,
826 f.product_type
827 FROM
828 suggestions s
829 JOIN
830 fakespot_fts fts
831 ON fts.rowid = s.id
832 JOIN
833 fakespot_custom_details f
834 ON f.suggestion_id = s.id
835 LEFT JOIN
836 icons i
837 ON i.id = f.icon_id
838 WHERE
839 fakespot_fts MATCH ?
840 ORDER BY
841 s.score DESC
842 "#
843 .to_string();
844
845 // Store the list of results plus the suggestion id for calculating the FTS match info
846 let mut results =
847 self.conn
848 .query_rows_and_then_cached(&sql, (&fts_query.match_arg,), |row| {
849 let id: usize = row.get(0)?;
850 let score = fakespot::FakespotScore::new(
851 &query.keyword,
852 row.get(10)?,
853 row.get(11)?,
854 row.get(3)?,
855 )
856 .as_suggest_score();
857 Result::Ok((
858 Suggestion::Fakespot {
859 title: row.get(1)?,
860 url: row.get(2)?,
861 score,
862 fakespot_grade: row.get(4)?,
863 product_id: row.get(5)?,
864 rating: row.get(6)?,
865 total_reviews: row.get(7)?,
866 icon: row.get(8)?,
867 icon_mimetype: row.get(9)?,
868 match_info: None,
869 },
870 id,
871 ))
872 })?;
873 // Sort the results, then add the FTS match info to the first one
874 // For performance reasons, this is only calculated for the result with the highest score.
875 // We assume that only one that will be shown to the user and therefore the only one we'll
876 // collect metrics for.
877 results.sort();
878 if let Some((suggestion, id)) = results.first_mut() {
879 match suggestion {
880 Suggestion::Fakespot {
881 match_info, title, ..
882 } => {
883 *match_info = Some(self.fetch_fakespot_fts_match_info(&fts_query, *id, title)?);
884 }
885 _ => unreachable!(),
886 }
887 }
888 Ok(results
889 .into_iter()
890 .map(|(suggestion, _)| suggestion)
891 .collect())
892 }
893
894 fn fetch_fakespot_fts_match_info(
895 &self,
896 fts_query: &FtsQuery<'_>,
897 suggestion_id: usize,
898 title: &str,
899 ) -> Result<FtsMatchInfo> {
900 let prefix = if fts_query.is_prefix_query {
901 // If the query was a prefix match query then test if the query without the prefix
902 // match would have also matched. If not, then this counts as a prefix match.
903 let sql = "SELECT 1 FROM fakespot_fts WHERE rowid = ? AND fakespot_fts MATCH ?";
904 let params = (&suggestion_id, &fts_query.match_arg_without_prefix_match);
905 !self.conn.exists(sql, params)?
906 } else {
907 // If not, then it definitely wasn't a prefix match
908 false
909 };
910
911 Ok(FtsMatchInfo {
912 prefix,
913 stemming: fts_query.match_required_stemming(title),
914 })
915 }
916
917 /// Fetches dynamic suggestions
918 pub fn fetch_dynamic_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
919 let Some(suggestion_types) = query
920 .provider_constraints
921 .as_ref()
922 .and_then(|c| c.dynamic_suggestion_types.as_ref())
923 else {
924 return Ok(vec![]);
925 };
926
927 let keyword = query.keyword.to_lowercase();
928 let params = rusqlite::params_from_iter(
929 std::iter::once(&SuggestionProvider::Dynamic as &dyn ToSql)
930 .chain(std::iter::once(&keyword as &dyn ToSql))
931 .chain(suggestion_types.iter().map(|t| t as &dyn ToSql)),
932 );
933 self.conn.query_rows_and_then_cached(
934 &format!(
935 r#"
936 SELECT
937 s.url,
938 s.score,
939 d.suggestion_type,
940 d.json_data
941 FROM
942 suggestions s
943 JOIN
944 dynamic_custom_details d
945 ON d.suggestion_id = s.id
946 JOIN
947 keywords k
948 ON k.suggestion_id = s.id
949 WHERE
950 s.provider = ?
951 AND k.keyword = ?
952 AND d.suggestion_type IN ({})
953 AND NOT EXISTS (SELECT 1 FROM dismissed_suggestions WHERE url = s.url)
954 ORDER BY
955 s.score ASC, d.suggestion_type ASC, s.id ASC
956 "#,
957 repeat_sql_vars(suggestion_types.len())
958 ),
959 params,
960 |row| -> Result<Suggestion> {
961 let dismissal_key: String = row.get("url")?;
962 let json_data: Option<String> = row.get("json_data")?;
963 Ok(Suggestion::Dynamic {
964 suggestion_type: row.get("suggestion_type")?,
965 data: match json_data {
966 None => None,
967 Some(j) => serde_json::from_str(&j)?,
968 },
969 score: row.get("score")?,
970 dismissal_key: (!dismissal_key.is_empty()).then_some(dismissal_key),
971 })
972 },
973 )
974 }
975
976 pub fn are_suggestions_ingested_for_record(&self, record_id: &SuggestRecordId) -> Result<bool> {
977 Ok(self.conn.exists(
978 r#"
979 SELECT
980 id
981 FROM
982 suggestions
983 WHERE
984 record_id = :record_id
985 "#,
986 named_params! {
987 ":record_id": record_id.as_str(),
988 },
989 )?)
990 }
991
992 pub fn is_amp_fts_data_ingested(&self, record_id: &SuggestRecordId) -> Result<bool> {
993 Ok(self.conn.exists(
994 r#"
995 SELECT 1
996 FROM suggestions s
997 JOIN amp_fts fts
998 ON fts.rowid = s.id
999 WHERE s.record_id = :record_id
1000 "#,
1001 named_params! {
1002 ":record_id": record_id.as_str(),
1003 },
1004 )?)
1005 }
1006
1007 /// Inserts all suggestions from a downloaded AMO attachment into
1008 /// the database.
1009 pub fn insert_amo_suggestions(
1010 &mut self,
1011 record_id: &SuggestRecordId,
1012 suggestions: &[DownloadedAmoSuggestion],
1013 ) -> Result<()> {
1014 let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
1015 let mut amo_insert = AmoInsertStatement::new(self.conn)?;
1016 let mut prefix_keyword_insert = PrefixKeywordInsertStatement::new(self.conn)?;
1017 for suggestion in suggestions {
1018 self.scope.err_if_interrupted()?;
1019 let suggestion_id = suggestion_insert.execute(
1020 record_id,
1021 &suggestion.title,
1022 &suggestion.url,
1023 suggestion.score,
1024 SuggestionProvider::Amo,
1025 )?;
1026 amo_insert.execute(suggestion_id, suggestion)?;
1027 for (index, keyword) in suggestion.keywords.iter().enumerate() {
1028 let (keyword_prefix, keyword_suffix) = split_keyword(keyword);
1029 prefix_keyword_insert.execute(
1030 suggestion_id,
1031 None,
1032 keyword_prefix,
1033 keyword_suffix,
1034 index,
1035 )?;
1036 }
1037 }
1038 Ok(())
1039 }
1040
1041 /// Inserts suggestions from an AMP attachment into the database.
1042 pub fn insert_amp_suggestions(
1043 &mut self,
1044 record_id: &SuggestRecordId,
1045 suggestions: &[DownloadedAmpSuggestion],
1046 enable_fts: bool,
1047 ) -> Result<()> {
1048 // Prepare statements outside of the loop. This results in a large performance
1049 // improvement on a fresh ingest, since there are so many rows.
1050 let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
1051 let mut amp_insert = AmpInsertStatement::new(self.conn)?;
1052 let mut keyword_insert = KeywordInsertStatement::new(self.conn)?;
1053 let mut fts_insert = AmpFtsInsertStatement::new(self.conn)?;
1054 for suggestion in suggestions {
1055 self.scope.err_if_interrupted()?;
1056 let suggestion_id = suggestion_insert.execute(
1057 record_id,
1058 &suggestion.title,
1059 &suggestion.url,
1060 suggestion.score.unwrap_or(DEFAULT_SUGGESTION_SCORE),
1061 SuggestionProvider::Amp,
1062 )?;
1063 amp_insert.execute(suggestion_id, suggestion)?;
1064 if enable_fts {
1065 fts_insert.execute(
1066 suggestion_id,
1067 &suggestion.full_keywords_fts_column(),
1068 &suggestion.title,
1069 )?;
1070 }
1071 let mut full_keyword_inserter = FullKeywordInserter::new(self.conn, suggestion_id);
1072 for keyword in suggestion.keywords() {
1073 let full_keyword_id = if let Some(full_keyword) = keyword.full_keyword {
1074 Some(full_keyword_inserter.maybe_insert(full_keyword)?)
1075 } else {
1076 None
1077 };
1078 keyword_insert.execute(
1079 suggestion_id,
1080 keyword.keyword,
1081 full_keyword_id,
1082 keyword.rank,
1083 )?;
1084 }
1085 }
1086 Ok(())
1087 }
1088
1089 /// Inserts suggestions from a Wikipedia attachment into the database.
1090 pub fn insert_wikipedia_suggestions(
1091 &mut self,
1092 record_id: &SuggestRecordId,
1093 suggestions: &[DownloadedWikipediaSuggestion],
1094 ) -> Result<()> {
1095 // Prepare statements outside of the loop. This results in a large performance
1096 // improvement on a fresh ingest, since there are so many rows.
1097 let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
1098 let mut wiki_insert = WikipediaInsertStatement::new(self.conn)?;
1099 let mut keyword_insert = KeywordInsertStatement::new(self.conn)?;
1100 for suggestion in suggestions {
1101 self.scope.err_if_interrupted()?;
1102 let suggestion_id = suggestion_insert.execute(
1103 record_id,
1104 &suggestion.title,
1105 &suggestion.url,
1106 suggestion.score.unwrap_or(DEFAULT_SUGGESTION_SCORE),
1107 SuggestionProvider::Wikipedia,
1108 )?;
1109 wiki_insert.execute(suggestion_id, suggestion)?;
1110 for keyword in suggestion.keywords() {
1111 // Don't update `full_keywords`, see bug 1876217.
1112 keyword_insert.execute(suggestion_id, keyword.keyword, None, keyword.rank)?;
1113 }
1114 }
1115 Ok(())
1116 }
1117
1118 /// Inserts all suggestions from a downloaded Pocket attachment into
1119 /// the database.
1120 pub fn insert_pocket_suggestions(
1121 &mut self,
1122 record_id: &SuggestRecordId,
1123 suggestions: &[DownloadedPocketSuggestion],
1124 ) -> Result<()> {
1125 let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
1126 let mut prefix_keyword_insert = PrefixKeywordInsertStatement::new(self.conn)?;
1127 for suggestion in suggestions {
1128 self.scope.err_if_interrupted()?;
1129 let suggestion_id = suggestion_insert.execute(
1130 record_id,
1131 &suggestion.title,
1132 &suggestion.url,
1133 suggestion.score,
1134 SuggestionProvider::Pocket,
1135 )?;
1136 for ((rank, keyword), confidence) in suggestion
1137 .high_confidence_keywords
1138 .iter()
1139 .enumerate()
1140 .zip(std::iter::repeat(KeywordConfidence::High))
1141 .chain(
1142 suggestion
1143 .low_confidence_keywords
1144 .iter()
1145 .enumerate()
1146 .zip(std::iter::repeat(KeywordConfidence::Low)),
1147 )
1148 {
1149 let (keyword_prefix, keyword_suffix) = split_keyword(keyword);
1150 prefix_keyword_insert.execute(
1151 suggestion_id,
1152 Some(confidence as u8),
1153 keyword_prefix,
1154 keyword_suffix,
1155 rank,
1156 )?;
1157 }
1158 }
1159 Ok(())
1160 }
1161
1162 /// Inserts all suggestions from a downloaded MDN attachment into
1163 /// the database.
1164 pub fn insert_mdn_suggestions(
1165 &mut self,
1166 record_id: &SuggestRecordId,
1167 suggestions: &[DownloadedMdnSuggestion],
1168 ) -> Result<()> {
1169 let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
1170 let mut mdn_insert = MdnInsertStatement::new(self.conn)?;
1171 let mut prefix_keyword_insert = PrefixKeywordInsertStatement::new(self.conn)?;
1172 for suggestion in suggestions {
1173 self.scope.err_if_interrupted()?;
1174 let suggestion_id = suggestion_insert.execute(
1175 record_id,
1176 &suggestion.title,
1177 &suggestion.url,
1178 suggestion.score,
1179 SuggestionProvider::Mdn,
1180 )?;
1181 mdn_insert.execute(suggestion_id, suggestion)?;
1182 for (index, keyword) in suggestion.keywords.iter().enumerate() {
1183 let (keyword_prefix, keyword_suffix) = split_keyword(keyword);
1184 prefix_keyword_insert.execute(
1185 suggestion_id,
1186 None,
1187 keyword_prefix,
1188 keyword_suffix,
1189 index,
1190 )?;
1191 }
1192 }
1193 Ok(())
1194 }
1195
1196 /// Inserts all suggestions from a downloaded Fakespot attachment into the database.
1197 pub fn insert_fakespot_suggestions(
1198 &mut self,
1199 record_id: &SuggestRecordId,
1200 suggestions: &[DownloadedFakespotSuggestion],
1201 ) -> Result<()> {
1202 let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
1203 let mut fakespot_insert = FakespotInsertStatement::new(self.conn)?;
1204 for suggestion in suggestions {
1205 let suggestion_id = suggestion_insert.execute(
1206 record_id,
1207 &suggestion.title,
1208 &suggestion.url,
1209 suggestion.score,
1210 SuggestionProvider::Fakespot,
1211 )?;
1212 fakespot_insert.execute(suggestion_id, suggestion)?;
1213 }
1214 Ok(())
1215 }
1216
1217 /// Inserts dynamic suggestion records data into the database.
1218 pub fn insert_dynamic_suggestions(
1219 &mut self,
1220 record_id: &SuggestRecordId,
1221 record: &DownloadedDynamicRecord,
1222 suggestions: &[DownloadedDynamicSuggestion],
1223 ) -> Result<()> {
1224 // `suggestion.keywords()` can yield duplicates for dynamic
1225 // suggestions, so ignore failures on insert in the uniqueness
1226 // constraint on `(suggestion_id, keyword)`.
1227 let mut keyword_insert = KeywordInsertStatement::new_with_or_ignore(self.conn)?;
1228 let mut suggestion_insert = SuggestionInsertStatement::new(self.conn)?;
1229 let mut dynamic_insert = DynamicInsertStatement::new(self.conn)?;
1230 for suggestion in suggestions {
1231 self.scope.err_if_interrupted()?;
1232 let suggestion_id = suggestion_insert.execute(
1233 record_id,
1234 // title - Not used by dynamic suggestions.
1235 "",
1236 // url - Dynamic suggestions store their dismissal key here
1237 // instead.
1238 suggestion.dismissal_key.as_deref().unwrap_or(""),
1239 record.score.unwrap_or(DEFAULT_SUGGESTION_SCORE),
1240 SuggestionProvider::Dynamic,
1241 )?;
1242 dynamic_insert.execute(suggestion_id, &record.suggestion_type, suggestion)?;
1243
1244 // Dynamic suggestions don't use `rank` but `(suggestion_id, rank)`
1245 // must be unique since there's an index on that tuple.
1246 for (rank, keyword) in suggestion.keywords().enumerate() {
1247 keyword_insert.execute(suggestion_id, &keyword, None, rank)?;
1248 }
1249 }
1250 Ok(())
1251 }
1252
1253 /// Inserts or replaces an icon for a suggestion into the database.
1254 pub fn put_icon(&mut self, icon_id: &str, data: &[u8], mimetype: &str) -> Result<()> {
1255 self.conn.execute(
1256 "INSERT OR REPLACE INTO icons(
1257 id,
1258 data,
1259 mimetype
1260 )
1261 VALUES(
1262 :id,
1263 :data,
1264 :mimetype
1265 )",
1266 named_params! {
1267 ":id": icon_id,
1268 ":data": data,
1269 ":mimetype": mimetype,
1270 },
1271 )?;
1272 Ok(())
1273 }
1274
1275 pub fn insert_dismissal(&self, key: &str) -> Result<()> {
1276 self.conn.execute(
1277 "INSERT OR IGNORE INTO dismissed_suggestions(url)
1278 VALUES(:url)",
1279 named_params! {
1280 ":url": key,
1281 },
1282 )?;
1283 Ok(())
1284 }
1285
1286 pub fn clear_dismissals(&self) -> Result<()> {
1287 self.conn.execute("DELETE FROM dismissed_suggestions", ())?;
1288 Ok(())
1289 }
1290
1291 pub fn has_dismissal(&self, key: &str) -> Result<bool> {
1292 Ok(self.conn.exists(
1293 "SELECT 1 FROM dismissed_suggestions WHERE url = :url",
1294 named_params! {
1295 ":url": key,
1296 },
1297 )?)
1298 }
1299
1300 pub fn any_dismissals(&self) -> Result<bool> {
1301 Ok(self
1302 .conn
1303 .exists("SELECT 1 FROM dismissed_suggestions LIMIT 1", ())?)
1304 }
1305
1306 /// Deletes all suggestions associated with a Remote Settings record from
1307 /// the database.
1308 pub fn drop_suggestions(&mut self, record_id: &SuggestRecordId) -> Result<()> {
1309 // If you update this, you probably need to update
1310 // `schema::clear_database()` too!
1311 //
1312 // Call `err_if_interrupted` before each statement since these have historically taken a
1313 // long time and caused shutdown hangs.
1314
1315 self.scope.err_if_interrupted()?;
1316 self.conn.execute_cached(
1317 "DELETE FROM keywords WHERE suggestion_id IN (SELECT id from suggestions WHERE record_id = :record_id)",
1318 named_params! { ":record_id": record_id.as_str() },
1319 )?;
1320 self.scope.err_if_interrupted()?;
1321 self.conn.execute_cached(
1322 "DELETE FROM full_keywords WHERE suggestion_id IN (SELECT id from suggestions WHERE record_id = :record_id)",
1323 named_params! { ":record_id": record_id.as_str() },
1324 )?;
1325 self.scope.err_if_interrupted()?;
1326 self.conn.execute_cached(
1327 "DELETE FROM prefix_keywords WHERE suggestion_id IN (SELECT id from suggestions WHERE record_id = :record_id)",
1328 named_params! { ":record_id": record_id.as_str() },
1329 )?;
1330 self.scope.err_if_interrupted()?;
1331 self.conn.execute_cached(
1332 "DELETE FROM keywords_metrics WHERE record_id = :record_id",
1333 named_params! { ":record_id": record_id.as_str() },
1334 )?;
1335 self.scope.err_if_interrupted()?;
1336 self.conn.execute_cached(
1337 "
1338 DELETE FROM fakespot_fts
1339 WHERE rowid IN (SELECT id from suggestions WHERE record_id = :record_id)
1340 ",
1341 named_params! { ":record_id": record_id.as_str() },
1342 )?;
1343 self.scope.err_if_interrupted()?;
1344 self.conn.execute_cached(
1345 "DELETE FROM suggestions WHERE record_id = :record_id",
1346 named_params! { ":record_id": record_id.as_str() },
1347 )?;
1348 self.scope.err_if_interrupted()?;
1349 self.conn.execute_cached(
1350 "DELETE FROM yelp_subjects WHERE record_id = :record_id",
1351 named_params! { ":record_id": record_id.as_str() },
1352 )?;
1353 self.scope.err_if_interrupted()?;
1354 self.conn.execute_cached(
1355 "DELETE FROM yelp_modifiers WHERE record_id = :record_id",
1356 named_params! { ":record_id": record_id.as_str() },
1357 )?;
1358 self.scope.err_if_interrupted()?;
1359 self.conn.execute_cached(
1360 "DELETE FROM yelp_custom_details WHERE record_id = :record_id",
1361 named_params! { ":record_id": record_id.as_str() },
1362 )?;
1363 self.scope.err_if_interrupted()?;
1364 self.conn.execute_cached(
1365 "DELETE FROM geonames WHERE record_id = :record_id",
1366 named_params! { ":record_id": record_id.as_str() },
1367 )?;
1368 self.scope.err_if_interrupted()?;
1369 self.conn.execute_cached(
1370 "DELETE FROM geonames_alternates WHERE record_id = :record_id",
1371 named_params! { ":record_id": record_id.as_str() },
1372 )?;
1373 self.scope.err_if_interrupted()?;
1374 self.conn.execute_cached(
1375 "DELETE FROM geonames_metrics WHERE record_id = :record_id",
1376 named_params! { ":record_id": record_id.as_str() },
1377 )?;
1378
1379 // Invalidate these caches since we might have deleted a record their
1380 // contents are based on.
1381 self.weather_cache.take();
1382 self.geoname_cache.take();
1383
1384 Ok(())
1385 }
1386
1387 /// Deletes an icon for a suggestion from the database.
1388 pub fn drop_icon(&mut self, icon_id: &str) -> Result<()> {
1389 self.conn.execute_cached(
1390 "DELETE FROM icons WHERE id = :id",
1391 named_params! { ":id": icon_id },
1392 )?;
1393 Ok(())
1394 }
1395
1396 /// Clears the database, removing all suggestions, icons, and metadata.
1397 pub fn clear(&mut self) -> Result<()> {
1398 Ok(clear_database(self.conn)?)
1399 }
1400
1401 /// Returns the value associated with a metadata key.
1402 pub fn get_meta<T: FromSql>(&self, key: &str) -> Result<Option<T>> {
1403 Ok(self.conn.try_query_one(
1404 "SELECT value FROM meta WHERE key = :key",
1405 named_params! { ":key": key },
1406 true,
1407 )?)
1408 }
1409
1410 /// Sets the value for a metadata key.
1411 pub fn put_meta(&mut self, key: &str, value: impl ToSql) -> Result<()> {
1412 self.conn.execute_cached(
1413 "INSERT OR REPLACE INTO meta(key, value) VALUES(:key, :value)",
1414 named_params! { ":key": key, ":value": value },
1415 )?;
1416 Ok(())
1417 }
1418
1419 /// Stores global Suggest configuration data.
1420 pub fn put_global_config(&mut self, config: &SuggestGlobalConfig) -> Result<()> {
1421 self.put_meta(GLOBAL_CONFIG_META_KEY, serde_json::to_string(config)?)
1422 }
1423
1424 /// Gets the stored global Suggest configuration data or a default config if
1425 /// none is stored.
1426 pub fn get_global_config(&self) -> Result<SuggestGlobalConfig> {
1427 self.get_meta::<String>(GLOBAL_CONFIG_META_KEY)?
1428 .map_or_else(
1429 || Ok(SuggestGlobalConfig::default()),
1430 |json| Ok(serde_json::from_str(&json)?),
1431 )
1432 }
1433
1434 /// Stores configuration data for a given provider.
1435 pub fn put_provider_config(
1436 &mut self,
1437 provider: SuggestionProvider,
1438 config: &SuggestProviderConfig,
1439 ) -> Result<()> {
1440 self.put_meta(
1441 &provider_config_meta_key(provider),
1442 serde_json::to_string(config)?,
1443 )
1444 }
1445
1446 /// Gets the stored configuration data for a given provider or None if none
1447 /// is stored.
1448 pub fn get_provider_config(
1449 &self,
1450 provider: SuggestionProvider,
1451 ) -> Result<Option<SuggestProviderConfig>> {
1452 self.get_meta::<String>(&provider_config_meta_key(provider))?
1453 .map_or_else(|| Ok(None), |json| Ok(serde_json::from_str(&json)?))
1454 }
1455
1456 /// Gets keywords metrics for a record type.
1457 pub fn get_keywords_metrics(&self, record_type: SuggestRecordType) -> Result<KeywordsMetrics> {
1458 let data = self.conn.try_query_row(
1459 r#"
1460 SELECT
1461 max(max_len) AS len,
1462 max(max_word_count) AS word_count
1463 FROM
1464 keywords_metrics
1465 WHERE
1466 record_type = :record_type
1467 "#,
1468 named_params! {
1469 ":record_type": record_type,
1470 },
1471 |row| -> Result<(usize, usize)> { Ok((row.get("len")?, row.get("word_count")?)) },
1472 true, // cache
1473 )?;
1474 Ok(data
1475 .map(|(max_len, max_word_count)| KeywordsMetrics {
1476 max_len,
1477 max_word_count,
1478 })
1479 .unwrap_or_default())
1480 }
1481 }
1482
1483 #[derive(Debug, PartialEq, Eq, Hash)]
1484 pub struct IngestedRecord {
1485 pub id: SuggestRecordId,
1486 pub collection: String,
1487 pub record_type: String,
1488 pub last_modified: u64,
1489 }
1490
1491 impl IngestedRecord {
1492 fn from_row(row: &rusqlite::Row) -> Result<Self> {
1493 Ok(Self {
1494 id: SuggestRecordId::new(row.get("id")?),
1495 collection: row.get("collection")?,
1496 record_type: row.get("type")?,
1497 last_modified: row.get("last_modified")?,
1498 })
1499 }
1500 }
1501
1502 /// Helper struct to get full_keyword_ids for a suggestion
1503 ///
1504 /// `FullKeywordInserter` handles repeated full keywords efficiently. The first instance will
1505 /// cause a row to be inserted into the database. Subsequent instances will return the same
1506 /// full_keyword_id.
1507 struct FullKeywordInserter<'a> {
1508 conn: &'a Connection,
1509 suggestion_id: i64,
1510 last_inserted: Option<(&'a str, i64)>,
1511 }
1512
1513 impl<'a> FullKeywordInserter<'a> {
1514 fn new(conn: &'a Connection, suggestion_id: i64) -> Self {
1515 Self {
1516 conn,
1517 suggestion_id,
1518 last_inserted: None,
1519 }
1520 }
1521
1522 fn maybe_insert(&mut self, full_keyword: &'a str) -> rusqlite::Result<i64> {
1523 match self.last_inserted {
1524 Some((s, id)) if s == full_keyword => Ok(id),
1525 _ => {
1526 let full_keyword_id = self.conn.query_row_and_then(
1527 "INSERT INTO full_keywords(
1528 suggestion_id,
1529 full_keyword
1530 )
1531 VALUES(
1532 :suggestion_id,
1533 :keyword
1534 )
1535 RETURNING id",
1536 named_params! {
1537 ":keyword": full_keyword,
1538 ":suggestion_id": self.suggestion_id,
1539 },
1540 |row| row.get(0),
1541 )?;
1542 self.last_inserted = Some((full_keyword, full_keyword_id));
1543 Ok(full_keyword_id)
1544 }
1545 }
1546 }
1547 }
1548
1549 // ======================== Statement types ========================
1550 //
1551 // During ingestion we can insert hundreds of thousands of rows. These types enable speedups by
1552 // allowing us to prepare a statement outside a loop and use it many times inside the loop.
1553 //
1554 // Each type wraps [Connection::prepare] and [Statement] to provide a simplified interface,
1555 // tailored to a specific query.
1556 //
1557 // This pattern is applicable for whenever we execute the same query repeatedly in a loop.
1558 // The impact scales with the number of loop iterations, which is why we currently don't do this
1559 // for providers like Mdn, Pocket, and Weather, which have relatively small number of records
1560 // compared to Amp/Wikipedia.
1561
1562 pub(crate) struct SuggestionInsertStatement<'conn>(rusqlite::Statement<'conn>);
1563
1564 impl<'conn> SuggestionInsertStatement<'conn> {
1565 pub(crate) fn new(conn: &'conn Connection) -> Result<Self> {
1566 Ok(Self(conn.prepare(
1567 "INSERT INTO suggestions(
1568 record_id,
1569 title,
1570 url,
1571 score,
1572 provider
1573 )
1574 VALUES(?, ?, ?, ?, ?)
1575 RETURNING id",
1576 )?))
1577 }
1578
1579 /// Execute the insert and return the `suggestion_id` for the new row
1580 pub(crate) fn execute(
1581 &mut self,
1582 record_id: &SuggestRecordId,
1583 title: &str,
1584 url: &str,
1585 score: f64,
1586 provider: SuggestionProvider,
1587 ) -> Result<i64> {
1588 self.0
1589 .query_row(
1590 (record_id.as_str(), title, url, score, provider as u8),
1591 |row| row.get(0),
1592 )
1593 .with_context("suggestion insert")
1594 }
1595 }
1596
1597 struct AmpInsertStatement<'conn>(rusqlite::Statement<'conn>);
1598
1599 impl<'conn> AmpInsertStatement<'conn> {
1600 fn new(conn: &'conn Connection) -> Result<Self> {
1601 Ok(Self(conn.prepare(
1602 "INSERT INTO amp_custom_details(
1603 suggestion_id,
1604 advertiser,
1605 block_id,
1606 iab_category,
1607 impression_url,
1608 click_url,
1609 icon_id
1610 )
1611 VALUES(?, ?, ?, ?, ?, ?, ?)
1612 ",
1613 )?))
1614 }
1615
1616 fn execute(&mut self, suggestion_id: i64, amp: &DownloadedAmpSuggestion) -> Result<()> {
1617 self.0
1618 .execute((
1619 suggestion_id,
1620 &amp.advertiser,
1621 amp.block_id,
1622 &amp.iab_category,
1623 &amp.impression_url,
1624 &amp.click_url,
1625 &amp.icon_id,
1626 ))
1627 .with_context("amp insert")?;
1628 Ok(())
1629 }
1630 }
1631
1632 struct WikipediaInsertStatement<'conn>(rusqlite::Statement<'conn>);
1633
1634 impl<'conn> WikipediaInsertStatement<'conn> {
1635 fn new(conn: &'conn Connection) -> Result<Self> {
1636 Ok(Self(conn.prepare(
1637 "INSERT INTO wikipedia_custom_details(
1638 suggestion_id,
1639 icon_id
1640 )
1641 VALUES(?, ?)
1642 ",
1643 )?))
1644 }
1645
1646 fn execute(
1647 &mut self,
1648 suggestion_id: i64,
1649 wikipedia: &DownloadedWikipediaSuggestion,
1650 ) -> Result<()> {
1651 self.0
1652 .execute((suggestion_id, &wikipedia.icon_id))
1653 .with_context("wikipedia insert")?;
1654 Ok(())
1655 }
1656 }
1657
1658 struct AmoInsertStatement<'conn>(rusqlite::Statement<'conn>);
1659
1660 impl<'conn> AmoInsertStatement<'conn> {
1661 fn new(conn: &'conn Connection) -> Result<Self> {
1662 Ok(Self(conn.prepare(
1663 "INSERT INTO amo_custom_details(
1664 suggestion_id,
1665 description,
1666 guid,
1667 icon_url,
1668 rating,
1669 number_of_ratings
1670 )
1671 VALUES(?, ?, ?, ?, ?, ?)
1672 ",
1673 )?))
1674 }
1675
1676 fn execute(&mut self, suggestion_id: i64, amo: &DownloadedAmoSuggestion) -> Result<()> {
1677 self.0
1678 .execute((
1679 suggestion_id,
1680 &amo.description,
1681 &amo.guid,
1682 &amo.icon_url,
1683 &amo.rating,
1684 amo.number_of_ratings,
1685 ))
1686 .with_context("amo insert")?;
1687 Ok(())
1688 }
1689 }
1690
1691 struct MdnInsertStatement<'conn>(rusqlite::Statement<'conn>);
1692
1693 impl<'conn> MdnInsertStatement<'conn> {
1694 fn new(conn: &'conn Connection) -> Result<Self> {
1695 Ok(Self(conn.prepare(
1696 "INSERT INTO mdn_custom_details(
1697 suggestion_id,
1698 description
1699 )
1700 VALUES(?, ?)
1701 ",
1702 )?))
1703 }
1704
1705 fn execute(&mut self, suggestion_id: i64, mdn: &DownloadedMdnSuggestion) -> Result<()> {
1706 self.0
1707 .execute((suggestion_id, &mdn.description))
1708 .with_context("mdn insert")?;
1709 Ok(())
1710 }
1711 }
1712
1713 struct FakespotInsertStatement<'conn>(rusqlite::Statement<'conn>);
1714
1715 impl<'conn> FakespotInsertStatement<'conn> {
1716 fn new(conn: &'conn Connection) -> Result<Self> {
1717 Ok(Self(conn.prepare(
1718 "INSERT INTO fakespot_custom_details(
1719 suggestion_id,
1720 fakespot_grade,
1721 product_id,
1722 keywords,
1723 product_type,
1724 rating,
1725 total_reviews,
1726 icon_id
1727 )
1728 VALUES(?, ?, ?, ?, ?, ?, ?, ?)
1729 ",
1730 )?))
1731 }
1732
1733 fn execute(
1734 &mut self,
1735 suggestion_id: i64,
1736 fakespot: &DownloadedFakespotSuggestion,
1737 ) -> Result<()> {
1738 let icon_id = fakespot
1739 .product_id
1740 .split_once('-')
1741 .map(|(vendor, _)| format!("fakespot-{vendor}"));
1742 self.0
1743 .execute((
1744 suggestion_id,
1745 &fakespot.fakespot_grade,
1746 &fakespot.product_id,
1747 &fakespot.keywords.to_lowercase(),
1748 &fakespot.product_type.to_lowercase(),
1749 fakespot.rating,
1750 fakespot.total_reviews,
1751 icon_id,
1752 ))
1753 .with_context("fakespot insert")?;
1754 Ok(())
1755 }
1756 }
1757
1758 struct DynamicInsertStatement<'conn>(rusqlite::Statement<'conn>);
1759
1760 impl<'conn> DynamicInsertStatement<'conn> {
1761 fn new(conn: &'conn Connection) -> Result<Self> {
1762 Ok(Self(conn.prepare(
1763 "INSERT INTO dynamic_custom_details(
1764 suggestion_id,
1765 suggestion_type,
1766 json_data
1767 )
1768 VALUES(?, ?, ?)
1769 ",
1770 )?))
1771 }
1772
1773 fn execute(
1774 &mut self,
1775 suggestion_id: i64,
1776 suggestion_type: &str,
1777 suggestion: &DownloadedDynamicSuggestion,
1778 ) -> Result<()> {
1779 self.0
1780 .execute((
1781 suggestion_id,
1782 suggestion_type,
1783 match &suggestion.data {
1784 None => None,
1785 Some(d) => Some(serde_json::to_string(&d)?),
1786 },
1787 ))
1788 .with_context("dynamic insert")?;
1789 Ok(())
1790 }
1791 }
1792
1793 pub(crate) struct KeywordInsertStatement<'conn>(rusqlite::Statement<'conn>);
1794
1795 impl<'conn> KeywordInsertStatement<'conn> {
1796 pub(crate) fn new(conn: &'conn Connection) -> Result<Self> {
1797 Ok(Self(conn.prepare(
1798 "INSERT INTO keywords(
1799 suggestion_id,
1800 keyword,
1801 full_keyword_id,
1802 rank
1803 )
1804 VALUES(?, ?, ?, ?)
1805 ",
1806 )?))
1807 }
1808
1809 pub(crate) fn new_with_or_ignore(conn: &'conn Connection) -> Result<Self> {
1810 Ok(Self(conn.prepare(
1811 "INSERT OR IGNORE INTO keywords(
1812 suggestion_id,
1813 keyword,
1814 full_keyword_id,
1815 rank
1816 )
1817 VALUES(?, ?, ?, ?)
1818 ",
1819 )?))
1820 }
1821
1822 pub(crate) fn execute(
1823 &mut self,
1824 suggestion_id: i64,
1825 keyword: &str,
1826 full_keyword_id: Option<i64>,
1827 rank: usize,
1828 ) -> Result<()> {
1829 self.0
1830 .execute((suggestion_id, keyword, full_keyword_id, rank))
1831 .with_context("keyword insert")?;
1832 Ok(())
1833 }
1834 }
1835
1836 struct PrefixKeywordInsertStatement<'conn>(rusqlite::Statement<'conn>);
1837
1838 impl<'conn> PrefixKeywordInsertStatement<'conn> {
1839 fn new(conn: &'conn Connection) -> Result<Self> {
1840 Ok(Self(conn.prepare(
1841 "INSERT INTO prefix_keywords(
1842 suggestion_id,
1843 confidence,
1844 keyword_prefix,
1845 keyword_suffix,
1846 rank
1847 )
1848 VALUES(?, ?, ?, ?, ?)
1849 ",
1850 )?))
1851 }
1852
1853 fn execute(
1854 &mut self,
1855 suggestion_id: i64,
1856 confidence: Option<u8>,
1857 keyword_prefix: &str,
1858 keyword_suffix: &str,
1859 rank: usize,
1860 ) -> Result<()> {
1861 self.0
1862 .execute((
1863 suggestion_id,
1864 confidence.unwrap_or(0),
1865 keyword_prefix,
1866 keyword_suffix,
1867 rank,
1868 ))
1869 .with_context("prefix keyword insert")?;
1870 Ok(())
1871 }
1872 }
1873
1874 #[derive(Debug, Default)]
1875 pub(crate) struct KeywordsMetrics {
1876 pub(crate) max_len: usize,
1877 pub(crate) max_word_count: usize,
1878 }
1879
1880 /// This can be used to update metrics as keywords are inserted into the DB.
1881 /// Create a `KeywordsMetricsUpdater`, call `update` on it as each keyword is
1882 /// inserted, and then call `finish` after all keywords have been inserted.
1883 pub(crate) struct KeywordsMetricsUpdater {
1884 pub(crate) max_len: usize,
1885 pub(crate) max_word_count: usize,
1886 }
1887
1888 impl KeywordsMetricsUpdater {
1889 pub(crate) fn new() -> Self {
1890 Self {
1891 max_len: 0,
1892 max_word_count: 0,
1893 }
1894 }
1895
1896 pub(crate) fn update(&mut self, keyword: &str) {
1897 self.max_len = std::cmp::max(self.max_len, keyword.len());
1898 self.max_word_count =
1899 std::cmp::max(self.max_word_count, keyword.split_whitespace().count());
1900 }
1901
1902 /// Inserts keywords metrics into the database. This assumes you have a
1903 /// cache object inside the `cache` cell that caches the metrics. It will be
1904 /// cleared since it will be invalidated by the metrics update.
1905 pub(crate) fn finish<T>(
1906 &self,
1907 conn: &Connection,
1908 record_id: &SuggestRecordId,
1909 record_type: SuggestRecordType,
1910 cache: &mut OnceCell<T>,
1911 ) -> Result<()> {
1912 let mut insert_stmt = conn.prepare(
1913 r#"
1914 INSERT OR REPLACE INTO keywords_metrics(
1915 record_id,
1916 record_type,
1917 max_len,
1918 max_word_count
1919 )
1920 VALUES(?, ?, ?, ?)
1921 "#,
1922 )?;
1923 insert_stmt
1924 .execute((
1925 record_id.as_str(),
1926 record_type,
1927 self.max_len,
1928 self.max_word_count,
1929 ))
1930 .with_context("keywords metrics insert")?;
1931
1932 // We just made some insertions that might invalidate the data in the
1933 // cache. Clear it so it's repopulated the next time it's accessed.
1934 cache.take();
1935
1936 Ok(())
1937 }
1938 }
1939
1940 pub(crate) struct AmpFtsInsertStatement<'conn>(rusqlite::Statement<'conn>);
1941
1942 impl<'conn> AmpFtsInsertStatement<'conn> {
1943 pub(crate) fn new(conn: &'conn Connection) -> Result<Self> {
1944 Ok(Self(conn.prepare(
1945 "INSERT INTO amp_fts(rowid, full_keywords, title)
1946 VALUES(?, ?, ?)
1947 ",
1948 )?))
1949 }
1950
1951 pub(crate) fn execute(
1952 &mut self,
1953 suggestion_id: i64,
1954 full_keywords: &str,
1955 title: &str,
1956 ) -> Result<()> {
1957 self.0
1958 .execute((suggestion_id, full_keywords, title))
1959 .with_context("amp fts insert")?;
1960 Ok(())
1961 }
1962 }
1963
1964 fn provider_config_meta_key(provider: SuggestionProvider) -> String {
1965 format!("{}{}", PROVIDER_CONFIG_META_KEY_PREFIX, provider as u8)
1966 }