-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathdb.rs
More file actions
2008 lines (1868 loc) · 70.2 KB
/
db.rs
File metadata and controls
2008 lines (1868 loc) · 70.2 KB
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
/* 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,
provider::{AmpMatchingStrategy, SuggestionProvider},
query::{full_keywords_to_fts_content, FtsQuery},
rs::{
DownloadedAmoSuggestion, DownloadedAmpSuggestion, DownloadedDynamicRecord,
DownloadedDynamicSuggestion, DownloadedFakespotSuggestion, DownloadedMdnSuggestion,
DownloadedWikipediaSuggestion, Record, SuggestRecordId, SuggestRecordType,
},
schema::{clear_database, SuggestConnectionInitializer},
suggestion::{cook_raw_suggestion_url, FtsMatchInfo, Suggestion},
util::{full_keyword, i18n_transform, split_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 (
-- For AMP suggestions dismissed with the deprecated URL-based dismissal API,
-- `dismissed_suggestions.url` will be the suggestion URL. With the new
-- `Suggestion`-based API, it will be the full keyword.
SELECT 1 FROM dismissed_suggestions WHERE url IN (fk.full_keyword, 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")?;
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_default(),
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 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 dynamic suggestions
pub fn fetch_dynamic_suggestions(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>> {
let Some(suggestion_types) = query
.provider_constraints
.as_ref()
.and_then(|c| c.dynamic_suggestion_types.as_ref())
else {
return Ok(vec![]);
};
let keyword = query.keyword.to_lowercase();
let params = rusqlite::params_from_iter(
std::iter::once(&SuggestionProvider::Dynamic 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
s.url,
s.score,
d.suggestion_type,
d.json_data
FROM
suggestions s
JOIN
dynamic_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.suggestion_type IN ({})
AND NOT EXISTS (SELECT 1 FROM dismissed_suggestions WHERE url = s.url)
ORDER BY
s.score ASC, d.suggestion_type ASC, s.id ASC
"#,
repeat_sql_vars(suggestion_types.len())
),
params,
|row| -> Result<Suggestion> {
let dismissal_key: String = row.get("url")?;
let json_data: Option<String> = row.get("json_data")?;
Ok(Suggestion::Dynamic {
suggestion_type: row.get("suggestion_type")?,
data: match json_data {
None => None,
Some(j) => serde_json::from_str(&j)?,
},
score: row.get("score")?,
dismissal_key: (!dismissal_key.is_empty()).then_some(dismissal_key),
})
},
)
}
pub fn are_suggestions_ingested_for_record(&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 {