Debian Codegraph @

third_party/rust/suggest/src/schema.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 crate::{db::Sqlite3Extension, geoname::geonames_collate};
7 use rusqlite::{Connection, Transaction};
8 use sql_support::{
9 open_database::{self, ConnectionInitializer},
10 ConnExt,
11 };
12
13 /// The current database schema version.
14 ///
15 /// For any changes to the schema [`SQL`], please make sure to:
16 ///
17 /// 1. Bump this version.
18 /// 2. Add a migration from the old version to the new version in
19 /// [`SuggestConnectionInitializer::upgrade_from`].
20 /// a. If suggestions should be re-ingested after the migration, call `clear_database()` inside
21 /// the migration.
22 /// 3. If the migration adds any tables, delete their their rows in
23 /// `clear_database()` by adding their names to `conditional_tables`, unless
24 /// they are cleared via a deletion trigger or there's some other good
25 /// reason not to do so.
26 pub const VERSION: u32 = 41;
27
28 /// The current Suggest database schema.
29 pub const SQL: &str = "
30 CREATE TABLE meta(
31 key TEXT PRIMARY KEY,
32 value NOT NULL
33 ) WITHOUT ROWID;
34
35 CREATE TABLE ingested_records(
36 id TEXT,
37 collection TEXT,
38 type TEXT NOT NULL,
39 last_modified INTEGER NOT NULL,
40 PRIMARY KEY (id, collection)
41 ) WITHOUT ROWID;
42
43 CREATE TABLE keywords(
44 keyword TEXT NOT NULL,
45 suggestion_id INTEGER NOT NULL,
46 full_keyword_id INTEGER NULL,
47 rank INTEGER NOT NULL,
48 PRIMARY KEY (keyword, suggestion_id)
49 ) WITHOUT ROWID;
50
51 -- Keywords metrics per record ID and type. Currently we only record metrics for
52 -- a small number of record types.
53 CREATE TABLE keywords_metrics(
54 record_id TEXT NOT NULL PRIMARY KEY,
55 record_type TEXT NOT NULL,
56 max_len INTEGER NOT NULL,
57 max_word_count INTEGER NOT NULL
58 ) WITHOUT ROWID;
59
60 CREATE INDEX keywords_metrics_record_type ON keywords_metrics(record_type);
61
62 -- full keywords are what we display to the user when a (partial) keyword matches
63 CREATE TABLE full_keywords(
64 id INTEGER PRIMARY KEY,
65 suggestion_id INTEGER NOT NULL,
66 full_keyword TEXT NOT NULL
67 );
68
69 CREATE TABLE prefix_keywords(
70 keyword_prefix TEXT NOT NULL,
71 keyword_suffix TEXT NOT NULL DEFAULT '',
72 confidence INTEGER NOT NULL DEFAULT 0,
73 rank INTEGER NOT NULL,
74 suggestion_id INTEGER NOT NULL,
75 PRIMARY KEY (keyword_prefix, keyword_suffix, suggestion_id)
76 ) WITHOUT ROWID;
77
78 CREATE UNIQUE INDEX keywords_suggestion_id_rank ON keywords(suggestion_id, rank);
79
80 CREATE TABLE suggestions(
81 id INTEGER PRIMARY KEY,
82 record_id TEXT NOT NULL,
83 provider INTEGER NOT NULL,
84 title TEXT NOT NULL,
85 url TEXT NOT NULL,
86 score REAL NOT NULL
87 );
88
89 CREATE TABLE amp_custom_details(
90 suggestion_id INTEGER PRIMARY KEY,
91 advertiser TEXT NOT NULL,
92 block_id INTEGER NOT NULL,
93 iab_category TEXT NOT NULL,
94 impression_url TEXT NOT NULL,
95 click_url TEXT NOT NULL,
96 icon_id TEXT NOT NULL,
97 FOREIGN KEY(suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE
98 );
99
100 CREATE TABLE wikipedia_custom_details(
101 suggestion_id INTEGER PRIMARY KEY REFERENCES suggestions(id) ON DELETE CASCADE,
102 icon_id TEXT NOT NULL
103 );
104
105 CREATE TABLE amo_custom_details(
106 suggestion_id INTEGER PRIMARY KEY,
107 description TEXT NOT NULL,
108 guid TEXT NOT NULL,
109 icon_url TEXT NOT NULL,
110 rating TEXT,
111 number_of_ratings INTEGER NOT NULL,
112 FOREIGN KEY(suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE
113 );
114
115 CREATE TABLE fakespot_custom_details(
116 suggestion_id INTEGER PRIMARY KEY,
117 fakespot_grade TEXT NOT NULL,
118 product_id TEXT NOT NULL,
119 keywords TEXT NOT NULL,
120 product_type TEXT NOT NULL,
121 rating REAL NOT NULL,
122 total_reviews INTEGER NOT NULL,
123 icon_id TEXT,
124 FOREIGN KEY(suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE
125 );
126
127 CREATE VIRTUAL TABLE IF NOT EXISTS fakespot_fts USING FTS5(
128 title,
129 content='',
130 contentless_delete=1,
131 tokenize=\"porter unicode61 remove_diacritics 2 tokenchars '''-'\"
132 );
133
134 CREATE TRIGGER fakespot_ai AFTER INSERT ON fakespot_custom_details BEGIN
135 INSERT INTO fakespot_fts(rowid, title)
136 SELECT id, title
137 FROM suggestions
138 WHERE id = new.suggestion_id;
139 END;
140
141 CREATE VIRTUAL TABLE IF NOT EXISTS amp_fts USING FTS5(
142 full_keywords,
143 title,
144 content='',
145 contentless_delete=1,
146 tokenize=\"porter unicode61 remove_diacritics 2 tokenchars '''-'\"
147 );
148
149 -- DELETE/UPDATE triggers are difficult to implement, since the FTS contents are split between the fakespot_custom_details and suggestions tables.
150 -- If you use an AFTER trigger, then the data from the other table has already been deleted.
151 -- BEFORE triggers are discouraged by the SQLite docs.
152 -- Instead, the drop_suggestions function handles updating the FTS data.
153
154 CREATE INDEX suggestions_record_id ON suggestions(record_id);
155
156 CREATE TABLE icons(
157 id TEXT PRIMARY KEY,
158 data BLOB NOT NULL,
159 mimetype TEXT NOT NULL
160 ) WITHOUT ROWID;
161
162 CREATE TABLE yelp_subjects(
163 keyword TEXT PRIMARY KEY,
164 subject_type INTEGER NOT NULL DEFAULT 0,
165 record_id TEXT NOT NULL
166 ) WITHOUT ROWID;
167
168 CREATE TABLE yelp_modifiers(
169 type INTEGER NOT NULL,
170 keyword TEXT NOT NULL,
171 record_id TEXT NOT NULL,
172 PRIMARY KEY (type, keyword)
173 ) WITHOUT ROWID;
174
175 CREATE TABLE yelp_custom_details(
176 icon_id TEXT PRIMARY KEY,
177 score REAL NOT NULL,
178 record_id TEXT NOT NULL
179 ) WITHOUT ROWID;
180
181 CREATE TABLE mdn_custom_details(
182 suggestion_id INTEGER PRIMARY KEY,
183 description TEXT NOT NULL,
184 FOREIGN KEY(suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE
185 );
186
187 CREATE TABLE dynamic_custom_details(
188 suggestion_id INTEGER PRIMARY KEY,
189 suggestion_type TEXT NOT NULL,
190 json_data TEXT,
191 FOREIGN KEY(suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE
192 );
193 CREATE INDEX dynamic_custom_details_suggestion_type ON dynamic_custom_details(suggestion_type);
194
195 CREATE TABLE geonames(
196 id INTEGER PRIMARY KEY,
197 record_id TEXT NOT NULL,
198 name TEXT NOT NULL,
199 feature_class TEXT NOT NULL,
200 feature_code TEXT NOT NULL,
201 country_code TEXT NOT NULL,
202 admin1_code TEXT,
203 admin2_code TEXT,
204 admin3_code TEXT,
205 admin4_code TEXT,
206 population INTEGER,
207 latitude TEXT,
208 longitude TEXT
209 );
210
211 -- `language` is a lowercase ISO 639 code: 'en', 'de', 'fr', etc. It can also be
212 -- a geonames pseudo-language like 'abbr' for abbreviations and 'iata' for
213 -- airport codes. It will be null for names derived from a geoname's primary
214 -- name (see `Geoname::name` and `Geoname::ascii_name`).
215 -- `geoname_id` is not defined as a foreign key because the main geonames
216 -- records are not guaranteed to be ingested before alternates records.
217 CREATE TABLE geonames_alternates(
218 id INTEGER PRIMARY KEY,
219 record_id TEXT NOT NULL,
220 geoname_id INTEGER NOT NULL,
221 language TEXT,
222 name TEXT NOT NULL COLLATE geonames_collate,
223 is_preferred INTEGER,
224 is_short INTEGER
225 );
226
227 CREATE INDEX geonames_alternates_geoname_id_language
228 ON geonames_alternates(geoname_id, language);
229
230 CREATE INDEX geonames_alternates_name
231 ON geonames_alternates(name);
232
233 CREATE TRIGGER geonames_alternates_delete AFTER DELETE ON geonames BEGIN
234 DELETE FROM geonames_alternates
235 WHERE geoname_id = old.id;
236 END;
237
238 CREATE TABLE geonames_metrics(
239 record_id TEXT NOT NULL PRIMARY KEY,
240 max_name_length INTEGER NOT NULL,
241 max_name_word_count INTEGER NOT NULL
242 ) WITHOUT ROWID;
243
244 -- `url` may be an opaque dismissal key rather than a URL depending on the
245 -- suggestion type.
246 CREATE TABLE dismissed_suggestions (
247 url TEXT PRIMARY KEY
248 ) WITHOUT ROWID;
249 ";
250
251 /// Initializes an SQLite connection to the Suggest database, performing
252 /// migrations as needed.
253 #[derive(Default)]
254 pub struct SuggestConnectionInitializer<'a> {
255 extensions_to_load: &'a [Sqlite3Extension],
256 }
257
258 impl<'a> SuggestConnectionInitializer<'a> {
259 pub fn new(extensions_to_load: &'a [Sqlite3Extension]) -> Self {
260 Self { extensions_to_load }
261 }
262
263 pub fn load_extensions(&self, conn: &Connection) -> open_database::Result<()> {
264 // Safety: this relies on the extensions we're loading to operate correctly, for the
265 // entry point to be correct, etc.
266 unsafe {
267 let _guard = rusqlite::LoadExtensionGuard::new(conn)?;
268 for ext in self.extensions_to_load {
269 conn.load_extension(&ext.library, ext.entry_point.as_deref())?;
270 }
271 }
272 Ok(())
273 }
274
275 fn create_custom_functions(&self, conn: &Connection) -> open_database::Result<()> {
276 conn.create_collation("geonames_collate", geonames_collate)?;
277 Ok(())
278 }
279 }
280
281 impl ConnectionInitializer for SuggestConnectionInitializer<'_> {
282 const NAME: &'static str = "suggest db";
283 const END_VERSION: u32 = VERSION;
284
285 fn prepare(&self, conn: &Connection, _db_empty: bool) -> open_database::Result<()> {
286 self.load_extensions(conn)?;
287 sql_support::setup_sqlite_defaults(conn)?;
288 conn.execute("PRAGMA foreign_keys = ON", ())?;
289 sql_support::debug_tools::define_debug_functions(conn)?;
290 self.create_custom_functions(conn)?;
291 Ok(())
292 }
293
294 fn init(&self, db: &Transaction<'_>) -> open_database::Result<()> {
295 db.execute_batch(SQL)?;
296 Ok(())
297 }
298
299 fn upgrade_from(&self, tx: &Transaction<'_>, version: u32) -> open_database::Result<()> {
300 // Custom functions are per connection. `prepare` usually handles
301 // creating them but on upgrade it's not called before this method is.
302 self.create_custom_functions(tx)?;
303
304 match version {
305 1..=15 => {
306 // Treat databases with these older schema versions as corrupt,
307 // so that they'll be replaced by a fresh, empty database with
308 // the current schema.
309 Err(open_database::Error::Corrupt)
310 }
311 16 => {
312 tx.execute(
313 "
314 CREATE TABLE dismissed_suggestions (
315 url_hash INTEGER PRIMARY KEY
316 ) WITHOUT ROWID;",
317 (),
318 )?;
319 Ok(())
320 }
321 17 => {
322 tx.execute(
323 "
324 DROP TABLE dismissed_suggestions;
325 CREATE TABLE dismissed_suggestions (
326 url TEXT PRIMARY KEY
327 ) WITHOUT ROWID;",
328 (),
329 )?;
330 Ok(())
331 }
332 18 => {
333 tx.execute_batch(
334 "
335 CREATE TABLE IF NOT EXISTS dismissed_suggestions (
336 url TEXT PRIMARY KEY
337 ) WITHOUT ROWID;",
338 )?;
339 Ok(())
340 }
341 19 => {
342 // Clear the database since we're going to be dropping the keywords table and
343 // re-creating it
344 clear_database(tx)?;
345 tx.execute_batch(
346 "
347 -- Recreate the various keywords table to drop the foreign keys.
348 DROP TABLE keywords;
349 DROP TABLE full_keywords;
350 DROP TABLE prefix_keywords;
351 CREATE TABLE keywords(
352 keyword TEXT NOT NULL,
353 suggestion_id INTEGER NOT NULL,
354 full_keyword_id INTEGER NULL,
355 rank INTEGER NOT NULL,
356 PRIMARY KEY (keyword, suggestion_id)
357 ) WITHOUT ROWID;
358 CREATE TABLE full_keywords(
359 id INTEGER PRIMARY KEY,
360 suggestion_id INTEGER NOT NULL,
361 full_keyword TEXT NOT NULL
362 );
363 CREATE TABLE prefix_keywords(
364 keyword_prefix TEXT NOT NULL,
365 keyword_suffix TEXT NOT NULL DEFAULT '',
366 confidence INTEGER NOT NULL DEFAULT 0,
367 rank INTEGER NOT NULL,
368 suggestion_id INTEGER NOT NULL,
369 PRIMARY KEY (keyword_prefix, keyword_suffix, suggestion_id)
370 ) WITHOUT ROWID;
371 CREATE UNIQUE INDEX keywords_suggestion_id_rank ON keywords(suggestion_id, rank);
372 ",
373 )?;
374 Ok(())
375 }
376
377 // Migration for the fakespot data. This is not currently active for any users, it's
378 // only used for the tests. It's safe to alter the fakespot_custom_detail schema and
379 // update this migration as the project moves forward.
380 //
381 // Note: if we want to add a regular migration while the fakespot code is still behind
382 // a feature flag, insert it before this one and make fakespot the last migration.
383 20 => {
384 tx.execute_batch(
385 "
386 CREATE TABLE fakespot_custom_details(
387 suggestion_id INTEGER PRIMARY KEY,
388 fakespot_grade TEXT NOT NULL,
389 product_id TEXT NOT NULL,
390 rating REAL NOT NULL,
391 total_reviews INTEGER NOT NULL,
392 FOREIGN KEY(suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE
393 );
394 -- Create the Fakespot FTS table.
395 -- The `tokenize` param is hard to read. The effect is that dashes and apostrophes are
396 -- considered valid tokens in a word, rather than separators.
397 CREATE VIRTUAL TABLE IF NOT EXISTS fakespot_fts USING FTS5(
398 title,
399 prefix='4 5 6 7 8 9 10 11',
400 content='',
401 contentless_delete=1,
402 tokenize=\"porter unicode61 remove_diacritics 2 tokenchars '''-'\"
403 );
404 CREATE TRIGGER fakespot_ai AFTER INSERT ON fakespot_custom_details BEGIN
405 INSERT INTO fakespot_fts(rowid, title)
406 SELECT id, title
407 FROM suggestions
408 WHERE id = new.suggestion_id;
409 END;
410 ",
411 )?;
412 Ok(())
413 }
414 21 => {
415 // Drop and re-create the fakespot_custom_details to add the icon_id column.
416 tx.execute_batch(
417 "
418 DROP TABLE fakespot_custom_details;
419 CREATE TABLE fakespot_custom_details(
420 suggestion_id INTEGER PRIMARY KEY,
421 fakespot_grade TEXT NOT NULL,
422 product_id TEXT NOT NULL,
423 rating REAL NOT NULL,
424 total_reviews INTEGER NOT NULL,
425 icon_id TEXT,
426 FOREIGN KEY(suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE
427 );
428 CREATE TRIGGER fakespot_ai AFTER INSERT ON fakespot_custom_details BEGIN
429 INSERT INTO fakespot_fts(rowid, title)
430 SELECT id, title
431 FROM suggestions
432 WHERE id = new.suggestion_id;
433 END;
434 ",
435 )?;
436 Ok(())
437 }
438 22 => {
439 // Drop and re-create the fakespot_fts table to remove the prefix index param
440 tx.execute_batch(
441 "
442 DROP TABLE fakespot_fts;
443 CREATE VIRTUAL TABLE fakespot_fts USING FTS5(
444 title,
445 content='',
446 contentless_delete=1,
447 tokenize=\"porter unicode61 remove_diacritics 2 tokenchars '''-'\"
448 );
449 ",
450 )?;
451 Ok(())
452 }
453 23 => {
454 // Drop all suggestions, then recreate the fakespot_custom_details table to add the
455 // `keywords` and `product_type` fields.
456 clear_database(tx)?;
457 tx.execute_batch(
458 "
459 DROP TABLE fakespot_custom_details;
460 CREATE TABLE fakespot_custom_details(
461 suggestion_id INTEGER PRIMARY KEY,
462 fakespot_grade TEXT NOT NULL,
463 product_id TEXT NOT NULL,
464 keywords TEXT NOT NULL,
465 product_type TEXT NOT NULL,
466 rating REAL NOT NULL,
467 total_reviews INTEGER NOT NULL,
468 icon_id TEXT,
469 FOREIGN KEY(suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE
470 );
471 CREATE TRIGGER fakespot_ai AFTER INSERT ON fakespot_custom_details BEGIN
472 INSERT INTO fakespot_fts(rowid, title)
473 SELECT id, title
474 FROM suggestions
475 WHERE id = new.suggestion_id;
476 END;
477 ",
478 )?;
479 Ok(())
480 }
481 24 => {
482 // Clear the database so that we re-ingest and populate the ingested_records table.
483 clear_database(tx)?;
484 tx.execute_batch(
485 "
486 CREATE TABLE rs_cache(
487 collection TEXT PRIMARY KEY,
488 data TEXT NOT NULL
489 ) WITHOUT ROWID;
490 CREATE TABLE ingested_records(
491 id TEXT,
492 collection TEXT,
493 type TEXT NOT NULL,
494 last_modified INTEGER NOT NULL,
495 PRIMARY KEY (id, collection)
496 ) WITHOUT ROWID;
497 ",
498 )?;
499 Ok(())
500 }
501 25 => {
502 // Create the exposure suggestions table and index.
503 tx.execute_batch(
504 "
505 CREATE TABLE exposure_custom_details(
506 suggestion_id INTEGER PRIMARY KEY,
507 type TEXT NOT NULL,
508 FOREIGN KEY(suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE
509 );
510 CREATE INDEX exposure_custom_details_type ON exposure_custom_details(type);
511 ",
512 )?;
513 Ok(())
514 }
515 26 => {
516 // Create tables related to city-based weather.
517 tx.execute_batch(
518 "
519 CREATE TABLE keywords_metrics(
520 record_id TEXT NOT NULL PRIMARY KEY,
521 provider INTEGER NOT NULL,
522 max_length INTEGER NOT NULL,
523 max_word_count INTEGER NOT NULL
524 ) WITHOUT ROWID;
525
526 CREATE TABLE geonames(
527 id INTEGER PRIMARY KEY,
528 record_id TEXT NOT NULL,
529 name TEXT NOT NULL,
530 feature_class TEXT NOT NULL,
531 feature_code TEXT NOT NULL,
532 country_code TEXT NOT NULL,
533 admin1_code TEXT NOT NULL,
534 population INTEGER
535 );
536 CREATE INDEX geonames_feature_class ON geonames(feature_class);
537 CREATE INDEX geonames_feature_code ON geonames(feature_code);
538
539 CREATE TABLE geonames_alternates(
540 name TEXT NOT NULL,
541 geoname_id INTEGER NOT NULL,
542 PRIMARY KEY (name, geoname_id),
543 FOREIGN KEY(geoname_id) REFERENCES geonames(id) ON DELETE CASCADE
544 ) WITHOUT ROWID;
545
546 CREATE TABLE geonames_metrics(
547 record_id TEXT NOT NULL PRIMARY KEY,
548 max_name_length INTEGER NOT NULL,
549 max_name_word_count INTEGER NOT NULL
550 ) WITHOUT ROWID;
551 ",
552 )?;
553 Ok(())
554 }
555 27 => {
556 // Add latitude and longitude to the geonames table. Clear the
557 // database so geonames are reingested.
558 clear_database(tx)?;
559 tx.execute_batch(
560 "
561 DROP INDEX geonames_feature_class;
562 DROP INDEX geonames_feature_code;
563 DROP TABLE geonames;
564 CREATE TABLE geonames(
565 id INTEGER PRIMARY KEY,
566 record_id TEXT NOT NULL,
567 name TEXT NOT NULL,
568 latitude REAL NOT NULL,
569 longitude REAL NOT NULL,
570 feature_class TEXT NOT NULL,
571 feature_code TEXT NOT NULL,
572 country_code TEXT NOT NULL,
573 admin1_code TEXT NOT NULL,
574 population INTEGER NOT NULL
575 );
576 CREATE INDEX geonames_feature_class ON geonames(feature_class);
577 CREATE INDEX geonames_feature_code ON geonames(feature_code);
578 ",
579 )?;
580 Ok(())
581 }
582 28 => {
583 // Add `iso_language` column to `geonames_alternates`. Clear the
584 // database so geonames are reingested.
585 clear_database(tx)?;
586 tx.execute_batch(
587 "
588 DROP TABLE geonames_alternates;
589 CREATE TABLE geonames_alternates(
590 name TEXT NOT NULL,
591 geoname_id INTEGER NOT NULL,
592 -- The value of the `iso_language` field for the alternate. This will be
593 -- null for the alternate we artificially create for the `name` in the
594 -- corresponding geoname record.
595 iso_language TEXT,
596 PRIMARY KEY (name, geoname_id),
597 FOREIGN KEY(geoname_id) REFERENCES geonames(id) ON DELETE CASCADE
598 ) WITHOUT ROWID;
599 ",
600 )?;
601 Ok(())
602 }
603 29 => {
604 // This migration only clears the database because some tables
605 // that should have been cleared in previous migrations were
606 // not.
607 clear_database(tx)?;
608 Ok(())
609 }
610 30 => {
611 // Add the `geonames_alternates_geoname_id` index.
612 clear_database(tx)?;
613 tx.execute_batch(
614 "
615 CREATE INDEX geonames_alternates_geoname_id ON geonames_alternates(geoname_id);
616 ",
617 )?;
618 Ok(())
619 }
620 31 => {
621 // Need to clear the database so that the FTS index will get filled.
622 clear_database(tx)?;
623 tx.execute_batch(
624 "
625 CREATE VIRTUAL TABLE IF NOT EXISTS amp_fts USING FTS5(
626 full_keywords,
627 title,
628 content='',
629 contentless_delete=1,
630 tokenize=\"porter unicode61 remove_diacritics 2 tokenchars '''-'\"
631 );
632
633 ",
634 )?;
635 Ok(())
636 }
637 32 => {
638 // Drop rs_cache since it's no longer needed.
639 tx.execute_batch("DROP TABLE rs_cache;")?;
640 Ok(())
641 }
642 33 => {
643 // This migration is due to the replacement of the
644 // `quicksuggest` collection with `quicksuggest-amp` and
645 // `quicksuggest-other`. Clear the DB so that records from the
646 // old collection don't stick around. See bug 1953945.
647 clear_database(tx)?;
648 Ok(())
649 }
650 34 => {
651 // Replace the exposure suggestions table and index with the
652 // dynamic suggestions table and index.
653 tx.execute_batch(
654 r#"
655 DROP INDEX exposure_custom_details_type;
656 DROP TABLE exposure_custom_details;
657 CREATE TABLE dynamic_custom_details(
658 suggestion_id INTEGER PRIMARY KEY,
659 suggestion_type TEXT NOT NULL,
660 json_data TEXT,
661 FOREIGN KEY(suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE
662 );
663 CREATE INDEX dynamic_custom_details_suggestion_type ON dynamic_custom_details(suggestion_type);
664 "#,
665 )?;
666 Ok(())
667 }
668 35 => {
669 // The commit that added this migration was reverted.
670 Ok(())
671 }
672 36 => {
673 tx.execute_batch("DROP TABLE IF EXISTS yelp_location_signs;")?;
674 Ok(())
675 }
676 37 => {
677 clear_database(tx)?;
678 tx.execute_batch(
679 "
680 DROP TABLE yelp_subjects;
681 CREATE TABLE yelp_subjects(
682 keyword TEXT PRIMARY KEY,
683 subject_type INTEGER NOT NULL DEFAULT 0,
684 record_id TEXT NOT NULL
685 ) WITHOUT ROWID;
686 ",
687 )?;
688 Ok(())
689 }
690 38 => {
691 // This migration makes changes to geonames.
692 tx.execute_batch(
693 r#"
694 DROP INDEX geonames_alternates_geoname_id;
695 DROP TABLE geonames_alternates;
696
697 DROP INDEX geonames_feature_class;
698 DROP INDEX geonames_feature_code;
699 DROP TABLE geonames;
700
701 CREATE TABLE geonames(
702 id INTEGER PRIMARY KEY,
703 record_id TEXT NOT NULL,
704 name TEXT NOT NULL,
705 feature_class TEXT NOT NULL,
706 feature_code TEXT NOT NULL,
707 country_code TEXT NOT NULL,
708 admin1_code TEXT,
709 admin2_code TEXT,
710 admin3_code TEXT,
711 admin4_code TEXT,
712 population INTEGER,
713 latitude TEXT,
714 longitude TEXT
715 );
716
717 CREATE TABLE geonames_alternates(
718 record_id TEXT NOT NULL,
719 geoname_id INTEGER NOT NULL,
720 language TEXT,
721 name TEXT NOT NULL COLLATE geonames_collate,
722 PRIMARY KEY(geoname_id, language, name)
723 );
724 CREATE INDEX geonames_alternates_geoname_id ON geonames_alternates(geoname_id);
725 CREATE INDEX geonames_alternates_name ON geonames_alternates(name);
726
727 CREATE TRIGGER geonames_alternates_delete AFTER DELETE ON geonames BEGIN
728 DELETE FROM geonames_alternates
729 WHERE geoname_id = old.id;
730 END;
731 "#,
732 )?;
733 Ok(())
734 }
735 39 => {
736 // This migration makes changes to keywords metrics.
737 clear_database(tx)?;
738 tx.execute_batch(
739 r#"
740 DROP TABLE keywords_metrics;
741 CREATE TABLE keywords_metrics(
742 record_id TEXT NOT NULL PRIMARY KEY,
743 record_type TEXT NOT NULL,
744 max_len INTEGER NOT NULL,
745 max_word_count INTEGER NOT NULL
746 ) WITHOUT ROWID;
747 CREATE INDEX keywords_metrics_record_type ON keywords_metrics(record_type);
748 "#,
749 )?;
750 Ok(())
751 }
752 40 => {
753 // This migration makes changes to geonames.
754 clear_database(tx)?;
755 tx.execute_batch(
756 r#"
757 DROP INDEX geonames_alternates_geoname_id;
758 DROP INDEX geonames_alternates_name;
759 DROP TABLE geonames_alternates;
760
761 CREATE TABLE geonames_alternates(
762 id INTEGER PRIMARY KEY,
763 record_id TEXT NOT NULL,
764 geoname_id INTEGER NOT NULL,
765 language TEXT,
766 name TEXT NOT NULL COLLATE geonames_collate,
767 is_preferred INTEGER,
768 is_short INTEGER
769 );
770 CREATE INDEX geonames_alternates_geoname_id_language
771 ON geonames_alternates(geoname_id, language);
772 CREATE INDEX geonames_alternates_name
773 ON geonames_alternates(name);
774 "#,
775 )?;
776 Ok(())
777 }
778 _ => Err(open_database::Error::IncompatibleVersion(version)),
779 }
780 }
781 }
782
783 /// Clears the database, removing all suggestions, icons, and metadata.
784 pub fn clear_database(db: &Connection) -> rusqlite::Result<()> {
785 db.execute_batch(
786 "
787 DELETE FROM meta;
788 DELETE FROM keywords;
789 DELETE FROM full_keywords;
790 DELETE FROM prefix_keywords;
791 DELETE FROM suggestions;
792 DELETE FROM icons;
793 DELETE FROM yelp_subjects;
794 DELETE FROM yelp_modifiers;
795 DELETE FROM yelp_custom_details;
796 ",
797 )?;
798 let conditional_tables = [
799 "fakespot_fts",
800 "geonames",
801 "geonames_metrics",
802 "ingested_records",
803 "keywords_metrics",
804 ];
805 for t in conditional_tables {
806 let table_exists = db.exists("SELECT 1 FROM sqlite_master WHERE name = ?", [t])?;
807 if table_exists {
808 db.execute(&format!("DELETE FROM {t}"), ())?;
809 }
810 }
811 Ok(())
812 }
813
814 #[cfg(test)]
815 mod test {
816 use super::*;
817 use sql_support::open_database::test_utils::MigratedDatabaseFile;
818
819 // Snapshot of the v16 schema. We use this to test that we can migrate from there to the
820 // current schema.
821 const V16_SCHEMA: &str = r#"
822 CREATE TABLE meta(
823 key TEXT PRIMARY KEY,
824 value NOT NULL
825 ) WITHOUT ROWID;
826
827 CREATE TABLE keywords(
828 keyword TEXT NOT NULL,
829 suggestion_id INTEGER NOT NULL REFERENCES suggestions(id) ON DELETE CASCADE,
830 full_keyword_id INTEGER NULL REFERENCES full_keywords(id) ON DELETE SET NULL,
831 rank INTEGER NOT NULL,
832 PRIMARY KEY (keyword, suggestion_id)
833 ) WITHOUT ROWID;
834
835 -- full keywords are what we display to the user when a (partial) keyword matches
836 -- The FK to suggestion_id makes it so full keywords get deleted when the parent suggestion is deleted.
837 CREATE TABLE full_keywords(
838 id INTEGER PRIMARY KEY,
839 suggestion_id INTEGER NOT NULL REFERENCES suggestions(id) ON DELETE CASCADE,
840 full_keyword TEXT NOT NULL
841 );
842
843 CREATE TABLE prefix_keywords(
844 keyword_prefix TEXT NOT NULL,
845 keyword_suffix TEXT NOT NULL DEFAULT '',
846 confidence INTEGER NOT NULL DEFAULT 0,
847 rank INTEGER NOT NULL,
848 suggestion_id INTEGER NOT NULL REFERENCES suggestions(id) ON DELETE CASCADE,
849 PRIMARY KEY (keyword_prefix, keyword_suffix, suggestion_id)
850 ) WITHOUT ROWID;
851
852 CREATE UNIQUE INDEX keywords_suggestion_id_rank ON keywords(suggestion_id, rank);
853
854 CREATE TABLE suggestions(
855 id INTEGER PRIMARY KEY,
856 record_id TEXT NOT NULL,
857 provider INTEGER NOT NULL,
858 title TEXT NOT NULL,
859 url TEXT NOT NULL,
860 score REAL NOT NULL
861 );
862
863 CREATE TABLE amp_custom_details(
864 suggestion_id INTEGER PRIMARY KEY,
865 advertiser TEXT NOT NULL,
866 block_id INTEGER NOT NULL,
867 iab_category TEXT NOT NULL,
868 impression_url TEXT NOT NULL,
869 click_url TEXT NOT NULL,
870 icon_id TEXT NOT NULL,
871 FOREIGN KEY(suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE
872 );
873
874 CREATE TABLE wikipedia_custom_details(
875 suggestion_id INTEGER PRIMARY KEY REFERENCES suggestions(id) ON DELETE CASCADE,
876 icon_id TEXT NOT NULL
877 );
878
879 CREATE TABLE amo_custom_details(
880 suggestion_id INTEGER PRIMARY KEY,
881 description TEXT NOT NULL,
882 guid TEXT NOT NULL,
883 icon_url TEXT NOT NULL,
884 rating TEXT,
885 number_of_ratings INTEGER NOT NULL,
886 FOREIGN KEY(suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE
887 );
888
889 CREATE INDEX suggestions_record_id ON suggestions(record_id);
890
891 CREATE TABLE icons(
892 id TEXT PRIMARY KEY,
893 data BLOB NOT NULL,
894 mimetype TEXT NOT NULL
895 ) WITHOUT ROWID;
896
897 CREATE TABLE yelp_subjects(
898 keyword TEXT PRIMARY KEY,
899 record_id TEXT NOT NULL
900 ) WITHOUT ROWID;
901
902 CREATE TABLE yelp_modifiers(
903 type INTEGER NOT NULL,
904 keyword TEXT NOT NULL,
905 record_id TEXT NOT NULL,
906 PRIMARY KEY (type, keyword)
907 ) WITHOUT ROWID;
908
909 CREATE TABLE yelp_location_signs(
910 keyword TEXT PRIMARY KEY,
911 need_location INTEGER NOT NULL,
912 record_id TEXT NOT NULL
913 ) WITHOUT ROWID;
914
915 CREATE TABLE yelp_custom_details(
916 icon_id TEXT PRIMARY KEY,
917 score REAL NOT NULL,
918 record_id TEXT NOT NULL
919 ) WITHOUT ROWID;
920
921 CREATE TABLE mdn_custom_details(
922 suggestion_id INTEGER PRIMARY KEY,
923 description TEXT NOT NULL,
924 FOREIGN KEY(suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE
925 );
926
927 PRAGMA user_version=16;
928 "#;
929
930 /// Test running all schema upgrades from V16, which was the first schema with a "real"
931 /// migration.
932 ///
933 /// If an upgrade fails, then this test will fail with a panic.
934 #[test]
935 fn test_all_upgrades() {
936 let db_file =
937 MigratedDatabaseFile::new(SuggestConnectionInitializer::default(), V16_SCHEMA);
938 db_file.run_all_upgrades();
939 db_file.assert_schema_matches_new_database();
940 }
941
942 /// Test that `clear_database()` works correctly during migrations.
943 ///
944 /// TODO: This only checks `ingested_records` and `rs_cache` for now since
945 /// they're very important, but ideally this would test all tables.
946 #[test]
947 fn test_clear_database() -> anyhow::Result<()> {
948 // Start with the v16 schema.
949 let db_file =
950 MigratedDatabaseFile::new(SuggestConnectionInitializer::default(), V16_SCHEMA);
951
952 // Upgrade to v25, the first version with with `ingested_records` tables.
953 db_file.upgrade_to(25);
954
955 // Insert some ingested records.
956 let conn = db_file.open();
957 conn.execute(
958 "INSERT INTO ingested_records(id, collection, type, last_modified) VALUES(?, ?, ?, ?)",
959 ("record-id", "quicksuggest", "record-type", 1),
960 )?;
961 conn.close().expect("Connection should be closed");
962
963 // Finish upgrading to the current version.
964 db_file.upgrade_to(VERSION);
965 db_file.assert_schema_matches_new_database();
966
967 // `ingested_records` should be empty.
968 let conn = db_file.open();
969 assert_eq!(
970 conn.query_one::<i32>("SELECT count(*) FROM ingested_records")?,
971 0,
972 "ingested_records should be empty"
973 );
974 conn.close().expect("Connection should be closed");
975
976 Ok(())
977 }
978
979 /// Test that yelp_location_signs table could be removed correctly.
980 #[test]
981 fn test_remove_yelp_location_signs_table() -> anyhow::Result<()> {
982 // Start with the v16 schema.
983 let db_file =
984 MigratedDatabaseFile::new(SuggestConnectionInitializer::default(), V16_SCHEMA);
985
986 // Upgrade to v36.
987 db_file.upgrade_to(36);
988
989 // Drop the table to simulate old 35 > 36 migration.
990 let conn = db_file.open();
991 conn.execute("DROP table yelp_location_signs", ())?;
992 conn.close().expect("Connection should be closed");
993
994 // Finish upgrading to the current version.
995 db_file.upgrade_to(VERSION);
996 db_file.assert_schema_matches_new_database();
997
998 Ok(())
999 }
1000 }