Debian Codegraph @

third_party/rust/suggest/src/geoname.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 /// GeoNames support. GeoNames is an open-source geographical database of place
7 /// names worldwide, including cities, regions, and countries [1]. Notably it's
8 /// used by MaxMind's databases [2]. We use GeoNames to detect city and region
9 /// names and to map cities to regions. Specifically we use the data at [3];
10 /// also see [3] for documentation.
11 ///
12 /// [1]: https://www.geonames.org/
13 /// [2]: https://www.maxmind.com/en/geoip-databases
14 /// [3]: https://download.geonames.org/export/dump/
15 use rusqlite::{named_params, Connection};
16 use serde::Deserialize;
17 use sql_support::ConnExt;
18 use std::{
19 borrow::Cow,
20 cell::OnceCell,
21 collections::HashMap,
22 hash::{Hash, Hasher},
23 };
24 use unicase::UniCase;
25 use unicode_normalization::{char::is_combining_mark, UnicodeNormalization};
26
27 use crate::{
28 db::{KeywordsMetrics, KeywordsMetricsUpdater, SuggestDao},
29 error::RusqliteResultExt,
30 metrics::MetricsContext,
31 rs::{Client, Record, SuggestRecordId, SuggestRecordType},
32 store::SuggestStoreInner,
33 Result,
34 };
35
36 /// The type of a geoname.
37 #[derive(Clone, Debug, Eq, Hash, PartialEq, uniffi::Enum)]
38 pub enum GeonameType {
39 Country,
40 /// A state, province, prefecture, district, borough, etc.
41 AdminDivision {
42 level: u8,
43 },
44 AdminDivisionOther,
45 /// A city, town, village, populated place, etc.
46 City,
47 Other,
48 }
49
50 pub type GeonameId = i64;
51
52 /// A single geographic place.
53 ///
54 /// This corresponds to a single row in the main "geoname" table described in
55 /// the GeoNames documentation [1]. We exclude fields we don't need.
56 ///
57 /// [1]: https://download.geonames.org/export/dump/readme.txt
58 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)]
59 pub struct Geoname {
60 /// The `geonameid` straight from the geoname table.
61 pub geoname_id: GeonameId,
62 /// The geoname type. This is derived from `feature_class` and
63 /// `feature_code` as a more convenient representation of the type.
64 pub geoname_type: GeonameType,
65 /// The place's primary name.
66 pub name: String,
67 /// ISO-3166 two-letter uppercase country code, e.g., "US".
68 pub country_code: String,
69 /// Primary geoname category. Examples:
70 ///
71 /// "PCLI" - Independent political entity: country
72 /// "A" - Administrative division: state, province, borough, district, etc.
73 /// "P" - Populated place: city, village, etc.
74 pub feature_class: String,
75 /// Secondary geoname category, depends on `feature_class`. Examples:
76 ///
77 /// "ADM1" - Administrative division 1
78 /// "PPL" - Populated place like a city
79 pub feature_code: String,
80 /// Administrative divisions. This maps admin division levels (1-based) to
81 /// their corresponding codes. For example, Liverpool has two admin
82 /// divisions: "ENG" at level 1 and "H8" at level 2. They would be
83 /// represented in this map with entries `(1, "ENG")` and `(2, "H8")`.
84 pub admin_division_codes: HashMap<u8, String>,
85 /// Population size.
86 pub population: u64,
87 /// Latitude in decimal degrees (as a string).
88 pub latitude: String,
89 /// Longitude in decimal degrees (as a string).
90 pub longitude: String,
91 }
92
93 /// Alternate names for a geoname and its country and admin divisions.
94 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)]
95 pub struct GeonameAlternates {
96 /// Names for the geoname itself.
97 geoname: AlternateNames,
98 /// Names for the geoname's country. This will be `Some` as long as the
99 /// country is also in the ingested data, which should typically be true.
100 country: Option<AlternateNames>,
101 /// Names for the geoname's admin divisions. This is parallel to
102 /// `Geoname::admin_division_codes`. If there are no names in the ingested
103 /// data for an admin division, then it will be absent from this map.
104 admin_divisions: HashMap<u8, AlternateNames>,
105 }
106
107 /// A set of names for a single entity.
108 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)]
109 pub struct AlternateNames {
110 /// The entity's primary name. For a `Geoname`, this is `Geoname::name`.
111 primary: String,
112 /// The entity's name in the language that was ingested according to the
113 /// locale in the remote settings context. If none exists and this
114 /// `AlternateNames` is for a `Geoname`, then this will be its primary name.
115 localized: Option<String>,
116 /// The entity's abbreviation, if any.
117 abbreviation: Option<String>,
118 }
119
120 impl Geoname {
121 /// Whether `self` and `other` are related. For example, if one is a city
122 /// and the other is an administrative division, this will return `true` if
123 /// the city is located in the division.
124 pub fn is_related_to(&self, other: &Self) -> bool {
125 if self.country_code != other.country_code {
126 return false;
127 }
128
129 let self_level = self.admin_level();
130 let other_level = other.admin_level();
131
132 // Build a sorted vec of levels in both `self and `other`.
133 let mut levels_asc: Vec<_> = self
134 .admin_division_codes
135 .keys()
136 .chain(other.admin_division_codes.keys())
137 .copied()
138 .collect();
139 levels_asc.sort();
140
141 // Each admin level needs to be the same in `self` and `other` up to the
142 // minimum level of `self` and `other`.
143 for level in levels_asc {
144 if self_level < level || other_level < level {
145 break;
146 }
147 if self.admin_division_codes.get(&level) != other.admin_division_codes.get(&level) {
148 return false;
149 }
150 }
151
152 // At this point, admin levels are the same up to the minimum level. If
153 // the types of `self` and `other` aren't the same, then one is an admin
154 // division of the other. If they are the same type, then they need to
155 // be the same geoname.
156 self.geoname_type != other.geoname_type || self.geoname_id == other.geoname_id
157 }
158
159 fn admin_level(&self) -> u8 {
160 match self.geoname_type {
161 GeonameType::Country => 0,
162 GeonameType::AdminDivision { level } => level,
163 _ => 4,
164 }
165 }
166 }
167
168 impl Hash for Geoname {
169 fn hash<H: Hasher>(&self, state: &mut H) {
170 self.geoname_id.hash(state)
171 }
172 }
173
174 /// A fetched geoname with info on how it was matched.
175 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)]
176 pub struct GeonameMatch {
177 /// The geoname that was matched.
178 pub geoname: Geoname,
179 /// The type of name that was matched.
180 pub match_type: GeonameMatchType,
181 /// Whether the name was matched by prefix.
182 pub prefix: bool,
183 }
184
185 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Enum)]
186 pub enum GeonameMatchType {
187 Abbreviation,
188 AirportCode,
189 /// This includes any names that aren't abbreviations or airport codes.
190 Name,
191 }
192
193 impl GeonameMatchType {
194 pub fn is_abbreviation(&self) -> bool {
195 matches!(self, GeonameMatchType::Abbreviation)
196 }
197
198 pub fn is_airport_code(&self) -> bool {
199 matches!(self, GeonameMatchType::AirportCode)
200 }
201
202 pub fn is_name(&self) -> bool {
203 matches!(self, GeonameMatchType::Name)
204 }
205 }
206
207 /// This data is used to service every query handled by the weather provider and
208 /// potentially other providers, so we cache it from the DB.
209 #[derive(Debug, Default)]
210 pub struct GeonameCache {
211 pub keywords_metrics: KeywordsMetrics,
212 }
213
214 /// See `Geoname` for documentation.
215 #[derive(Clone, Debug, Deserialize)]
216 struct DownloadedGeoname {
217 id: GeonameId,
218 name: String,
219 ascii_name: Option<String>,
220 feature_class: String,
221 feature_code: String,
222 country: String,
223 admin1: Option<String>,
224 admin2: Option<String>,
225 admin3: Option<String>,
226 admin4: Option<String>,
227 population: Option<u64>,
228 latitude: Option<String>,
229 longitude: Option<String>,
230 }
231
232 #[derive(Clone, Debug, Deserialize)]
233 struct DownloadedGeonamesAlternatesAttachment {
234 /// The language of the names in this attachment as a lowercase ISO 639
235 /// code: "en", "de", "fr", etc. Can also be a geonames pseduo-language like
236 /// "abbr" for abbreviations and "iata" for airport codes.
237 language: String,
238 /// Tuples of geoname IDs and their alternate names.
239 alternates_by_geoname_id: Vec<(GeonameId, Vec<DownloadedGeonamesAlternate<String>>)>,
240 }
241
242 #[derive(Clone, Debug, Deserialize)]
243 #[serde(untagged)]
244 enum DownloadedGeonamesAlternate<S: AsRef<str>> {
245 Name(S),
246 Full {
247 name: S,
248 is_preferred: Option<bool>,
249 is_short: Option<bool>,
250 },
251 }
252
253 impl<S: AsRef<str>> DownloadedGeonamesAlternate<S> {
254 fn name(&self) -> &str {
255 match self {
256 Self::Name(name) => name.as_ref(),
257 Self::Full { name, .. } => name.as_ref(),
258 }
259 }
260
261 fn is_preferred(&self) -> bool {
262 match self {
263 Self::Name(_) => false,
264 Self::Full { is_preferred, .. } => is_preferred.unwrap_or(false),
265 }
266 }
267
268 fn is_short(&self) -> bool {
269 match self {
270 Self::Name(_) => false,
271 Self::Full { is_short, .. } => is_short.unwrap_or(false),
272 }
273 }
274 }
275
276 /// Compares two strings ignoring case, Unicode combining marks, and some
277 /// punctuation. Intended to be used as a Sqlite collating sequence for
278 /// comparing geoname names.
279 pub fn geonames_collate(a: &str, b: &str) -> std::cmp::Ordering {
280 UniCase::new(collate_remove_chars(a)).cmp(&UniCase::new(collate_remove_chars(b)))
281 }
282
283 fn collate_remove_chars(s: &str) -> Cow<'_, str> {
284 let borrowable = !s
285 .nfkd()
286 .any(|c| is_combining_mark(c) || matches!(c, '.' | ',' | '-'));
287
288 if borrowable {
289 Cow::from(s)
290 } else {
291 s.nfkd()
292 .filter_map(|c| {
293 if is_combining_mark(c) {
294 // Remove Unicode combining marks:
295 // "Que\u{0301}bec" => "Quebec"
296 None
297 } else {
298 match c {
299 // Remove '.' and ',':
300 // "St. Louis, U.S.A." => "St Louis USA"
301 '.' | ',' => None,
302 // Replace '-' with space:
303 // "Carmel-by-the-Sea" => "Carmel by the Sea"
304 '-' => Some(' '),
305 _ => Some(c),
306 }
307 }
308 })
309 .collect::<_>()
310 }
311 }
312
313 impl SuggestDao<'_> {
314 /// Fetches geonames that have at least one name matching the `query`
315 /// string.
316 ///
317 /// `match_name_prefix` determines whether prefix matching is performed on
318 /// names that aren't abbreviations and airport codes. When `true`, names
319 /// that start with `query` will match. When false, names that equal `query`
320 /// will match. Prefix matching is never performed on abbreviations and
321 /// airport codes because we don't currently have a use case for that.
322 ///
323 /// `filter` restricts returned geonames to those that are related to the
324 /// ones in the filter. Cities can be restricted to administrative divisions
325 /// by including the divisions in `filter` and vice versa. This is
326 /// especially useful since place names are not unique. `filter` is
327 /// conjunctive: All geonames in `filter` must be related to a geoname in
328 /// order for it to be filtered in.
329 ///
330 /// The returned matches will include all matching types for a geoname, one
331 /// match per type per geoname. For example, if the query matches both a
332 /// geoname's name and abbreviation, two matches for that geoname will be
333 /// returned: one with a `match_type` of `GeonameMatchType::Name` and one
334 /// with a `match_type` of `GeonameMatchType::Abbreviation`. `prefix` is set
335 /// according to whether the query matched a prefix of the given type.
336 pub fn fetch_geonames(
337 &self,
338 query: &str,
339 match_name_prefix: bool,
340 filter: Option<Vec<&Geoname>>,
341 ) -> Result<Vec<GeonameMatch>> {
342 let candidate_name = query;
343 Ok(self
344 .conn
345 .query_rows_and_then_cached(
346 r#"
347 SELECT
348 g.id,
349 g.name,
350 g.feature_class,
351 g.feature_code,
352 g.country_code,
353 g.admin1_code,
354 g.admin2_code,
355 g.admin3_code,
356 g.admin4_code,
357 g.population,
358 g.latitude,
359 g.longitude,
360 a.name != :name AS prefix,
361 (SELECT CASE
362 -- abbreviation
363 WHEN a.language = 'abbr' THEN 1
364 -- airport code
365 WHEN a.language IN ('iata', 'icao', 'faac') THEN 2
366 -- name
367 ELSE 3
368 END
369 ) AS match_type
370 FROM
371 geonames g
372 JOIN
373 geonames_alternates a ON g.id = a.geoname_id
374 WHERE
375 a.name = :name
376 OR (
377 :prefix
378 AND match_type = 3
379 AND (a.name BETWEEN :name AND :name || X'FFFF')
380 )
381 GROUP BY
382 g.id, match_type
383 ORDER BY
384 g.feature_class = 'P' DESC, g.population DESC, g.id ASC, a.language ASC
385 "#,
386 named_params! {
387 ":name": candidate_name,
388 ":prefix": match_name_prefix,
389 },
390 |row| -> Result<Option<GeonameMatch>> {
391 let feature_class: String = row.get("feature_class")?;
392 let feature_code: String = row.get("feature_code")?;
393 let geoname_type = match feature_class.as_str() {
394 "A" => {
395 if feature_code.starts_with("P") {
396 GeonameType::Country
397 } else {
398 match feature_code.as_str() {
399 "ADM1" => GeonameType::AdminDivision { level: 1 },
400 "ADM2" => GeonameType::AdminDivision { level: 2 },
401 "ADM3" => GeonameType::AdminDivision { level: 3 },
402 "ADM4" => GeonameType::AdminDivision { level: 4 },
403 _ => GeonameType::AdminDivisionOther,
404 }
405 }
406 }
407 "P" => GeonameType::City,
408 _ => GeonameType::Other,
409 };
410 let g_match = GeonameMatch {
411 geoname: Geoname {
412 geoname_id: row.get("id")?,
413 geoname_type,
414 name: row.get("name")?,
415 feature_class,
416 feature_code,
417 country_code: row.get("country_code")?,
418 admin_division_codes: [
419 row.get::<_, Option<String>>("admin1_code")?.map(|c| (1, c)),
420 row.get::<_, Option<String>>("admin2_code")?.map(|c| (2, c)),
421 row.get::<_, Option<String>>("admin3_code")?.map(|c| (3, c)),
422 row.get::<_, Option<String>>("admin4_code")?.map(|c| (4, c)),
423 ]
424 .into_iter()
425 .flatten()
426 .collect(),
427 population: row
428 .get::<_, Option<u64>>("population")?
429 .unwrap_or_default(),
430 latitude: row
431 .get::<_, Option<String>>("latitude")?
432 .unwrap_or_default(),
433 longitude: row
434 .get::<_, Option<String>>("longitude")?
435 .unwrap_or_default(),
436 },
437 prefix: row.get("prefix")?,
438 match_type: match row.get::<_, i32>("match_type")? {
439 1 => GeonameMatchType::Abbreviation,
440 2 => GeonameMatchType::AirportCode,
441 _ => GeonameMatchType::Name,
442 },
443 };
444 if let Some(geonames) = &filter {
445 if geonames.iter().all(|g| g.is_related_to(&g_match.geoname)) {
446 Ok(Some(g_match))
447 } else {
448 Ok(None)
449 }
450 } else {
451 Ok(Some(g_match))
452 }
453 },
454 )?
455 .into_iter()
456 .flatten()
457 .collect())
458 }
459
460 /// Fetches alternate names for a geoname and its country and admin
461 /// divisions.
462 pub fn fetch_geoname_alternates(&self, geoname: &Geoname) -> Result<GeonameAlternates> {
463 #[derive(Debug)]
464 struct Row {
465 geoname_id: GeonameId,
466 feature_code: String,
467 primary_name: String,
468 alt_language: Option<String>,
469 alt_name: String,
470 }
471
472 let rows = self.conn.query_rows_and_then_cached(
473 r#"
474 SELECT
475 g.id,
476 g.feature_code,
477 g.name AS primary_name,
478 a.language AS alt_language,
479 a.name AS alt_name
480 FROM
481 geonames g
482 JOIN
483 geonames_alternates a ON g.id = a.geoname_id
484 WHERE
485 -- Ignore airport codes
486 (a.language IS NULL OR a.language NOT IN ('iata', 'icao', 'faac'))
487 AND (
488 -- The row matches the passed-in geoname
489 g.id = :geoname_id
490 -- The row matches the geoname's country
491 OR (
492 g.feature_code IN ('PCLI', 'PCL', 'PCLD', 'PCLF', 'PCLS')
493 AND g.country_code = :country
494 )
495 -- The row matches one of the geoname's admin divisions
496 OR (g.feature_code = 'ADM1' AND g.admin1_code = :admin1)
497 OR (g.feature_code = 'ADM2' AND g.admin2_code = :admin2)
498 OR (g.feature_code = 'ADM3' AND g.admin3_code = :admin3)
499 OR (g.feature_code = 'ADM4' AND g.admin4_code = :admin4)
500 )
501 ORDER BY
502 -- Group rows for the same geoname together
503 g.id ASC,
504 -- Sort preferred and short names first; longer names tend to be
505 -- less commonly used ("California" vs. "State of California")
506 a.is_preferred DESC,
507 a.is_short DESC,
508 -- `a.language` is null for the primary and ASCII name (see
509 -- `insert_geonames`); sort those last
510 a.language IS NULL ASC,
511 -- Group by language; `a.language` should be either null, 'abbr'
512 -- for abbreviations, or the language code that was ingested
513 -- according to the locale in the RS context
514 a.language ASC,
515 -- Sort shorter names first, same reason as above
516 length(a.name) ASC,
517 a.name ASC
518 "#,
519 named_params! {
520 ":geoname_id": geoname.geoname_id,
521 ":country": geoname.country_code,
522 ":admin1": geoname.admin_division_codes.get(&1),
523 ":admin2": geoname.admin_division_codes.get(&2),
524 ":admin3": geoname.admin_division_codes.get(&3),
525 ":admin4": geoname.admin_division_codes.get(&4),
526 },
527 |row| -> Result<Row> {
528 Ok(Row {
529 geoname_id: row.get("id")?,
530 feature_code: row.get("feature_code")?,
531 primary_name: row.get("primary_name")?,
532 alt_language: row.get("alt_language")?,
533 alt_name: row.get("alt_name")?,
534 })
535 },
536 )?;
537
538 let mut geoname_localized: OnceCell<String> = OnceCell::new();
539 let mut geoname_abbr: OnceCell<String> = OnceCell::new();
540 let mut country_primary: OnceCell<String> = OnceCell::new();
541 let mut country_localized: OnceCell<String> = OnceCell::new();
542 let mut country_abbr: OnceCell<String> = OnceCell::new();
543 let mut admin_primary: HashMap<u8, String> = HashMap::new();
544 let mut admin_localized: HashMap<u8, String> = HashMap::new();
545 let mut admin_abbr: HashMap<u8, String> = HashMap::new();
546
547 // Loop through the rows. For each of the geoname, country, and admin
548 // divisions, save the first primary name, localized name, abbreviation
549 // we encounter. The `ORDER BY` in the query ensures that these will be
550 // the best names for each (or what we guess will be the best names).
551 for row in rows.into_iter() {
552 if row.geoname_id == geoname.geoname_id {
553 match row.alt_language.as_deref() {
554 Some("abbr") => geoname_abbr.get_or_init(|| row.alt_name),
555 _ => geoname_localized.get_or_init(|| row.alt_name),
556 };
557 } else if let Some(level) = match row.feature_code.as_str() {
558 "ADM1" => Some(1),
559 "ADM2" => Some(2),
560 "ADM3" => Some(3),
561 "ADM4" => Some(4),
562 _ => None,
563 } {
564 admin_primary.entry(level).or_insert(row.primary_name);
565 match row.alt_language.as_deref() {
566 Some("abbr") => admin_abbr.entry(level).or_insert(row.alt_name),
567 _ => admin_localized.entry(level).or_insert(row.alt_name),
568 };
569 } else {
570 country_primary.get_or_init(|| row.primary_name);
571 match row.alt_language.as_deref() {
572 Some("abbr") => country_abbr.get_or_init(|| row.alt_name),
573 _ => country_localized.get_or_init(|| row.alt_name),
574 };
575 }
576 }
577
578 Ok(GeonameAlternates {
579 geoname: AlternateNames {
580 primary: geoname.name.clone(),
581 localized: geoname_localized.take(),
582 abbreviation: geoname_abbr.take(),
583 },
584 country: country_primary.take().map(|primary| AlternateNames {
585 primary,
586 localized: country_localized.take(),
587 abbreviation: country_abbr.take(),
588 }),
589 admin_divisions: geoname
590 .admin_division_codes
591 .keys()
592 .filter_map(|level| {
593 admin_primary.remove(level).map(|primary| {
594 (
595 *level,
596 AlternateNames {
597 primary,
598 localized: admin_localized.remove(level),
599 abbreviation: admin_abbr.remove(level),
600 },
601 )
602 })
603 })
604 .collect(),
605 })
606 }
607
608 /// Inserts GeoNames data into the database.
609 fn insert_geonames(
610 &mut self,
611 record_id: &SuggestRecordId,
612 geonames: &[DownloadedGeoname],
613 ) -> Result<()> {
614 self.scope.err_if_interrupted()?;
615
616 let mut geoname_insert = GeonameInsertStatement::new(self.conn)?;
617 let mut alt_insert = GeonameAlternateInsertStatement::new(self.conn)?;
618 let mut metrics_updater = KeywordsMetricsUpdater::new();
619
620 for geoname in geonames {
621 geoname_insert.execute(record_id, geoname)?;
622
623 // Add alternates for each geoname's primary name (`geoname.name`)
624 // and ASCII name. `language` is set to null for these alternates.
625 alt_insert.execute(
626 record_id,
627 geoname.id,
628 None, // language
629 &DownloadedGeonamesAlternate::Name(geoname.name.as_str()),
630 )?;
631 metrics_updater.update(&geoname.name);
632
633 if let Some(ascii_name) = &geoname.ascii_name {
634 alt_insert.execute(
635 record_id,
636 geoname.id,
637 None, // language
638 &DownloadedGeonamesAlternate::Name(ascii_name.as_str()),
639 )?;
640 metrics_updater.update(ascii_name);
641 }
642 }
643
644 metrics_updater.finish(
645 self.conn,
646 record_id,
647 SuggestRecordType::GeonamesAlternates,
648 &mut self.geoname_cache,
649 )?;
650
651 Ok(())
652 }
653
654 /// Inserts GeoNames alternates data into the database.
655 fn insert_geonames_alternates(
656 &mut self,
657 record_id: &SuggestRecordId,
658 attachments: &[DownloadedGeonamesAlternatesAttachment],
659 ) -> Result<()> {
660 let mut alt_insert = GeonameAlternateInsertStatement::new(self.conn)?;
661 let mut metrics_updater = KeywordsMetricsUpdater::new();
662 for attach in attachments {
663 for (geoname_id, alts) in &attach.alternates_by_geoname_id {
664 for alt in alts {
665 alt_insert.execute(record_id, *geoname_id, Some(&attach.language), alt)?;
666 metrics_updater.update(alt.name());
667 }
668 }
669 }
670 metrics_updater.finish(
671 self.conn,
672 record_id,
673 SuggestRecordType::GeonamesAlternates,
674 &mut self.geoname_cache,
675 )?;
676 Ok(())
677 }
678
679 pub fn geoname_cache(&self) -> &GeonameCache {
680 self.geoname_cache.get_or_init(|| GeonameCache {
681 keywords_metrics: self
682 .get_keywords_metrics(SuggestRecordType::GeonamesAlternates)
683 .unwrap_or_default(),
684 })
685 }
686 }
687
688 impl<S> SuggestStoreInner<S>
689 where
690 S: Client,
691 {
692 /// Inserts a GeoNames record into the database.
693 pub fn process_geonames_record(
694 &self,
695 dao: &mut SuggestDao,
696 record: &Record,
697 context: &mut MetricsContext,
698 ) -> Result<()> {
699 self.download_attachment(dao, record, context, |dao, record_id, data| {
700 dao.insert_geonames(record_id, data)
701 })
702 }
703
704 /// Inserts a GeoNames record into the database.
705 pub fn process_geonames_alternates_record(
706 &self,
707 dao: &mut SuggestDao,
708 record: &Record,
709 context: &mut MetricsContext,
710 ) -> Result<()> {
711 self.download_attachment(dao, record, context, |dao, record_id, data| {
712 dao.insert_geonames_alternates(record_id, data)
713 })
714 }
715 }
716
717 struct GeonameInsertStatement<'conn>(rusqlite::Statement<'conn>);
718
719 impl<'conn> GeonameInsertStatement<'conn> {
720 fn new(conn: &'conn Connection) -> Result<Self> {
721 Ok(Self(conn.prepare(
722 "INSERT OR REPLACE INTO geonames(
723 id,
724 record_id,
725 name,
726 feature_class,
727 feature_code,
728 country_code,
729 admin1_code,
730 admin2_code,
731 admin3_code,
732 admin4_code,
733 population,
734 latitude,
735 longitude
736 )
737 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
738 ",
739 )?))
740 }
741
742 fn execute(&mut self, record_id: &SuggestRecordId, g: &DownloadedGeoname) -> Result<()> {
743 self.0
744 .execute(rusqlite::params![
745 &g.id,
746 record_id.as_str(),
747 &g.name,
748 &g.feature_class,
749 &g.feature_code,
750 &g.country,
751 &g.admin1,
752 &g.admin2,
753 &g.admin3,
754 &g.admin4,
755 &g.population,
756 &g.latitude,
757 &g.longitude,
758 ])
759 .with_context("geoname insert")?;
760 Ok(())
761 }
762 }
763
764 struct GeonameAlternateInsertStatement<'conn>(rusqlite::Statement<'conn>);
765
766 impl<'conn> GeonameAlternateInsertStatement<'conn> {
767 fn new(conn: &'conn Connection) -> Result<Self> {
768 Ok(Self(conn.prepare(
769 r#"
770 INSERT INTO geonames_alternates(
771 record_id,
772 geoname_id,
773 language,
774 name,
775 is_preferred,
776 is_short
777 )
778 VALUES(?, ?, ?, ?, ?, ?)
779 "#,
780 )?))
781 }
782
783 fn execute<S: AsRef<str>>(
784 &mut self,
785 record_id: &SuggestRecordId,
786 geoname_id: GeonameId,
787 language: Option<&str>,
788 alt: &DownloadedGeonamesAlternate<S>,
789 ) -> Result<()> {
790 self.0
791 .execute((
792 record_id.as_str(),
793 geoname_id,
794 language,
795 alt.name(),
796 alt.is_preferred(),
797 alt.is_short(),
798 ))
799 .with_context("geoname alternate insert")?;
800 Ok(())
801 }
802 }
803
804 #[cfg(test)]
805 pub(crate) mod tests {
806 use super::*;
807 use crate::{
808 provider::SuggestionProvider,
809 rs::{Collection, SuggestRecordType},
810 store::tests::TestStore,
811 testing::*,
812 SuggestIngestionConstraints,
813 };
814 use itertools::Itertools;
815 use serde_json::Value as JsonValue;
816
817 pub(crate) const LONG_NAME: &str = "123 aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk lll mmm nnn ooo ppp qqq rrr sss ttt uuu vvv www x yyy zzz";
818
819 pub(crate) fn geoname_mock_record(id: &str, json: JsonValue) -> MockRecord {
820 MockRecord {
821 collection: Collection::Other,
822 record_type: SuggestRecordType::Geonames,
823 id: id.to_string(),
824 inline_data: None,
825 attachment: Some(MockAttachment::Json(json)),
826 }
827 }
828
829 pub(crate) fn geoname_alternates_mock_record(id: &str, json: JsonValue) -> MockRecord {
830 MockRecord {
831 collection: Collection::Other,
832 record_type: SuggestRecordType::GeonamesAlternates,
833 id: id.to_string(),
834 inline_data: None,
835 attachment: Some(MockAttachment::Json(json)),
836 }
837 }
838
839 pub(crate) fn new_test_store() -> TestStore {
840 TestStore::new(
841 MockRemoteSettingsClient::default()
842 .with_record(geoname_mock_record("geonames-0", geonames_data()))
843 .with_record(geoname_alternates_mock_record(
844 "geonames-alternates-en",
845 geonames_alternates_data_en(),
846 ))
847 .with_record(geoname_alternates_mock_record(
848 "geonames-alternates-abbr",
849 geonames_alternates_data_abbr(),
850 ))
851 .with_record(geoname_alternates_mock_record(
852 "geonames-alternates-iata",
853 geonames_alternates_data_iata(),
854 )),
855 )
856 }
857
858 fn geonames_data() -> serde_json::Value {
859 json!([
860 // Waterloo, AL
861 {
862 "id": 4096497,
863 "name": "Waterloo",
864 "feature_class": "P",
865 "feature_code": "PPL",
866 "country": "US",
867 "admin1": "AL",
868 "admin2": "077",
869 "population": 200,
870 "latitude": "34.91814",
871 "longitude": "-88.0642",
872 },
873
874 // AL
875 {
876 "id": 4829764,
877 "name": "Alabama",
878 "feature_class": "A",
879 "feature_code": "ADM1",
880 "country": "US",
881 "admin1": "AL",
882 "population": 4530315,
883 "latitude": "32.75041",
884 "longitude": "-86.75026",
885 },
886
887 // Waterloo, IA
888 {
889 "id": 4880889,
890 "name": "Waterloo",
891 "feature_class": "P",
892 "feature_code": "PPLA2",
893 "country": "US",
894 "admin1": "IA",
895 "admin2": "013",
896 "admin3": "94597",
897 "population": 68460,
898 "latitude": "42.49276",
899 "longitude": "-92.34296",
900 },
901
902 // IA
903 {
904 "id": 4862182,
905 "name": "Iowa",
906 "feature_class": "A",
907 "feature_code": "ADM1",
908 "country": "US",
909 "admin1": "IA",
910 "population": 2955010,
911 "latitude": "42.00027",
912 "longitude": "-93.50049",
913 },
914
915 // New York City
916 {
917 "id": 5128581,
918 "name": "New York City",
919 "feature_class": "P",
920 "feature_code": "PPL",
921 "country": "US",
922 "admin1": "NY",
923 "population": 8804190,
924 "latitude": "40.71427",
925 "longitude": "-74.00597",
926 },
927
928 // Rochester, NY
929 {
930 "id": 5134086,
931 "name": "Rochester",
932 "feature_class": "P",
933 "feature_code": "PPLA2",
934 "country": "US",
935 "admin1": "NY",
936 "admin2": "055",
937 "admin3": "63000",
938 "population": 209802,
939 "latitude": "43.15478",
940 "longitude": "-77.61556",
941 },
942
943 // NY state
944 {
945 "id": 5128638,
946 "name": "New York",
947 "feature_class": "A",
948 "feature_code": "ADM1",
949 "country": "US",
950 "admin1": "NY",
951 "population": 19274244,
952 "latitude": "43.00035",
953 "longitude": "-75.4999",
954 },
955
956 // Waco, TX: Has a surprising IATA airport code that's a
957 // common English word and not a prefix of the city name
958 {
959 "id": 4739526,
960 "name": "Waco",
961 "feature_class": "P",
962 "feature_code": "PPLA2",
963 "country": "US",
964 "admin1": "TX",
965 "admin2": "309",
966 "population": 132356,
967 "latitude": "31.54933",
968 "longitude": "-97.14667",
969 },
970
971 // TX
972 {
973 "id": 4736286,
974 "name": "Texas",
975 "feature_class": "A",
976 "feature_code": "ADM1",
977 "country": "US",
978 "admin1": "TX",
979 "population": 22875689,
980 "latitude": "31.25044",
981 "longitude": "-99.25061",
982 },
983
984 // New Orleans (shares a prefix with New York)
985 {
986 "id": 4335045,
987 "name": "New Orleans",
988 "feature_class": "P",
989 "feature_code": "PPLA2",
990 "country": "US",
991 "admin1": "LA",
992 "admin2": "071",
993 "admin3": "98000",
994 "population": 389617,
995 "latitude": "29.95465",
996 "longitude": "-90.07507",
997 },
998
999 // Carlsbad, CA (in San Diego county, name starts with "CA")
1000 {
1001 "id": 5334223,
1002 "name": "Carlsbad",
1003 "country": "US",
1004 "feature_class": "P",
1005 "feature_code": "PPL",
1006 "admin1": "CA",
1007 "admin2": "073",
1008 "population": 114746,
1009 "latitude": "33.15809",
1010 "longitude": "-117.35059",
1011 },
1012
1013 // San Diego
1014 {
1015 "id": 5391811,
1016 "name": "San Diego",
1017 "country": "US",
1018 "feature_class": "P",
1019 "feature_code": "PPLA2",
1020 "admin1": "CA",
1021 "admin2": "073",
1022 "population": 1394928,
1023 "latitude": "32.71571",
1024 "longitude": "-117.16472",
1025 },
1026
1027 // San Diego County (same name as the city)
1028 {
1029 "id": 5391832,
1030 "name": "San Diego",
1031 "country": "US",
1032 "feature_class": "A",
1033 "feature_code": "ADM2",
1034 "admin1": "CA",
1035 "admin2": "073",
1036 "population": 3095313,
1037 "latitude": "33.0282",
1038 "longitude": "-116.77021",
1039 },
1040
1041 // CA
1042 {
1043 "id": 5332921,
1044 "name": "California",
1045 "feature_class": "A",
1046 "feature_code": "ADM1",
1047 "country": "US",
1048 "admin1": "CA",
1049 "population": 39512223,
1050 "latitude": "37.25022",
1051 "longitude": "-119.75126",
1052 },
1053
1054 // Made-up city with a long name (the digits in the name are to
1055 // prevent matches on this geoname in weather tests, etc.)
1056 {
1057 "id": 999,
1058 "name": "123 Long Name",
1059 "feature_class": "P",
1060 "feature_code": "PPLA2",
1061 "country": "US",
1062 "admin1": "NY",
1063 "population": 2,
1064 "latitude": "38.06084",
1065 "longitude": "-97.92977",
1066 },
1067
1068 // Made-up cities with punctuation their alternates (the digits in
1069 // the names are to prevent matches on these geonames in weather
1070 // tests, etc.)
1071 {
1072 "id": 1000,
1073 "name": "123 Punctuation City 0",
1074 "feature_class": "P",
1075 "feature_code": "PPLA2",
1076 "country": "XX",
1077 "population": 2,
1078 "latitude": "38.06084",
1079 "longitude": "-97.92977",
1080 },
1081 {
1082 "id": 1001,
1083 "name": "123 Punctuation City 1",
1084 "feature_class": "P",
1085 "feature_code": "PPLA2",
1086 "country": "XX",
1087 "population": 2,
1088 "latitude": "38.06084",
1089 "longitude": "-97.92977",
1090 },
1091 {
1092 "id": 1002,
1093 "name": "123 Punctuation City 2",
1094 "feature_class": "P",
1095 "feature_code": "PPLA2",
1096 "country": "XX",
1097 "population": 2,
1098 "latitude": "38.06084",
1099 "longitude": "-97.92977",
1100 },
1101 {
1102 "id": 1003,
1103 "name": "123 Punctuation City 3",
1104 "feature_class": "P",
1105 "feature_code": "PPLA2",
1106 "country": "XX",
1107 "population": 2,
1108 "latitude": "38.06084",
1109 "longitude": "-97.92977",
1110 },
1111 {
1112 "id": 1004,
1113 "name": "123 Punctuation City 4",
1114 "feature_class": "P",
1115 "feature_code": "PPLA2",
1116 "country": "XX",
1117 "population": 2,
1118 "latitude": "38.06084",
1119 "longitude": "-97.92977",
1120 },
1121 {
1122 "id": 1005,
1123 "name": "123 Punctuation City 5",
1124 "feature_class": "P",
1125 "feature_code": "PPLA2",
1126 "country": "XX",
1127 "population": 2,
1128 "latitude": "38.06084",
1129 "longitude": "-97.92977",
1130 },
1131
1132 // St. Louis (has '.' in name)
1133 {
1134 "id": 4407066,
1135 "name": "St. Louis",
1136 "feature_class": "P",
1137 "feature_code": "PPLA2",
1138 "country": "US",
1139 "admin1": "MO",
1140 "admin2": "510",
1141 "population": 315685,
1142 "latitude": "38.62727",
1143 "longitude": "-90.19789",
1144 },
1145
1146 // Carmel-by-the-Sea (has '-' in name)
1147 {
1148 "id": 5334320,
1149 "name": "Carmel-by-the-Sea",
1150 "feature_class": "P",
1151 "feature_code": "PPL",
1152 "country": "US",
1153 "admin1": "CA",
1154 "admin2": "053",
1155 "population": 3897,
1156 "latitude": "36.55524",
1157 "longitude": "-121.92329",
1158 },
1159
1160 // United States
1161 {
1162 "id": 6252001,
1163 "name": "United States",
1164 "feature_class": "A",
1165 "feature_code": "PCLI",
1166 "country": "US",
1167 "admin1": "00",
1168 "population": 327167434,
1169 "latitude": "39.76",
1170 "longitude": "-98.5",
1171 },
1172
1173 // Canada
1174 {
1175 "id": 6251999,
1176 "name": "Canada",
1177 "feature_class": "A",
1178 "feature_code": "PCLI",
1179 "country": "CA",
1180 "admin1": "00",
1181 "population": 37058856,
1182 "latitude": "60.10867",
1183 "longitude": "-113.64258",
1184 },
1185
1186 // ON
1187 {
1188 "id": 6093943,
1189 "name": "Ontario",
1190 "feature_class": "A",
1191 "feature_code": "ADM1",
1192 "country": "CA",
1193 "admin1": "08",
1194 "population": 12861940,
1195 "latitude": "49.25014",
1196 "longitude": "-84.49983",
1197 },
1198
1199 // Waterloo, ON
1200 {
1201 "id": 6176823,
1202 "name": "Waterloo",
1203 "feature_class": "P",
1204 "feature_code": "PPL",
1205 "country": "CA",
1206 "admin1": "08",
1207 "admin2": "3530",
1208 "population": 104986,
1209 "latitude": "43.4668",
1210 "longitude": "-80.51639",
1211 },
1212
1213 // UK
1214 {
1215 "id": 2635167,
1216 "name": "United Kingdom of Great Britain and Northern Ireland",
1217 "feature_class": "A",
1218 "feature_code": "PCLI",
1219 "country": "GB",
1220 "admin1": "00",
1221 "population": 66488991,
1222 "latitude": "54.75844",
1223 "longitude": "-2.69531",
1224 },
1225
1226 // England
1227 {
1228 "id": 6269131,
1229 "name": "England",
1230 "feature_class": "A",
1231 "feature_code": "ADM1",
1232 "country": "GB",
1233 "admin1": "ENG",
1234 "population": 57106398,
1235 "latitude": "52.16045",
1236 "longitude": "-0.70312",
1237 },
1238
1239 // Liverpool (metropolitan borough, admin2 for Liverpool city)
1240 {
1241 "id": 3333167,
1242 "name": "Liverpool",
1243 "feature_class": "A",
1244 "feature_code": "ADM2",
1245 "country": "GB",
1246 "admin1": "ENG",
1247 "admin2": "H8",
1248 "population": 484578,
1249 "latitude": "53.41667",
1250 "longitude": "-2.91667",
1251 },
1252
1253 // Liverpool (city)
1254 {
1255 "id": 2644210,
1256 "name": "Liverpool",
1257 "feature_class": "P",
1258 "feature_code": "PPLA2",
1259 "country": "GB",
1260 "admin1": "ENG",
1261 "admin2": "H8",
1262 "population": 864122,
1263 "latitude": "53.41058",
1264 "longitude": "-2.97794",
1265 },
1266
1267 // Gößnitz, DE (has non-basic-Latin chars and an `ascii_name`)
1268 {
1269 "id": 2918770,
1270 "name": "Gößnitz",
1271 "ascii_name": "Goessnitz",
1272 "feature_class": "P",
1273 "feature_code": "PPL",
1274 "country": "DE",
1275 "admin1": "15",
1276 "admin2": "00",
1277 "admin3": "16077",
1278 "admin4": "16077012",
1279 "population": 4104,
1280 "latitude": "50.88902",
1281 "longitude": "12.43292",
1282 },
1283 ])
1284 }
1285
1286 fn geonames_alternates_data_en() -> serde_json::Value {
1287 json!({
1288 "language": "en",
1289 "alternates_by_geoname_id": [
1290 // United States
1291 [6252001, [
1292 { "name": "United States", "is_preferred": true, "is_short": true },
1293 { "name": "United States of America", "is_preferred": true },
1294 { "name": "USA", "is_short": true },
1295 "America",
1296 ]],
1297
1298 // UK
1299 [2635167, [
1300 { "name": "United Kingdom", "is_preferred": true, "is_short": true },
1301 { "name": "Great Britain", "is_short": true },
1302 { "name": "UK", "is_short": true },
1303 "Britain",
1304 "U.K.",
1305 "United Kingdom of Great Britain and Northern Ireland",
1306 "U.K",
1307 ]],
1308
1309 // New York City
1310 [5128581, [
1311 { "name": "New York", "is_preferred": true, "is_short": true },
1312 ]],
1313
1314 // Made-up city with a long name
1315 [999, [LONG_NAME]],
1316
1317 // Made-up cities with punctuation in their alternates
1318 [1000, [
1319 // The first name is shorter, so we should prefer it.
1320 "123 Made Up City w Punct in Alternates",
1321 "123 Made-Up City. w/ Punct. in Alternates",
1322 ]],
1323 [1001, [
1324 // The second name is shorter, so we should prefer it.
1325 "123 Made-Up City. w/ Punct. in Alternates",
1326 "123 Made Up City w Punct in Alternates",
1327 ]],
1328 [1002, [
1329 // These names are the same length but the second will be
1330 // sorted first due to the `a.name ASC` in the `ORDER BY`,
1331 // so we should prefer it.
1332 "123 Made-Up City. w/ Punct. in Alternates",
1333 "123 Made Up City w Punct in Alternates",
1334 "123 Made-Up City. w/ Punct. in Alternatex",
1335 ]],
1336 [1003, [
1337 // The second name has `is_preferred`, so we should prefer
1338 // it.
1339 "123 Aaa Bbb Ccc Ddd",
1340 { "name": "123 Aaa, Bbb-Ccc. Ddd", "is_preferred": true },
1341 "123 Aaa Bbb Ccc Eee",
1342 ]],
1343 [1004, [
1344 // The second name has `is_short`, so we should prefer it.
1345 "123 Aaa Bbb Ccc Ddd",
1346 { "name": "123 Aaa, Bbb-Ccc. Ddd", "is_short": true },
1347 "123 Aaa Bbb Ccc Eee",
1348 ]],
1349 [1005, [
1350 // The second name has `is_preferred` and `is_short`, so we
1351 // should prefer it.
1352 "123 Aaa Bbb Ccc Ddd",
1353 { "name": "123 Aaa, Bbb-Ccc. Ddd", "is_preferred": true, "is_short": true },
1354 "123 Aaa Bbb Ccc Eee",
1355 ]],
1356 ],
1357 })
1358 }
1359
1360 fn geonames_alternates_data_abbr() -> serde_json::Value {
1361 json!({
1362 "language": "abbr",
1363 "alternates_by_geoname_id": [
1364 // AL
1365 [4829764, ["AL"]],
1366 // IA
1367 [4862182, ["IA"]],
1368 // ON
1369 [6093943, [
1370 "ON",
1371 "Ont.",
1372 ]],
1373 // NY State
1374 [5128638, ["NY"]],
1375 // TX
1376 [4736286, ["TX"]],
1377 // New York City
1378 [5128581, [
1379 "NYC",
1380 "NY",
1381 ]],
1382 // CA
1383 [5332921, ["CA"]],
1384 // United States
1385 [6252001, [
1386 { "name": "US", "is_short": true },
1387 "U.S.",
1388 "USA",
1389 "U.S.A.",
1390 ]],
1391 // Liverpool (metropolitan borough, admin2 for Liverpool city)
1392 [3333167, ["LIV"]],
1393 // UK
1394 [2635167, [
1395 "UK",
1396 ]],
1397 ],
1398 })
1399 }
1400
1401 fn geonames_alternates_data_iata() -> serde_json::Value {
1402 json!({
1403 "language": "iata",
1404 "alternates_by_geoname_id": [
1405 // Waco, TX
1406 [4739526, ["ACT"]],
1407 // Rochester, NY
1408 [5134086, ["ROC"]],
1409 ],
1410 })
1411 }
1412
1413 pub(crate) fn waterloo_al() -> Geoname {
1414 Geoname {
1415 geoname_id: 4096497,
1416 geoname_type: GeonameType::City,
1417 name: "Waterloo".to_string(),
1418 feature_class: "P".to_string(),
1419 feature_code: "PPL".to_string(),
1420 country_code: "US".to_string(),
1421 admin_division_codes: [(1, "AL".to_string()), (2, "077".to_string())].into(),
1422 population: 200,
1423 latitude: "34.91814".to_string(),
1424 longitude: "-88.0642".to_string(),
1425 }
1426 }
1427
1428 pub(crate) fn waterloo_ia() -> Geoname {
1429 Geoname {
1430 geoname_id: 4880889,
1431 geoname_type: GeonameType::City,
1432 name: "Waterloo".to_string(),
1433 feature_class: "P".to_string(),
1434 feature_code: "PPLA2".to_string(),
1435 country_code: "US".to_string(),
1436 admin_division_codes: [
1437 (1, "IA".to_string()),
1438 (2, "013".to_string()),
1439 (3, "94597".to_string()),
1440 ]
1441 .into(),
1442 population: 68460,
1443 latitude: "42.49276".to_string(),
1444 longitude: "-92.34296".to_string(),
1445 }
1446 }
1447
1448 pub(crate) fn nyc() -> Geoname {
1449 Geoname {
1450 geoname_id: 5128581,
1451 geoname_type: GeonameType::City,
1452 name: "New York City".to_string(),
1453 feature_class: "P".to_string(),
1454 feature_code: "PPL".to_string(),
1455 country_code: "US".to_string(),
1456 admin_division_codes: [(1, "NY".to_string())].into(),
1457 population: 8804190,
1458 latitude: "40.71427".to_string(),
1459 longitude: "-74.00597".to_string(),
1460 }
1461 }
1462
1463 pub(crate) fn rochester() -> Geoname {
1464 Geoname {
1465 geoname_id: 5134086,
1466 geoname_type: GeonameType::City,
1467 name: "Rochester".to_string(),
1468 feature_class: "P".to_string(),
1469 feature_code: "PPLA2".to_string(),
1470 country_code: "US".to_string(),
1471 admin_division_codes: [
1472 (1, "NY".to_string()),
1473 (2, "055".to_string()),
1474 (3, "63000".to_string()),
1475 ]
1476 .into(),
1477 population: 209802,
1478 latitude: "43.15478".to_string(),
1479 longitude: "-77.61556".to_string(),
1480 }
1481 }
1482
1483 pub(crate) fn waco() -> Geoname {
1484 Geoname {
1485 geoname_id: 4739526,
1486 geoname_type: GeonameType::City,
1487 name: "Waco".to_string(),
1488 feature_class: "P".to_string(),
1489 feature_code: "PPLA2".to_string(),
1490 country_code: "US".to_string(),
1491 admin_division_codes: [(1, "TX".to_string()), (2, "309".to_string())].into(),
1492 population: 132356,
1493 latitude: "31.54933".to_string(),
1494 longitude: "-97.14667".to_string(),
1495 }
1496 }
1497
1498 pub(crate) fn new_orleans() -> Geoname {
1499 Geoname {
1500 geoname_id: 4335045,
1501 geoname_type: GeonameType::City,
1502 name: "New Orleans".to_string(),
1503 feature_class: "P".to_string(),
1504 feature_code: "PPLA2".to_string(),
1505 country_code: "US".to_string(),
1506 admin_division_codes: [
1507 (1, "LA".to_string()),
1508 (2, "071".to_string()),
1509 (3, "98000".to_string()),
1510 ]
1511 .into(),
1512 population: 389617,
1513 latitude: "29.95465".to_string(),
1514 longitude: "-90.07507".to_string(),
1515 }
1516 }
1517
1518 pub(crate) fn carlsbad() -> Geoname {
1519 Geoname {
1520 geoname_id: 5334223,
1521 geoname_type: GeonameType::City,
1522 name: "Carlsbad".to_string(),
1523 feature_class: "P".to_string(),
1524 feature_code: "PPL".to_string(),
1525 country_code: "US".to_string(),
1526 admin_division_codes: [(1, "CA".to_string()), (2, "073".to_string())].into(),
1527 population: 114746,
1528 latitude: "33.15809".to_string(),
1529 longitude: "-117.35059".to_string(),
1530 }
1531 }
1532
1533 pub(crate) fn san_diego() -> Geoname {
1534 Geoname {
1535 geoname_id: 5391811,
1536 geoname_type: GeonameType::City,
1537 name: "San Diego".to_string(),
1538 feature_class: "P".to_string(),
1539 feature_code: "PPLA2".to_string(),
1540 country_code: "US".to_string(),
1541 admin_division_codes: [(1, "CA".to_string()), (2, "073".to_string())].into(),
1542 population: 1394928,
1543 latitude: "32.71571".to_string(),
1544 longitude: "-117.16472".to_string(),
1545 }
1546 }
1547
1548 pub(crate) fn long_name_city() -> Geoname {
1549 Geoname {
1550 geoname_id: 999,
1551 geoname_type: GeonameType::City,
1552 name: "123 Long Name".to_string(),
1553 feature_class: "P".to_string(),
1554 feature_code: "PPLA2".to_string(),
1555 country_code: "US".to_string(),
1556 admin_division_codes: [(1, "NY".to_string())].into(),
1557 population: 2,
1558 latitude: "38.06084".to_string(),
1559 longitude: "-97.92977".to_string(),
1560 }
1561 }
1562
1563 pub(crate) fn punctuation_city(i: i64) -> Geoname {
1564 Geoname {
1565 geoname_id: 1000 + i,
1566 geoname_type: GeonameType::City,
1567 name: format!("123 Punctuation City {i}"),
1568 feature_class: "P".to_string(),
1569 feature_code: "PPLA2".to_string(),
1570 country_code: "XX".to_string(),
1571 admin_division_codes: [].into(),
1572 population: 2,
1573 latitude: "38.06084".to_string(),
1574 longitude: "-97.92977".to_string(),
1575 }
1576 }
1577
1578 pub(crate) fn al() -> Geoname {
1579 Geoname {
1580 geoname_id: 4829764,
1581 geoname_type: GeonameType::AdminDivision { level: 1 },
1582 name: "Alabama".to_string(),
1583 feature_class: "A".to_string(),
1584 feature_code: "ADM1".to_string(),
1585 country_code: "US".to_string(),
1586 admin_division_codes: [(1, "AL".to_string())].into(),
1587 population: 4530315,
1588 latitude: "32.75041".to_string(),
1589 longitude: "-86.75026".to_string(),
1590 }
1591 }
1592
1593 pub(crate) fn ia() -> Geoname {
1594 Geoname {
1595 geoname_id: 4862182,
1596 geoname_type: GeonameType::AdminDivision { level: 1 },
1597 name: "Iowa".to_string(),
1598 feature_class: "A".to_string(),
1599 feature_code: "ADM1".to_string(),
1600 country_code: "US".to_string(),
1601 admin_division_codes: [(1, "IA".to_string())].into(),
1602 population: 2955010,
1603 latitude: "42.00027".to_string(),
1604 longitude: "-93.50049".to_string(),
1605 }
1606 }
1607
1608 pub(crate) fn ny_state() -> Geoname {
1609 Geoname {
1610 geoname_id: 5128638,
1611 geoname_type: GeonameType::AdminDivision { level: 1 },
1612 name: "New York".to_string(),
1613 feature_class: "A".to_string(),
1614 feature_code: "ADM1".to_string(),
1615 country_code: "US".to_string(),
1616 admin_division_codes: [(1, "NY".to_string())].into(),
1617 population: 19274244,
1618 latitude: "43.00035".to_string(),
1619 longitude: "-75.4999".to_string(),
1620 }
1621 }
1622
1623 pub(crate) fn st_louis() -> Geoname {
1624 Geoname {
1625 geoname_id: 4407066,
1626 geoname_type: GeonameType::City,
1627 name: "St. Louis".to_string(),
1628 feature_class: "P".to_string(),
1629 feature_code: "PPLA2".to_string(),
1630 country_code: "US".to_string(),
1631 admin_division_codes: [(1, "MO".to_string()), (2, "510".to_string())].into(),
1632 population: 315685,
1633 latitude: "38.62727".to_string(),
1634 longitude: "-90.19789".to_string(),
1635 }
1636 }
1637
1638 pub(crate) fn carmel() -> Geoname {
1639 Geoname {
1640 geoname_id: 5334320,
1641 geoname_type: GeonameType::City,
1642 name: "Carmel-by-the-Sea".to_string(),
1643 feature_class: "P".to_string(),
1644 feature_code: "PPL".to_string(),
1645 country_code: "US".to_string(),
1646 admin_division_codes: [(1, "CA".to_string()), (2, "053".to_string())].into(),
1647 population: 3897,
1648 latitude: "36.55524".to_string(),
1649 longitude: "-121.92329".to_string(),
1650 }
1651 }
1652
1653 pub(crate) fn us() -> Geoname {
1654 Geoname {
1655 geoname_id: 6252001,
1656 geoname_type: GeonameType::Country,
1657 name: "United States".to_string(),
1658 feature_class: "A".to_string(),
1659 feature_code: "PCLI".to_string(),
1660 country_code: "US".to_string(),
1661 admin_division_codes: [(1, "00".to_string())].into(),
1662 population: 327167434,
1663 latitude: "39.76".to_string(),
1664 longitude: "-98.5".to_string(),
1665 }
1666 }
1667
1668 pub(crate) fn canada() -> Geoname {
1669 Geoname {
1670 geoname_id: 6251999,
1671 geoname_type: GeonameType::Country,
1672 name: "Canada".to_string(),
1673 feature_class: "A".to_string(),
1674 feature_code: "PCLI".to_string(),
1675 country_code: "CA".to_string(),
1676 admin_division_codes: [(1, "00".to_string())].into(),
1677 population: 37058856,
1678 latitude: "60.10867".to_string(),
1679 longitude: "-113.64258".to_string(),
1680 }
1681 }
1682
1683 pub(crate) fn on() -> Geoname {
1684 Geoname {
1685 geoname_id: 6093943,
1686 geoname_type: GeonameType::AdminDivision { level: 1 },
1687 name: "Ontario".to_string(),
1688 feature_class: "A".to_string(),
1689 feature_code: "ADM1".to_string(),
1690 country_code: "CA".to_string(),
1691 admin_division_codes: [(1, "08".to_string())].into(),
1692 population: 12861940,
1693 latitude: "49.25014".to_string(),
1694 longitude: "-84.49983".to_string(),
1695 }
1696 }
1697
1698 pub(crate) fn waterloo_on() -> Geoname {
1699 Geoname {
1700 geoname_id: 6176823,
1701 geoname_type: GeonameType::City,
1702 name: "Waterloo".to_string(),
1703 feature_class: "P".to_string(),
1704 feature_code: "PPL".to_string(),
1705 country_code: "CA".to_string(),
1706 admin_division_codes: [(1, "08".to_string()), (2, "3530".to_string())].into(),
1707 population: 104986,
1708 latitude: "43.4668".to_string(),
1709 longitude: "-80.51639".to_string(),
1710 }
1711 }
1712
1713 pub(crate) fn uk() -> Geoname {
1714 Geoname {
1715 geoname_id: 2635167,
1716 geoname_type: GeonameType::Country,
1717 name: "United Kingdom of Great Britain and Northern Ireland".to_string(),
1718 feature_class: "A".to_string(),
1719 feature_code: "PCLI".to_string(),
1720 country_code: "GB".to_string(),
1721 admin_division_codes: [(1, "00".to_string())].into(),
1722 population: 66488991,
1723 latitude: "54.75844".to_string(),
1724 longitude: "-2.69531".to_string(),
1725 }
1726 }
1727
1728 pub(crate) fn england() -> Geoname {
1729 Geoname {
1730 geoname_id: 6269131,
1731 geoname_type: GeonameType::AdminDivision { level: 1 },
1732 name: "England".to_string(),
1733 feature_class: "A".to_string(),
1734 feature_code: "ADM1".to_string(),
1735 country_code: "GB".to_string(),
1736 admin_division_codes: [(1, "ENG".to_string())].into(),
1737 population: 57106398,
1738 latitude: "52.16045".to_string(),
1739 longitude: "-0.70312".to_string(),
1740 }
1741 }
1742
1743 pub(crate) fn liverpool_metro() -> Geoname {
1744 Geoname {
1745 geoname_id: 3333167,
1746 geoname_type: GeonameType::AdminDivision { level: 2 },
1747 name: "Liverpool".to_string(),
1748 feature_class: "A".to_string(),
1749 feature_code: "ADM2".to_string(),
1750 country_code: "GB".to_string(),
1751 admin_division_codes: [(1, "ENG".to_string()), (2, "H8".to_string())].into(),
1752 population: 484578,
1753 latitude: "53.41667".to_string(),
1754 longitude: "-2.91667".to_string(),
1755 }
1756 }
1757
1758 pub(crate) fn liverpool_city() -> Geoname {
1759 Geoname {
1760 geoname_id: 2644210,
1761 geoname_type: GeonameType::City,
1762 name: "Liverpool".to_string(),
1763 feature_class: "P".to_string(),
1764 feature_code: "PPLA2".to_string(),
1765 country_code: "GB".to_string(),
1766 admin_division_codes: [(1, "ENG".to_string()), (2, "H8".to_string())].into(),
1767 population: 864122,
1768 latitude: "53.41058".to_string(),
1769 longitude: "-2.97794".to_string(),
1770 }
1771 }
1772
1773 pub(crate) fn goessnitz() -> Geoname {
1774 Geoname {
1775 geoname_id: 2918770,
1776 geoname_type: GeonameType::City,
1777 name: "Gößnitz".to_string(),
1778 feature_class: "P".to_string(),
1779 feature_code: "PPL".to_string(),
1780 country_code: "DE".to_string(),
1781 admin_division_codes: [
1782 (1, "15".to_string()),
1783 (2, "00".to_string()),
1784 (3, "16077".to_string()),
1785 (4, "16077012".to_string()),
1786 ]
1787 .into(),
1788 population: 4104,
1789 latitude: "50.88902".to_string(),
1790 longitude: "12.43292".to_string(),
1791 }
1792 }
1793
1794 #[test]
1795 fn is_related_to() -> anyhow::Result<()> {
1796 // The geonames in each vec should be pairwise related.
1797 let tests = [
1798 vec![waterloo_ia(), ia(), us()],
1799 vec![waterloo_al(), al(), us()],
1800 vec![waterloo_on(), on(), canada()],
1801 vec![liverpool_city(), liverpool_metro(), england(), uk()],
1802 ];
1803 for geonames in tests {
1804 for g in &geonames {
1805 // A geoname should always be related to itself.
1806 assert!(
1807 g.is_related_to(g),
1808 "g.is_related_to(g) should always be true: {:?}",
1809 g
1810 );
1811 }
1812 for a_and_b in geonames.iter().permutations(2) {
1813 assert!(
1814 a_and_b[0].is_related_to(a_and_b[1]),
1815 "is_related_to: {:?}",
1816 a_and_b
1817 );
1818 }
1819 }
1820 Ok(())
1821 }
1822
1823 #[test]
1824 fn is_not_related_to() -> anyhow::Result<()> {
1825 // The geonames in each vec should not be pairwise related.
1826 let tests = [
1827 vec![waterloo_ia(), al()],
1828 vec![waterloo_ia(), on()],
1829 vec![waterloo_ia(), canada(), uk()],
1830 vec![waterloo_al(), ia()],
1831 vec![waterloo_al(), on()],
1832 vec![waterloo_al(), canada(), uk()],
1833 vec![waterloo_on(), al()],
1834 vec![waterloo_on(), ia()],
1835 vec![waterloo_on(), us(), uk()],
1836 vec![
1837 waterloo_ia(),
1838 waterloo_al(),
1839 waterloo_on(),
1840 liverpool_city(),
1841 ],
1842 vec![liverpool_city(), us(), canada()],
1843 vec![liverpool_metro(), us(), canada()],
1844 vec![england(), us(), canada()],
1845 vec![al(), ia(), on(), england()],
1846 vec![us(), canada(), uk()],
1847 ];
1848 for geonames in tests {
1849 for a_and_b in geonames.iter().permutations(2) {
1850 assert!(
1851 !a_and_b[0].is_related_to(a_and_b[1]),
1852 "!is_related_to: {:?}",
1853 a_and_b
1854 );
1855 }
1856 }
1857 Ok(())
1858 }
1859
1860 #[test]
1861 fn geonames_collate() -> anyhow::Result<()> {
1862 let tests = [
1863 ["AbC xYz", "ABC XYZ", "abc xyz"].as_slice(),
1864 &["Àęí", "Aei", "àęí", "aei"],
1865 &[
1866 // "Québec" with single 'é' char
1867 "Qu\u{00e9}bec",
1868 // "Québec" with ASCII 'e' followed by combining acute accent
1869 "Que\u{0301}bec",
1870 "Quebec",
1871 "quebec",
1872 ],
1873 &[
1874 "Gößnitz",
1875 "Gössnitz",
1876 "Goßnitz",
1877 "Gossnitz",
1878 "gößnitz",
1879 "gössnitz",
1880 "goßnitz",
1881 "gossnitz",
1882 ],
1883 &["St. Louis", "St... Louis", "St Louis"],
1884 &["U.S.A.", "US.A.", "U.SA.", "U.S.A", "USA.", "U.SA", "USA"],
1885 &["Carmel-by-the-Sea", "Carmel by the Sea"],
1886 &[".,-'()[]?<>", ".,-'()[]?<>"],
1887 ];
1888 for strs in tests {
1889 for a_and_b in strs.iter().permutations(2) {
1890 assert_eq!(
1891 super::geonames_collate(a_and_b[0], a_and_b[1]),
1892 std::cmp::Ordering::Equal,
1893 "Comparing: {:?}",
1894 a_and_b
1895 );
1896 }
1897 }
1898 Ok(())
1899 }
1900
1901 #[test]
1902 fn alternates() -> anyhow::Result<()> {
1903 before_each();
1904
1905 let store = new_test_store();
1906
1907 // Ingest weather to also ingest geonames.
1908 store.ingest(SuggestIngestionConstraints {
1909 providers: Some(vec![SuggestionProvider::Weather]),
1910 ..SuggestIngestionConstraints::all_providers()
1911 });
1912
1913 #[derive(Debug)]
1914 struct Test {
1915 geoname: Geoname,
1916 expected: GeonameAlternates,
1917 }
1918
1919 impl Test {
1920 fn new<F: FnOnce(&Geoname) -> GeonameAlternates>(
1921 geoname: Geoname,
1922 expected: F,
1923 ) -> Self {
1924 Test {
1925 expected: expected(&geoname),
1926 geoname,
1927 }
1928 }
1929 }
1930
1931 let tests = [
1932 Test::new(nyc(), |g| GeonameAlternates {
1933 geoname: AlternateNames {
1934 primary: g.name.clone(),
1935 localized: Some("New York".to_string()),
1936 abbreviation: Some("NY".to_string()),
1937 },
1938 country: Some(AlternateNames {
1939 primary: "United States".to_string(),
1940 localized: Some("United States".to_string()),
1941 abbreviation: Some("US".to_string()),
1942 }),
1943 admin_divisions: [(
1944 1,
1945 AlternateNames {
1946 primary: ny_state().name.clone(),
1947 localized: Some("New York".to_string()),
1948 abbreviation: Some("NY".to_string()),
1949 },
1950 )]
1951 .into(),
1952 }),
1953 Test::new(waterloo_on(), |g| GeonameAlternates {
1954 geoname: AlternateNames {
1955 primary: g.name.clone(),
1956 localized: Some("Waterloo".to_string()),
1957 abbreviation: None,
1958 },
1959 country: Some(AlternateNames {
1960 primary: "Canada".to_string(),
1961 // There are no alternates for Canada so `localized` should
1962 // be the primary name
1963 localized: Some("Canada".to_string()),
1964 abbreviation: None,
1965 }),
1966 admin_divisions: [(
1967 1,
1968 AlternateNames {
1969 primary: on().name.clone(),
1970 localized: Some("Ontario".to_string()),
1971 abbreviation: Some("ON".to_string()),
1972 },
1973 )]
1974 .into(),
1975 }),
1976 Test::new(liverpool_city(), |g| GeonameAlternates {
1977 geoname: AlternateNames {
1978 primary: g.name.clone(),
1979 localized: Some("Liverpool".to_string()),
1980 abbreviation: None,
1981 },
1982 country: Some(AlternateNames {
1983 primary: "United Kingdom of Great Britain and Northern Ireland".to_string(),
1984 localized: Some("United Kingdom".to_string()),
1985 abbreviation: Some("UK".to_string()),
1986 }),
1987 admin_divisions: [
1988 (
1989 1,
1990 AlternateNames {
1991 primary: england().name.clone(),
1992 localized: Some("England".to_string()),
1993 abbreviation: None,
1994 },
1995 ),
1996 (
1997 2,
1998 AlternateNames {
1999 primary: liverpool_metro().name.clone(),
2000 localized: Some("Liverpool".to_string()),
2001 abbreviation: Some("LIV".to_string()),
2002 },
2003 ),
2004 ]
2005 .into(),
2006 }),
2007 Test::new(punctuation_city(0), |g| GeonameAlternates {
2008 geoname: AlternateNames {
2009 primary: g.name.clone(),
2010 localized: Some("123 Made Up City w Punct in Alternates".to_string()),
2011 abbreviation: None,
2012 },
2013 country: None,
2014 admin_divisions: [].into(),
2015 }),
2016 Test::new(punctuation_city(1), |g| GeonameAlternates {
2017 geoname: AlternateNames {
2018 primary: g.name.clone(),
2019 localized: Some("123 Made Up City w Punct in Alternates".to_string()),
2020 abbreviation: None,
2021 },
2022 country: None,
2023 admin_divisions: [].into(),
2024 }),
2025 Test::new(punctuation_city(2), |g| GeonameAlternates {
2026 geoname: AlternateNames {
2027 primary: g.name.clone(),
2028 localized: Some("123 Made Up City w Punct in Alternates".to_string()),
2029 abbreviation: None,
2030 },
2031 country: None,
2032 admin_divisions: [].into(),
2033 }),
2034 Test::new(punctuation_city(3), |g| GeonameAlternates {
2035 geoname: AlternateNames {
2036 primary: g.name.clone(),
2037 localized: Some("123 Aaa, Bbb-Ccc. Ddd".to_string()),
2038 abbreviation: None,
2039 },
2040 country: None,
2041 admin_divisions: [].into(),
2042 }),
2043 Test::new(punctuation_city(4), |g| GeonameAlternates {
2044 geoname: AlternateNames {
2045 primary: g.name.clone(),
2046 localized: Some("123 Aaa, Bbb-Ccc. Ddd".to_string()),
2047 abbreviation: None,
2048 },
2049 country: None,
2050 admin_divisions: [].into(),
2051 }),
2052 Test::new(punctuation_city(5), |g| GeonameAlternates {
2053 geoname: AlternateNames {
2054 primary: g.name.clone(),
2055 localized: Some("123 Aaa, Bbb-Ccc. Ddd".to_string()),
2056 abbreviation: None,
2057 },
2058 country: None,
2059 admin_divisions: [].into(),
2060 }),
2061 ];
2062
2063 store.read(|dao| {
2064 for t in tests {
2065 assert_eq!(
2066 dao.fetch_geoname_alternates(&t.geoname)?,
2067 t.expected,
2068 "geoname={:?}",
2069 t.geoname
2070 );
2071 }
2072 Ok(())
2073 })?;
2074
2075 Ok(())
2076 }
2077
2078 #[test]
2079 fn geonames() -> anyhow::Result<()> {
2080 before_each();
2081
2082 let store = new_test_store();
2083
2084 // Ingest weather to also ingest geonames.
2085 store.ingest(SuggestIngestionConstraints {
2086 providers: Some(vec![SuggestionProvider::Weather]),
2087 ..SuggestIngestionConstraints::all_providers()
2088 });
2089
2090 #[derive(Debug)]
2091 struct Test {
2092 query: &'static str,
2093 match_name_prefix: bool,
2094 filter: Option<Vec<Geoname>>,
2095 expected: Vec<GeonameMatch>,
2096 }
2097
2098 let tests = [
2099 Test {
2100 query: "ia",
2101 match_name_prefix: false,
2102 filter: None,
2103 expected: vec![GeonameMatch {
2104 geoname: ia(),
2105 match_type: GeonameMatchType::Abbreviation,
2106 prefix: false,
2107 }],
2108 },
2109 Test {
2110 query: "ia",
2111 match_name_prefix: true,
2112 filter: None,
2113 expected: vec![GeonameMatch {
2114 geoname: ia(),
2115 match_type: GeonameMatchType::Abbreviation,
2116 prefix: false,
2117 }],
2118 },
2119 Test {
2120 query: "ia",
2121 match_name_prefix: false,
2122 filter: Some(vec![waterloo_ia(), waterloo_al()]),
2123 expected: vec![],
2124 },
2125 Test {
2126 query: "ia",
2127 match_name_prefix: false,
2128 filter: Some(vec![waterloo_ia()]),
2129 expected: vec![GeonameMatch {
2130 geoname: ia(),
2131 match_type: GeonameMatchType::Abbreviation,
2132 prefix: false,
2133 }],
2134 },
2135 Test {
2136 query: "ia",
2137 match_name_prefix: false,
2138 filter: Some(vec![us()]),
2139 expected: vec![GeonameMatch {
2140 geoname: ia(),
2141 match_type: GeonameMatchType::Abbreviation,
2142 prefix: false,
2143 }],
2144 },
2145 Test {
2146 query: "ia",
2147 match_name_prefix: false,
2148 filter: Some(vec![waterloo_al()]),
2149 expected: vec![],
2150 },
2151 Test {
2152 query: "ia",
2153 match_name_prefix: false,
2154 filter: Some(vec![canada()]),
2155 expected: vec![],
2156 },
2157 Test {
2158 query: "ia",
2159 match_name_prefix: false,
2160 filter: Some(vec![uk()]),
2161 expected: vec![],
2162 },
2163 Test {
2164 query: "iaxyz",
2165 match_name_prefix: false,
2166 filter: None,
2167 expected: vec![],
2168 },
2169 Test {
2170 query: "iaxyz",
2171 match_name_prefix: true,
2172 filter: None,
2173 expected: vec![],
2174 },
2175 Test {
2176 query: "iowa",
2177 match_name_prefix: false,
2178 filter: None,
2179 expected: vec![GeonameMatch {
2180 geoname: ia(),
2181 match_type: GeonameMatchType::Name,
2182 prefix: false,
2183 }],
2184 },
2185 Test {
2186 query: "al",
2187 match_name_prefix: false,
2188 filter: None,
2189 expected: vec![GeonameMatch {
2190 geoname: al(),
2191 match_type: GeonameMatchType::Abbreviation,
2192 prefix: false,
2193 }],
2194 },
2195 // "al" is both a name prefix and an abbreviation.
2196 Test {
2197 query: "al",
2198 match_name_prefix: true,
2199 filter: None,
2200 expected: vec![
2201 GeonameMatch {
2202 geoname: al(),
2203 match_type: GeonameMatchType::Name,
2204 prefix: true,
2205 },
2206 GeonameMatch {
2207 geoname: al(),
2208 match_type: GeonameMatchType::Abbreviation,
2209 prefix: false,
2210 },
2211 ],
2212 },
2213 Test {
2214 query: "waterloo",
2215 match_name_prefix: false,
2216 filter: Some(vec![ia()]),
2217 expected: vec![GeonameMatch {
2218 geoname: waterloo_ia(),
2219 match_type: GeonameMatchType::Name,
2220 prefix: false,
2221 }],
2222 },
2223 Test {
2224 query: "waterloo",
2225 match_name_prefix: false,
2226 filter: Some(vec![al()]),
2227 expected: vec![GeonameMatch {
2228 geoname: waterloo_al(),
2229 match_type: GeonameMatchType::Name,
2230 prefix: false,
2231 }],
2232 },
2233 Test {
2234 query: "waterloo",
2235 match_name_prefix: false,
2236 filter: Some(vec![ny_state()]),
2237 expected: vec![],
2238 },
2239 Test {
2240 query: "waterloo",
2241 match_name_prefix: false,
2242 filter: None,
2243 // Matches should be returned by population descending.
2244 expected: vec![
2245 GeonameMatch {
2246 geoname: waterloo_on(),
2247 match_type: GeonameMatchType::Name,
2248 prefix: false,
2249 },
2250 GeonameMatch {
2251 geoname: waterloo_ia(),
2252 match_type: GeonameMatchType::Name,
2253 prefix: false,
2254 },
2255 GeonameMatch {
2256 geoname: waterloo_al(),
2257 match_type: GeonameMatchType::Name,
2258 prefix: false,
2259 },
2260 ],
2261 },
2262 Test {
2263 query: "water",
2264 match_name_prefix: true,
2265 filter: None,
2266 expected: vec![
2267 GeonameMatch {
2268 geoname: waterloo_on(),
2269 match_type: GeonameMatchType::Name,
2270 prefix: true,
2271 },
2272 GeonameMatch {
2273 geoname: waterloo_ia(),
2274 match_type: GeonameMatchType::Name,
2275 prefix: true,
2276 },
2277 GeonameMatch {
2278 geoname: waterloo_al(),
2279 match_type: GeonameMatchType::Name,
2280 prefix: true,
2281 },
2282 ],
2283 },
2284 Test {
2285 query: "water",
2286 match_name_prefix: false,
2287 filter: None,
2288 expected: vec![],
2289 },
2290 Test {
2291 query: "waterloo",
2292 match_name_prefix: false,
2293 filter: Some(vec![us()]),
2294 expected: vec![
2295 GeonameMatch {
2296 geoname: waterloo_ia(),
2297 match_type: GeonameMatchType::Name,
2298 prefix: false,
2299 },
2300 GeonameMatch {
2301 geoname: waterloo_al(),
2302 match_type: GeonameMatchType::Name,
2303 prefix: false,
2304 },
2305 ],
2306 },
2307 Test {
2308 query: "waterloo",
2309 match_name_prefix: false,
2310 filter: Some(vec![al(), us()]),
2311 expected: vec![GeonameMatch {
2312 geoname: waterloo_al(),
2313 match_type: GeonameMatchType::Name,
2314 prefix: false,
2315 }],
2316 },
2317 Test {
2318 query: "waterloo",
2319 match_name_prefix: false,
2320 filter: Some(vec![us(), al()]),
2321 expected: vec![GeonameMatch {
2322 geoname: waterloo_al(),
2323 match_type: GeonameMatchType::Name,
2324 prefix: false,
2325 }],
2326 },
2327 Test {
2328 query: "waterloo",
2329 match_name_prefix: false,
2330 filter: Some(vec![ia(), al()]),
2331 expected: vec![],
2332 },
2333 Test {
2334 query: "waterloo",
2335 match_name_prefix: false,
2336 filter: Some(vec![canada()]),
2337 expected: vec![GeonameMatch {
2338 geoname: waterloo_on(),
2339 match_type: GeonameMatchType::Name,
2340 prefix: false,
2341 }],
2342 },
2343 Test {
2344 query: "waterloo",
2345 match_name_prefix: false,
2346 filter: Some(vec![on()]),
2347 expected: vec![GeonameMatch {
2348 geoname: waterloo_on(),
2349 match_type: GeonameMatchType::Name,
2350 prefix: false,
2351 }],
2352 },
2353 Test {
2354 query: "waterloo",
2355 match_name_prefix: false,
2356 filter: Some(vec![on(), canada()]),
2357 expected: vec![GeonameMatch {
2358 geoname: waterloo_on(),
2359 match_type: GeonameMatchType::Name,
2360 prefix: false,
2361 }],
2362 },
2363 Test {
2364 query: "waterloo",
2365 match_name_prefix: false,
2366 filter: Some(vec![canada(), on()]),
2367 expected: vec![GeonameMatch {
2368 geoname: waterloo_on(),
2369 match_type: GeonameMatchType::Name,
2370 prefix: false,
2371 }],
2372 },
2373 Test {
2374 query: "waterloo",
2375 match_name_prefix: false,
2376 filter: Some(vec![al(), canada()]),
2377 expected: vec![],
2378 },
2379 Test {
2380 query: "waterloo",
2381 match_name_prefix: false,
2382 filter: Some(vec![on(), us()]),
2383 expected: vec![],
2384 },
2385 Test {
2386 query: "waterloo",
2387 match_name_prefix: false,
2388 filter: Some(vec![waterloo_al()]),
2389 expected: vec![GeonameMatch {
2390 geoname: waterloo_al(),
2391 match_type: GeonameMatchType::Name,
2392 prefix: false,
2393 }],
2394 },
2395 Test {
2396 query: "waterloo",
2397 match_name_prefix: false,
2398 filter: Some(vec![uk()]),
2399 expected: vec![],
2400 },
2401 Test {
2402 query: "waterlooxyz",
2403 match_name_prefix: false,
2404 filter: None,
2405 expected: vec![],
2406 },
2407 Test {
2408 query: "waterlooxyz",
2409 match_name_prefix: true,
2410 filter: None,
2411 expected: vec![],
2412 },
2413 Test {
2414 query: "waterloo xyz",
2415 match_name_prefix: false,
2416 filter: None,
2417 expected: vec![],
2418 },
2419 Test {
2420 query: "waterloo xyz",
2421 match_name_prefix: true,
2422 filter: None,
2423 expected: vec![],
2424 },
2425 Test {
2426 query: "ny",
2427 match_name_prefix: false,
2428 filter: None,
2429 // NYC should be first since cities are ordered before regions.
2430 expected: vec![
2431 GeonameMatch {
2432 geoname: nyc(),
2433 match_type: GeonameMatchType::Abbreviation,
2434 prefix: false,
2435 },
2436 GeonameMatch {
2437 geoname: ny_state(),
2438 match_type: GeonameMatchType::Abbreviation,
2439 prefix: false,
2440 },
2441 ],
2442 },
2443 Test {
2444 query: "ny",
2445 match_name_prefix: false,
2446 filter: Some(vec![nyc()]),
2447 expected: vec![
2448 GeonameMatch {
2449 geoname: nyc(),
2450 match_type: GeonameMatchType::Abbreviation,
2451 prefix: false,
2452 },
2453 GeonameMatch {
2454 geoname: ny_state(),
2455 match_type: GeonameMatchType::Abbreviation,
2456 prefix: false,
2457 },
2458 ],
2459 },
2460 Test {
2461 query: "ny",
2462 match_name_prefix: false,
2463 filter: Some(vec![ny_state()]),
2464 expected: vec![
2465 GeonameMatch {
2466 geoname: nyc(),
2467 match_type: GeonameMatchType::Abbreviation,
2468 prefix: false,
2469 },
2470 GeonameMatch {
2471 geoname: ny_state(),
2472 match_type: GeonameMatchType::Abbreviation,
2473 prefix: false,
2474 },
2475 ],
2476 },
2477 Test {
2478 query: "nyc",
2479 match_name_prefix: false,
2480 filter: None,
2481 expected: vec![GeonameMatch {
2482 geoname: nyc(),
2483 match_type: GeonameMatchType::Abbreviation,
2484 prefix: false,
2485 }],
2486 },
2487 Test {
2488 query: "NeW YoRk",
2489 match_name_prefix: false,
2490 filter: None,
2491 expected: vec![
2492 GeonameMatch {
2493 geoname: nyc(),
2494 match_type: GeonameMatchType::Name,
2495 prefix: false,
2496 },
2497 GeonameMatch {
2498 geoname: ny_state(),
2499 match_type: GeonameMatchType::Name,
2500 prefix: false,
2501 },
2502 ],
2503 },
2504 Test {
2505 query: "NY",
2506 match_name_prefix: false,
2507 filter: None,
2508 expected: vec![
2509 GeonameMatch {
2510 geoname: nyc(),
2511 match_type: GeonameMatchType::Abbreviation,
2512 prefix: false,
2513 },
2514 GeonameMatch {
2515 geoname: ny_state(),
2516 match_type: GeonameMatchType::Abbreviation,
2517 prefix: false,
2518 },
2519 ],
2520 },
2521 Test {
2522 query: "new",
2523 match_name_prefix: false,
2524 filter: None,
2525 expected: vec![],
2526 },
2527 Test {
2528 query: "new",
2529 match_name_prefix: true,
2530 filter: None,
2531 expected: vec![
2532 GeonameMatch {
2533 geoname: nyc(),
2534 match_type: GeonameMatchType::Name,
2535 prefix: true,
2536 },
2537 GeonameMatch {
2538 geoname: new_orleans(),
2539 match_type: GeonameMatchType::Name,
2540 prefix: true,
2541 },
2542 GeonameMatch {
2543 geoname: ny_state(),
2544 match_type: GeonameMatchType::Name,
2545 prefix: true,
2546 },
2547 ],
2548 },
2549 Test {
2550 query: "new york foo",
2551 match_name_prefix: false,
2552 filter: None,
2553 expected: vec![],
2554 },
2555 Test {
2556 query: "new york foo",
2557 match_name_prefix: true,
2558 filter: None,
2559 expected: vec![],
2560 },
2561 Test {
2562 query: "new foo",
2563 match_name_prefix: true,
2564 filter: None,
2565 expected: vec![],
2566 },
2567 Test {
2568 query: "foo new york",
2569 match_name_prefix: false,
2570 filter: None,
2571 expected: vec![],
2572 },
2573 Test {
2574 query: "foo new york",
2575 match_name_prefix: true,
2576 filter: None,
2577 expected: vec![],
2578 },
2579 Test {
2580 query: "foo new",
2581 match_name_prefix: true,
2582 filter: None,
2583 expected: vec![],
2584 },
2585 Test {
2586 query: "roc",
2587 match_name_prefix: false,
2588 filter: None,
2589 expected: vec![GeonameMatch {
2590 geoname: rochester(),
2591 match_type: GeonameMatchType::AirportCode,
2592 prefix: false,
2593 }],
2594 },
2595 // "roc" is both a name prefix and an airport code.
2596 Test {
2597 query: "roc",
2598 match_name_prefix: true,
2599 filter: None,
2600 expected: vec![
2601 GeonameMatch {
2602 geoname: rochester(),
2603 match_type: GeonameMatchType::Name,
2604 prefix: true,
2605 },
2606 GeonameMatch {
2607 geoname: rochester(),
2608 match_type: GeonameMatchType::AirportCode,
2609 prefix: false,
2610 },
2611 ],
2612 },
2613 Test {
2614 query: "123 long name",
2615 match_name_prefix: false,
2616 filter: None,
2617 expected: vec![GeonameMatch {
2618 geoname: long_name_city(),
2619 match_type: GeonameMatchType::Name,
2620 prefix: false,
2621 }],
2622 },
2623 Test {
2624 query: LONG_NAME,
2625 match_name_prefix: false,
2626 filter: None,
2627 expected: vec![GeonameMatch {
2628 geoname: long_name_city(),
2629 match_type: GeonameMatchType::Name,
2630 prefix: false,
2631 }],
2632 },
2633 Test {
2634 query: "ac",
2635 match_name_prefix: false,
2636 filter: None,
2637 expected: vec![],
2638 },
2639 Test {
2640 query: "ac",
2641 match_name_prefix: true,
2642 filter: None,
2643 expected: vec![],
2644 },
2645 Test {
2646 query: "act",
2647 match_name_prefix: false,
2648 filter: None,
2649 expected: vec![GeonameMatch {
2650 geoname: waco(),
2651 match_type: GeonameMatchType::AirportCode,
2652 prefix: false,
2653 }],
2654 },
2655 Test {
2656 query: "act",
2657 match_name_prefix: true,
2658 filter: None,
2659 expected: vec![GeonameMatch {
2660 geoname: waco(),
2661 match_type: GeonameMatchType::AirportCode,
2662 prefix: false,
2663 }],
2664 },
2665 Test {
2666 query: "us",
2667 match_name_prefix: false,
2668 filter: None,
2669 expected: vec![GeonameMatch {
2670 geoname: us(),
2671 match_type: GeonameMatchType::Abbreviation,
2672 prefix: false,
2673 }],
2674 },
2675 Test {
2676 query: "us",
2677 match_name_prefix: false,
2678 filter: Some(vec![waterloo_ia()]),
2679 expected: vec![GeonameMatch {
2680 geoname: us(),
2681 match_type: GeonameMatchType::Abbreviation,
2682 prefix: false,
2683 }],
2684 },
2685 Test {
2686 query: "us",
2687 match_name_prefix: false,
2688 filter: Some(vec![ia()]),
2689 expected: vec![GeonameMatch {
2690 geoname: us(),
2691 match_type: GeonameMatchType::Abbreviation,
2692 prefix: false,
2693 }],
2694 },
2695 Test {
2696 query: "canada",
2697 match_name_prefix: false,
2698 filter: None,
2699 expected: vec![GeonameMatch {
2700 geoname: canada(),
2701 match_type: GeonameMatchType::Name,
2702 prefix: false,
2703 }],
2704 },
2705 Test {
2706 query: "canada",
2707 match_name_prefix: false,
2708 filter: Some(vec![on()]),
2709 expected: vec![GeonameMatch {
2710 geoname: canada(),
2711 match_type: GeonameMatchType::Name,
2712 prefix: false,
2713 }],
2714 },
2715 Test {
2716 query: "canada",
2717 match_name_prefix: false,
2718 filter: Some(vec![waterloo_on(), on()]),
2719 expected: vec![GeonameMatch {
2720 geoname: canada(),
2721 match_type: GeonameMatchType::Name,
2722 prefix: false,
2723 }],
2724 },
2725 Test {
2726 query: "uk",
2727 match_name_prefix: false,
2728 filter: None,
2729 expected: vec![
2730 // "UK" is listed as both an 'en' alternate and 'abbr'
2731 // alternate. The abbreviation should be first since 'abbr'
2732 // is ordered before 'en'.
2733 GeonameMatch {
2734 geoname: uk(),
2735 match_type: GeonameMatchType::Abbreviation,
2736 prefix: false,
2737 },
2738 GeonameMatch {
2739 geoname: uk(),
2740 match_type: GeonameMatchType::Name,
2741 prefix: false,
2742 },
2743 ],
2744 },
2745 Test {
2746 query: "st. louis",
2747 match_name_prefix: false,
2748 filter: None,
2749 expected: vec![GeonameMatch {
2750 geoname: st_louis(),
2751 match_type: GeonameMatchType::Name,
2752 prefix: false,
2753 }],
2754 },
2755 Test {
2756 query: "st louis",
2757 match_name_prefix: false,
2758 filter: None,
2759 expected: vec![GeonameMatch {
2760 geoname: st_louis(),
2761 match_type: GeonameMatchType::Name,
2762 prefix: false,
2763 }],
2764 },
2765 Test {
2766 query: "st.",
2767 match_name_prefix: true,
2768 filter: None,
2769 expected: vec![GeonameMatch {
2770 geoname: st_louis(),
2771 match_type: GeonameMatchType::Name,
2772 prefix: true,
2773 }],
2774 },
2775 Test {
2776 query: "st. l",
2777 match_name_prefix: true,
2778 filter: None,
2779 expected: vec![GeonameMatch {
2780 geoname: st_louis(),
2781 match_type: GeonameMatchType::Name,
2782 prefix: true,
2783 }],
2784 },
2785 Test {
2786 query: "st l",
2787 match_name_prefix: true,
2788 filter: None,
2789 expected: vec![GeonameMatch {
2790 geoname: st_louis(),
2791 match_type: GeonameMatchType::Name,
2792 prefix: true,
2793 }],
2794 },
2795 Test {
2796 query: "st.",
2797 match_name_prefix: false,
2798 filter: None,
2799 expected: vec![],
2800 },
2801 Test {
2802 query: "st l",
2803 match_name_prefix: false,
2804 filter: None,
2805 expected: vec![],
2806 },
2807 Test {
2808 query: "carmel-by-the-sea",
2809 match_name_prefix: false,
2810 filter: None,
2811 expected: vec![GeonameMatch {
2812 geoname: carmel(),
2813 match_type: GeonameMatchType::Name,
2814 prefix: false,
2815 }],
2816 },
2817 Test {
2818 query: "carmel by the sea",
2819 match_name_prefix: false,
2820 filter: None,
2821 expected: vec![GeonameMatch {
2822 geoname: carmel(),
2823 match_type: GeonameMatchType::Name,
2824 prefix: false,
2825 }],
2826 },
2827 Test {
2828 query: "carmel-",
2829 match_name_prefix: true,
2830 filter: None,
2831 expected: vec![GeonameMatch {
2832 geoname: carmel(),
2833 match_type: GeonameMatchType::Name,
2834 prefix: true,
2835 }],
2836 },
2837 Test {
2838 query: "carmel-b",
2839 match_name_prefix: true,
2840 filter: None,
2841 expected: vec![GeonameMatch {
2842 geoname: carmel(),
2843 match_type: GeonameMatchType::Name,
2844 prefix: true,
2845 }],
2846 },
2847 Test {
2848 query: "carmel b",
2849 match_name_prefix: true,
2850 filter: None,
2851 expected: vec![GeonameMatch {
2852 geoname: carmel(),
2853 match_type: GeonameMatchType::Name,
2854 prefix: true,
2855 }],
2856 },
2857 Test {
2858 query: "carmel-",
2859 match_name_prefix: false,
2860 filter: None,
2861 expected: vec![],
2862 },
2863 Test {
2864 query: "carmel-b",
2865 match_name_prefix: false,
2866 filter: None,
2867 expected: vec![],
2868 },
2869 Test {
2870 query: "carmel b",
2871 match_name_prefix: false,
2872 filter: None,
2873 expected: vec![],
2874 },
2875 Test {
2876 query: "liverpool",
2877 match_name_prefix: false,
2878 filter: None,
2879 expected: vec![
2880 GeonameMatch {
2881 geoname: liverpool_city(),
2882 match_type: GeonameMatchType::Name,
2883 prefix: false,
2884 },
2885 GeonameMatch {
2886 geoname: liverpool_metro(),
2887 match_type: GeonameMatchType::Name,
2888 prefix: false,
2889 },
2890 ],
2891 },
2892 Test {
2893 query: "liverpool",
2894 match_name_prefix: false,
2895 filter: Some(vec![liverpool_metro()]),
2896 expected: vec![
2897 GeonameMatch {
2898 geoname: liverpool_city(),
2899 match_type: GeonameMatchType::Name,
2900 prefix: false,
2901 },
2902 GeonameMatch {
2903 geoname: liverpool_metro(),
2904 match_type: GeonameMatchType::Name,
2905 prefix: false,
2906 },
2907 ],
2908 },
2909 Test {
2910 query: "liverpool",
2911 match_name_prefix: false,
2912 filter: Some(vec![england()]),
2913 expected: vec![
2914 GeonameMatch {
2915 geoname: liverpool_city(),
2916 match_type: GeonameMatchType::Name,
2917 prefix: false,
2918 },
2919 GeonameMatch {
2920 geoname: liverpool_metro(),
2921 match_type: GeonameMatchType::Name,
2922 prefix: false,
2923 },
2924 ],
2925 },
2926 Test {
2927 query: "liverpool",
2928 match_name_prefix: false,
2929 filter: Some(vec![uk()]),
2930 expected: vec![
2931 GeonameMatch {
2932 geoname: liverpool_city(),
2933 match_type: GeonameMatchType::Name,
2934 prefix: false,
2935 },
2936 GeonameMatch {
2937 geoname: liverpool_metro(),
2938 match_type: GeonameMatchType::Name,
2939 prefix: false,
2940 },
2941 ],
2942 },
2943 Test {
2944 query: "liverpool",
2945 match_name_prefix: false,
2946 filter: Some(vec![liverpool_metro(), england()]),
2947 expected: vec![
2948 GeonameMatch {
2949 geoname: liverpool_city(),
2950 match_type: GeonameMatchType::Name,
2951 prefix: false,
2952 },
2953 GeonameMatch {
2954 geoname: liverpool_metro(),
2955 match_type: GeonameMatchType::Name,
2956 prefix: false,
2957 },
2958 ],
2959 },
2960 Test {
2961 query: "liverpool",
2962 match_name_prefix: false,
2963 filter: Some(vec![liverpool_metro(), uk()]),
2964 expected: vec![
2965 GeonameMatch {
2966 geoname: liverpool_city(),
2967 match_type: GeonameMatchType::Name,
2968 prefix: false,
2969 },
2970 GeonameMatch {
2971 geoname: liverpool_metro(),
2972 match_type: GeonameMatchType::Name,
2973 prefix: false,
2974 },
2975 ],
2976 },
2977 Test {
2978 query: "liverpool",
2979 match_name_prefix: false,
2980 filter: Some(vec![england(), uk()]),
2981 expected: vec![
2982 GeonameMatch {
2983 geoname: liverpool_city(),
2984 match_type: GeonameMatchType::Name,
2985 prefix: false,
2986 },
2987 GeonameMatch {
2988 geoname: liverpool_metro(),
2989 match_type: GeonameMatchType::Name,
2990 prefix: false,
2991 },
2992 ],
2993 },
2994 Test {
2995 query: "liverpool",
2996 match_name_prefix: false,
2997 filter: Some(vec![liverpool_metro(), england(), uk()]),
2998 expected: vec![
2999 GeonameMatch {
3000 geoname: liverpool_city(),
3001 match_type: GeonameMatchType::Name,
3002 prefix: false,
3003 },
3004 GeonameMatch {
3005 geoname: liverpool_metro(),
3006 match_type: GeonameMatchType::Name,
3007 prefix: false,
3008 },
3009 ],
3010 },
3011 Test {
3012 query: "gößnitz",
3013 match_name_prefix: false,
3014 filter: None,
3015 expected: vec![GeonameMatch {
3016 geoname: goessnitz(),
3017 match_type: GeonameMatchType::Name,
3018 prefix: false,
3019 }],
3020 },
3021 Test {
3022 query: "gössnitz",
3023 match_name_prefix: false,
3024 filter: None,
3025 expected: vec![GeonameMatch {
3026 geoname: goessnitz(),
3027 match_type: GeonameMatchType::Name,
3028 prefix: false,
3029 }],
3030 },
3031 Test {
3032 query: "goßnitz",
3033 match_name_prefix: false,
3034 filter: None,
3035 expected: vec![GeonameMatch {
3036 geoname: goessnitz(),
3037 match_type: GeonameMatchType::Name,
3038 prefix: false,
3039 }],
3040 },
3041 Test {
3042 query: "gossnitz",
3043 match_name_prefix: false,
3044 filter: None,
3045 expected: vec![GeonameMatch {
3046 geoname: goessnitz(),
3047 match_type: GeonameMatchType::Name,
3048 prefix: false,
3049 }],
3050 },
3051 Test {
3052 query: "goessnitz",
3053 match_name_prefix: false,
3054 filter: None,
3055 expected: vec![GeonameMatch {
3056 geoname: goessnitz(),
3057 match_type: GeonameMatchType::Name,
3058 prefix: false,
3059 }],
3060 },
3061 Test {
3062 query: "gö",
3063 match_name_prefix: true,
3064 filter: None,
3065 expected: vec![GeonameMatch {
3066 geoname: goessnitz(),
3067 match_type: GeonameMatchType::Name,
3068 prefix: true,
3069 }],
3070 },
3071 Test {
3072 query: "göß",
3073 match_name_prefix: true,
3074 filter: None,
3075 expected: vec![GeonameMatch {
3076 geoname: goessnitz(),
3077 match_type: GeonameMatchType::Name,
3078 prefix: true,
3079 }],
3080 },
3081 Test {
3082 query: "gößn",
3083 match_name_prefix: true,
3084 filter: None,
3085 expected: vec![GeonameMatch {
3086 geoname: goessnitz(),
3087 match_type: GeonameMatchType::Name,
3088 prefix: true,
3089 }],
3090 },
3091 Test {
3092 query: "gös",
3093 match_name_prefix: true,
3094 filter: None,
3095 expected: vec![GeonameMatch {
3096 geoname: goessnitz(),
3097 match_type: GeonameMatchType::Name,
3098 prefix: true,
3099 }],
3100 },
3101 Test {
3102 query: "goß",
3103 match_name_prefix: true,
3104 filter: None,
3105 expected: vec![GeonameMatch {
3106 geoname: goessnitz(),
3107 match_type: GeonameMatchType::Name,
3108 prefix: true,
3109 }],
3110 },
3111 Test {
3112 query: "goßn",
3113 match_name_prefix: true,
3114 filter: None,
3115 expected: vec![GeonameMatch {
3116 geoname: goessnitz(),
3117 match_type: GeonameMatchType::Name,
3118 prefix: true,
3119 }],
3120 },
3121 Test {
3122 query: "gos",
3123 match_name_prefix: true,
3124 filter: None,
3125 expected: vec![GeonameMatch {
3126 geoname: goessnitz(),
3127 match_type: GeonameMatchType::Name,
3128 prefix: true,
3129 }],
3130 },
3131 Test {
3132 query: "goss",
3133 match_name_prefix: true,
3134 filter: None,
3135 expected: vec![GeonameMatch {
3136 geoname: goessnitz(),
3137 match_type: GeonameMatchType::Name,
3138 prefix: true,
3139 }],
3140 },
3141 ];
3142
3143 store.read(|dao| {
3144 for t in tests {
3145 let gs = t.filter.clone().unwrap_or_default();
3146 let gs_refs: Vec<_> = gs.iter().collect();
3147 let filters = if gs_refs.is_empty() {
3148 None
3149 } else {
3150 Some(gs_refs)
3151 };
3152 assert_eq!(
3153 dao.fetch_geonames(t.query, t.match_name_prefix, filters)?,
3154 t.expected,
3155 "query={:?} -- Full test: {:?}",
3156 t.query,
3157 t
3158 );
3159 }
3160 Ok(())
3161 })?;
3162
3163 Ok(())
3164 }
3165
3166 #[test]
3167 fn geonames_metrics() -> anyhow::Result<()> {
3168 before_each();
3169
3170 // Add a some records: a core geonames record and some alternates
3171 // records. The names in each should contribute to metrics.
3172 let mut store = TestStore::new(
3173 MockRemoteSettingsClient::default()
3174 .with_record(geoname_mock_record(
3175 "geonames-0",
3176 json!([
3177 {
3178 "id": 4096497,
3179 "name": "Waterloo",
3180 "feature_class": "P",
3181 "feature_code": "PPL",
3182 "country": "US",
3183 "admin1": "AL",
3184 "admin2": "077",
3185 "population": 200,
3186 "latitude": "34.91814",
3187 "longitude": "-88.0642",
3188 },
3189 ]),
3190 ))
3191 .with_record(geoname_alternates_mock_record(
3192 "geonames-alternates-0",
3193 json!({
3194 "language": "en",
3195 "alternates_by_geoname_id": [
3196 [4096497, ["a b c d e"]],
3197 ],
3198 }),
3199 ))
3200 .with_record(geoname_alternates_mock_record(
3201 "geonames-alternates-1",
3202 json!({
3203 "language": "en",
3204 "alternates_by_geoname_id": [
3205 [1, ["abcdefghik lmnopqrstu"]],
3206 ],
3207 }),
3208 )),
3209 );
3210
3211 // Ingest weather to also ingest geonames.
3212 store.ingest(SuggestIngestionConstraints {
3213 providers: Some(vec![SuggestionProvider::Weather]),
3214 ..SuggestIngestionConstraints::all_providers()
3215 });
3216
3217 store.read(|dao| {
3218 let cache = dao.geoname_cache();
3219 assert_eq!(cache.keywords_metrics.max_len, 21); // "abcdefghik lmnopqrstu"
3220 assert_eq!(cache.keywords_metrics.max_word_count, 5); // "a b c d e"
3221 Ok(())
3222 })?;
3223
3224 // Delete the first alternates record. The metrics should change.
3225 store
3226 .client_mut()
3227 .delete_record(geoname_mock_record("geonames-alternates-0", json!({})));
3228 store.ingest(SuggestIngestionConstraints {
3229 providers: Some(vec![SuggestionProvider::Weather]),
3230 ..SuggestIngestionConstraints::all_providers()
3231 });
3232 store.read(|dao| {
3233 let cache = dao.geoname_cache();
3234 assert_eq!(cache.keywords_metrics.max_len, 21); // "abcdefghik lmnopqrstu"
3235 assert_eq!(cache.keywords_metrics.max_word_count, 2); // "abcdefghik lmnopqrstu"
3236 Ok(())
3237 })?;
3238
3239 // Delete the second alternates record. The metrics should change again.
3240 store
3241 .client_mut()
3242 .delete_record(geoname_mock_record("geonames-alternates-1", json!({})));
3243 store.ingest(SuggestIngestionConstraints {
3244 providers: Some(vec![SuggestionProvider::Weather]),
3245 ..SuggestIngestionConstraints::all_providers()
3246 });
3247 store.read(|dao| {
3248 let cache = dao.geoname_cache();
3249 assert_eq!(cache.keywords_metrics.max_len, 8); // "waterloo"
3250 assert_eq!(cache.keywords_metrics.max_word_count, 1); // "waterloo"
3251 Ok(())
3252 })?;
3253
3254 // Add a new record. The metrics should change again.
3255 store
3256 .client_mut()
3257 .add_record(geoname_alternates_mock_record(
3258 "geonames-alternates-2",
3259 json!({
3260 "language": "en",
3261 "alternates_by_geoname_id": [
3262 [2, ["abcd efgh iklm"]],
3263 ],
3264 }),
3265 ));
3266 store.ingest(SuggestIngestionConstraints {
3267 providers: Some(vec![SuggestionProvider::Weather]),
3268 ..SuggestIngestionConstraints::all_providers()
3269 });
3270 store.read(|dao| {
3271 let cache = dao.geoname_cache();
3272 assert_eq!(cache.keywords_metrics.max_len, 14); // "abcd efgh iklm"
3273 assert_eq!(cache.keywords_metrics.max_word_count, 3); // "abcd efgh iklm"
3274 Ok(())
3275 })?;
3276
3277 Ok(())
3278 }
3279
3280 #[test]
3281 fn geonames_deleted_record() -> anyhow::Result<()> {
3282 before_each();
3283
3284 // Create the store with the test data and ingest.
3285 let mut store = new_test_store();
3286 store.ingest(SuggestIngestionConstraints {
3287 providers: Some(vec![SuggestionProvider::Weather]),
3288 ..SuggestIngestionConstraints::all_providers()
3289 });
3290
3291 // Make sure we have a match.
3292 store.read(|dao| {
3293 assert_eq!(
3294 dao.fetch_geonames("waterloo", false, None)?,
3295 vec![
3296 GeonameMatch {
3297 geoname: waterloo_on(),
3298 match_type: GeonameMatchType::Name,
3299 prefix: false,
3300 },
3301 GeonameMatch {
3302 geoname: waterloo_ia(),
3303 match_type: GeonameMatchType::Name,
3304 prefix: false,
3305 },
3306 GeonameMatch {
3307 geoname: waterloo_al(),
3308 match_type: GeonameMatchType::Name,
3309 prefix: false,
3310 },
3311 ],
3312 );
3313 Ok(())
3314 })?;
3315
3316 // Delete the record.
3317 store
3318 .client_mut()
3319 .delete_record(geoname_mock_record("geonames-0", json!({})));
3320 store.ingest(SuggestIngestionConstraints {
3321 providers: Some(vec![SuggestionProvider::Weather]),
3322 ..SuggestIngestionConstraints::all_providers()
3323 });
3324
3325 // The same query shouldn't match anymore and the tables should be
3326 // empty.
3327 store.read(|dao| {
3328 assert_eq!(dao.fetch_geonames("waterloo", false, None)?, vec![],);
3329
3330 let g_ids = dao.conn.query_rows_and_then(
3331 "SELECT id FROM geonames",
3332 [],
3333 |row| -> Result<GeonameId> { Ok(row.get("id")?) },
3334 )?;
3335 assert_eq!(g_ids, Vec::<GeonameId>::new());
3336
3337 let alt_g_ids = dao.conn.query_rows_and_then(
3338 "SELECT geoname_id FROM geonames_alternates",
3339 [],
3340 |row| -> Result<GeonameId> { Ok(row.get("geoname_id")?) },
3341 )?;
3342 assert_eq!(alt_g_ids, Vec::<GeonameId>::new());
3343
3344 Ok(())
3345 })?;
3346
3347 Ok(())
3348 }
3349
3350 #[test]
3351 fn geonames_reingest() -> anyhow::Result<()> {
3352 before_each();
3353
3354 // Create the store with the test data and ingest.
3355 let mut store = new_test_store();
3356 store.ingest(SuggestIngestionConstraints {
3357 providers: Some(vec![SuggestionProvider::Weather]),
3358 ..SuggestIngestionConstraints::all_providers()
3359 });
3360
3361 // Get the table counts.
3362 let (geonames_count, alternates_count) = store.read(|dao| {
3363 Ok((
3364 dao.conn.query_row_and_then(
3365 "SELECT count(*) FROM geonames",
3366 [],
3367 |row| -> Result<i64> { Ok(row.get(0)?) },
3368 )?,
3369 dao.conn.query_row_and_then(
3370 "SELECT count(*) FROM geonames_alternates",
3371 [],
3372 |row| -> Result<i64> { Ok(row.get(0)?) },
3373 )?,
3374 ))
3375 })?;
3376
3377 assert_ne!(geonames_count, 0);
3378 assert_ne!(alternates_count, 0);
3379
3380 // Delete the record and add a new record with a new ID that has the
3381 // same data.
3382 store
3383 .client_mut()
3384 .delete_record(geoname_mock_record("geonames-0", json!({})))
3385 .add_record(geoname_mock_record("geonames-1", geonames_data()));
3386
3387 // Ingest again.
3388 store.ingest(SuggestIngestionConstraints {
3389 providers: Some(vec![SuggestionProvider::Weather]),
3390 ..SuggestIngestionConstraints::all_providers()
3391 });
3392
3393 // Make sure we have a match.
3394 store.read(|dao| {
3395 assert_eq!(
3396 dao.fetch_geonames("waterloo", false, None)?,
3397 vec![
3398 GeonameMatch {
3399 geoname: waterloo_on(),
3400 match_type: GeonameMatchType::Name,
3401 prefix: false,
3402 },
3403 GeonameMatch {
3404 geoname: waterloo_ia(),
3405 match_type: GeonameMatchType::Name,
3406 prefix: false,
3407 },
3408 GeonameMatch {
3409 geoname: waterloo_al(),
3410 match_type: GeonameMatchType::Name,
3411 prefix: false,
3412 },
3413 ],
3414 );
3415 Ok(())
3416 })?;
3417
3418 // Get the table counts again. They should be the same as before.
3419 let (new_geonames_count, new_alternates_count) = store.read(|dao| {
3420 Ok((
3421 dao.conn.query_row_and_then(
3422 "SELECT count(*) FROM geonames",
3423 [],
3424 |row| -> Result<i64> { Ok(row.get(0)?) },
3425 )?,
3426 dao.conn.query_row_and_then(
3427 "SELECT count(*) FROM geonames_alternates",
3428 [],
3429 |row| -> Result<i64> { Ok(row.get(0)?) },
3430 )?,
3431 ))
3432 })?;
3433
3434 assert_eq!(geonames_count, new_geonames_count);
3435 assert_eq!(alternates_count, new_alternates_count);
3436
3437 Ok(())
3438 }
3439
3440 #[test]
3441 fn geonames_store_api() -> anyhow::Result<()> {
3442 before_each();
3443
3444 let store = new_test_store();
3445
3446 // Ingest weather to also ingest geonames.
3447 store.ingest(SuggestIngestionConstraints {
3448 providers: Some(vec![SuggestionProvider::Weather]),
3449 ..SuggestIngestionConstraints::all_providers()
3450 });
3451
3452 #[derive(Debug)]
3453 struct Test {
3454 query: &'static str,
3455 match_name_prefix: bool,
3456 filter: Option<Vec<Geoname>>,
3457 expected: Vec<GeonameMatch>,
3458 }
3459
3460 // This only tests a few different calls to exercise all the fetch
3461 // options. Comprehensive fetch cases are in the main `geonames` test.
3462 let tests = [
3463 // simple fetch with no options
3464 Test {
3465 query: "ia",
3466 match_name_prefix: false,
3467 filter: None,
3468 expected: vec![GeonameMatch {
3469 geoname: ia(),
3470 match_type: GeonameMatchType::Abbreviation,
3471 prefix: false,
3472 }],
3473 },
3474 // filter
3475 Test {
3476 query: "ia",
3477 match_name_prefix: false,
3478 filter: Some(vec![waterloo_ia()]),
3479 expected: vec![GeonameMatch {
3480 geoname: ia(),
3481 match_type: GeonameMatchType::Abbreviation,
3482 prefix: false,
3483 }],
3484 },
3485 // prefix matching
3486 Test {
3487 query: "ny",
3488 match_name_prefix: true,
3489 filter: None,
3490 expected: vec![
3491 GeonameMatch {
3492 geoname: nyc(),
3493 match_type: GeonameMatchType::Abbreviation,
3494 prefix: false,
3495 },
3496 GeonameMatch {
3497 geoname: ny_state(),
3498 match_type: GeonameMatchType::Abbreviation,
3499 prefix: false,
3500 },
3501 ],
3502 },
3503 ];
3504
3505 for t in tests {
3506 assert_eq!(
3507 store.fetch_geonames(t.query, t.match_name_prefix, t.filter.clone()),
3508 t.expected,
3509 "Test: {:?}",
3510 t
3511 );
3512 }
3513
3514 Ok(())
3515 }
3516 }