1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Functions for importing and managing static country information.
11 from io import StringIO
12 import psycopg2.extras
14 from nominatim.db import utils as db_utils
15 from nominatim.db.connection import connect
18 """ Caches country-specific properties from the configuration file.
25 def load(self, config):
26 """ Load the country properties from the configuration files,
27 if they are not loaded yet.
30 self._info = config.load_sub_configuration('country_settings.yaml')
31 # Convert languages into a list for simpler handling.
32 for prop in self._info.values():
33 if 'languages' not in prop:
34 prop['languages'] = []
35 elif not isinstance(prop['languages'], list):
36 prop['languages'] = [x.strip()
37 for x in prop['languages'].split(',')]
38 if 'names' not in prop:
39 prop['names']['name'] = {}
42 """ Return tuples of (country_code, property dict) as iterable.
44 return self._info.items()
47 _COUNTRY_INFO = _CountryInfo()
49 def setup_country_config(config):
50 """ Load country properties from the configuration file.
51 Needs to be called before using any other functions in this
54 _COUNTRY_INFO.load(config)
58 """ Iterate over country code and properties.
60 return _COUNTRY_INFO.items()
63 def setup_country_tables(dsn, sql_dir, ignore_partitions=False):
64 """ Create and populate the tables with basic static data that provides
65 the background for geocoding. Data is assumed to not yet exist.
67 db_utils.execute_file(dsn, sql_dir / 'country_osm_grid.sql.gz')
69 def add_prefix_to_keys(name, prefix):
70 return {prefix+k: v for k, v in name.items()}
72 params, country_names_data = [], ''
73 for ccode, props in _COUNTRY_INFO.items():
74 if ccode is not None and props is not None:
78 partition = props.get('partition')
79 lang = props['languages'][0] if len(props['languages']) == 1 else None
80 params.append((ccode, partition, lang))
82 name = add_prefix_to_keys(props.get('names').get('name'), 'name:')
83 name = json.dumps(name , ensure_ascii=False, separators=(', ', '=>'))
84 country_names_data += ccode + '\t' + name[1:-1] + '\n'
85 with connect(dsn) as conn:
86 with conn.cursor() as cur:
88 """ CREATE TABLE public.country_name (
89 country_code character varying(2),
91 derived_name public.hstore,
92 country_default_language_code text,
95 data = StringIO(country_names_data)
96 cur.copy_from(data, 'country_name', columns=('country_code', 'name'))
98 """ UPDATE country_name
99 SET partition = part, country_default_language_code = lang
100 FROM (VALUES %s) AS v (cc, part, lang)
101 WHERE country_code = v.cc""", params)
105 def create_country_names(conn, tokenizer, languages=None):
106 """ Add default country names to search index. `languages` is a comma-
107 separated list of language codes as used in OSM. If `languages` is not
108 empty then only name translations for the given languages are added
112 languages = languages.split(',')
114 def _include_key(key):
115 return key.startswith('name:') and \
116 key[5:] in languages or key[5:] == 'default'
118 with conn.cursor() as cur:
119 psycopg2.extras.register_hstore(cur)
120 cur.execute("""SELECT country_code, name FROM country_name
121 WHERE country_code is not null""")
123 with tokenizer.name_analyzer() as analyzer:
124 for code, name in cur:
125 names = {'countrycode': code}
127 names['short_name'] = 'UK'
129 names['short_name'] = 'United States'
131 # country names (only in languages as provided)
133 names.update(((k, v) for k, v in name.items() if _include_key(k)))
135 analyzer.add_country_names(code, names)