]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/refresh.py
5cfa1ab00e92a46d941bd1c55a3d7effbf6d38f1
[nominatim.git] / nominatim / tools / refresh.py
1 """
2 Functions for bringing auxiliary data in the database up-to-date.
3 """
4 import json
5 import logging
6 import re
7 from textwrap import dedent
8
9 from psycopg2.extras import execute_values
10
11 from ..db.utils import execute_file
12 from ..version import NOMINATIM_VERSION
13
14 LOG = logging.getLogger()
15
16 def update_postcodes(dsn, sql_dir):
17     """ Recalculate postcode centroids and add, remove and update entries in the
18         location_postcode table. `conn` is an opne connection to the database.
19     """
20     execute_file(dsn, sql_dir / 'update-postcodes.sql')
21
22
23 def recompute_word_counts(dsn, sql_dir):
24     """ Compute the frequency of full-word search terms.
25     """
26     execute_file(dsn, sql_dir / 'words_from_search_name.sql')
27
28
29 def _add_address_level_rows_from_entry(rows, entry):
30     """ Converts a single entry from the JSON format for address rank
31         descriptions into a flat format suitable for inserting into a
32         PostgreSQL table and adds these lines to `rows`.
33     """
34     countries = entry.get('countries') or (None, )
35     for key, values in entry['tags'].items():
36         for value, ranks in values.items():
37             if isinstance(ranks, list):
38                 rank_search, rank_address = ranks
39             else:
40                 rank_search = rank_address = ranks
41             if not value:
42                 value = None
43             for country in countries:
44                 rows.append((country, key, value, rank_search, rank_address))
45
46 def load_address_levels(conn, table, levels):
47     """ Replace the `address_levels` table with the contents of `levels'.
48
49         A new table is created any previously existing table is dropped.
50         The table has the following columns:
51             country, class, type, rank_search, rank_address
52     """
53     rows = []
54     for entry in levels:
55         _add_address_level_rows_from_entry(rows, entry)
56
57     with conn.cursor() as cur:
58         cur.execute('DROP TABLE IF EXISTS {}'.format(table))
59
60         cur.execute("""CREATE TABLE {} (country_code varchar(2),
61                                         class TEXT,
62                                         type TEXT,
63                                         rank_search SMALLINT,
64                                         rank_address SMALLINT)""".format(table))
65
66         execute_values(cur, "INSERT INTO {} VALUES %s".format(table), rows)
67
68         cur.execute('CREATE UNIQUE INDEX ON {} (country_code, class, type)'.format(table))
69
70     conn.commit()
71
72 def load_address_levels_from_file(conn, config_file):
73     """ Replace the `address_levels` table with the contents of the config
74         file.
75     """
76     with config_file.open('r') as fdesc:
77         load_address_levels(conn, 'address_levels', json.load(fdesc))
78
79 PLPGSQL_BASE_MODULES = (
80     'utils.sql',
81     'normalization.sql',
82     'ranking.sql',
83     'importance.sql',
84     'address_lookup.sql',
85     'interpolation.sql'
86 )
87
88 PLPGSQL_TABLE_MODULES = (
89     ('place', 'place_triggers.sql'),
90     ('placex', 'placex_triggers.sql'),
91     ('location_postcode', 'postcode_triggers.sql')
92 )
93
94 def _get_standard_function_sql(conn, config, sql_dir, enable_diff_updates, enable_debug):
95     """ Read all applicable SQLs containing PL/pgSQL functions, replace
96         placefolders and execute them.
97     """
98     sql_func_dir = sql_dir / 'functions'
99     sql = ''
100
101     # Get the basic set of functions that is always imported.
102     for sql_file in PLPGSQL_BASE_MODULES:
103         with (sql_func_dir / sql_file).open('r') as fdesc:
104             sql += fdesc.read()
105
106     # Some files require the presence of a certain table
107     for table, fname in PLPGSQL_TABLE_MODULES:
108         if conn.table_exists(table):
109             with (sql_func_dir / fname).open('r') as fdesc:
110                 sql += fdesc.read()
111
112     # Replace placeholders.
113     sql = sql.replace('{modulepath}',
114                       config.DATABASE_MODULE_PATH or str((config.project_dir / 'module').resolve()))
115
116     if enable_diff_updates:
117         sql = sql.replace('RETURN NEW; -- %DIFFUPDATES%', '--')
118
119     if enable_debug:
120         sql = sql.replace('--DEBUG:', '')
121
122     if config.get_bool('LIMIT_REINDEXING'):
123         sql = sql.replace('--LIMIT INDEXING:', '')
124
125     if not config.get_bool('USE_US_TIGER_DATA'):
126         sql = sql.replace('-- %NOTIGERDATA% ', '')
127
128     if not config.get_bool('USE_AUX_LOCATION_DATA'):
129         sql = sql.replace('-- %NOAUXDATA% ', '')
130
131     reverse_only = 'false' if conn.table_exists('search_name') else 'true'
132
133     return sql.replace('%REVERSE-ONLY%', reverse_only)
134
135
136 def replace_partition_string(sql, partitions):
137     """ Replace a partition template with the actual partition code.
138     """
139     for match in re.findall('^-- start(.*?)^-- end', sql, re.M | re.S):
140         repl = ''
141         for part in partitions:
142             repl += match.replace('-partition-', str(part))
143         sql = sql.replace(match, repl)
144
145     return sql
146
147 def _get_partition_function_sql(conn, sql_dir):
148     """ Create functions that work on partition tables.
149     """
150     with conn.cursor() as cur:
151         cur.execute('SELECT distinct partition FROM country_name')
152         partitions = set([0])
153         for row in cur:
154             partitions.add(row[0])
155
156     with (sql_dir / 'partition-functions.src.sql').open('r') as fdesc:
157         sql = fdesc.read()
158
159     return replace_partition_string(sql, sorted(partitions))
160
161 def create_functions(conn, config, sql_dir,
162                      enable_diff_updates=True, enable_debug=False):
163     """ (Re)create the PL/pgSQL functions.
164     """
165     sql = _get_standard_function_sql(conn, config, sql_dir,
166                                      enable_diff_updates, enable_debug)
167     sql += _get_partition_function_sql(conn, sql_dir)
168
169     with conn.cursor() as cur:
170         cur.execute(sql)
171
172     conn.commit()
173
174
175 WEBSITE_SCRIPTS = (
176     'deletable.php',
177     'details.php',
178     'lookup.php',
179     'polygons.php',
180     'reverse.php',
181     'search.php',
182     'status.php'
183 )
184
185 # constants needed by PHP scripts: PHP name, config name, type
186 PHP_CONST_DEFS = (
187     ('Database_DSN', 'DATABASE_DSN', str),
188     ('Default_Language', 'DEFAULT_LANGUAGE', str),
189     ('Log_DB', 'LOG_DB', bool),
190     ('Log_File', 'LOG_FILE', str),
191     ('Max_Word_Frequency', 'MAX_WORD_FREQUENCY', int),
192     ('NoAccessControl', 'CORS_NOACCESSCONTROL', bool),
193     ('Places_Max_ID_count', 'LOOKUP_MAX_COUNT', int),
194     ('PolygonOutput_MaximumTypes', 'POLYGON_OUTPUT_MAX_TYPES', int),
195     ('Search_BatchMode', 'SEARCH_BATCH_MODE', bool),
196     ('Search_NameOnlySearchFrequencyThreshold', 'SEARCH_NAME_ONLY_THRESHOLD', str),
197     ('Term_Normalization_Rules', 'TERM_NORMALIZATION', str),
198     ('Use_Aux_Location_data', 'USE_AUX_LOCATION_DATA', bool),
199     ('Use_US_Tiger_Data', 'USE_US_TIGER_DATA', bool),
200     ('MapIcon_URL', 'MAPICON_URL', str),
201 )
202
203
204 def import_wikipedia_articles(dsn, data_path, ignore_errors=False):
205     """ Replaces the wikipedia importance tables with new data.
206         The import is run in a single transaction so that the new data
207         is replace seemlessly.
208
209         Returns 0 if all was well and 1 if the importance file could not
210         be found. Throws an exception if there was an error reading the file.
211     """
212     datafile = data_path / 'wikimedia-importance.sql.gz'
213
214     if not datafile.exists():
215         return 1
216
217     pre_code = """BEGIN;
218                   DROP TABLE IF EXISTS "wikipedia_article";
219                   DROP TABLE IF EXISTS "wikipedia_redirect"
220                """
221     post_code = "COMMIT"
222     execute_file(dsn, datafile, ignore_errors=ignore_errors,
223                  pre_code=pre_code, post_code=post_code)
224
225     return 0
226
227
228 def recompute_importance(conn):
229     """ Recompute wikipedia links and importance for all entries in placex.
230         This is a long-running operations that must not be executed in
231         parallel with updates.
232     """
233     with conn.cursor() as cur:
234         cur.execute('ALTER TABLE placex DISABLE TRIGGER ALL')
235         cur.execute("""
236             UPDATE placex SET (wikipedia, importance) =
237                (SELECT wikipedia, importance
238                 FROM compute_importance(extratags, country_code, osm_type, osm_id))
239             """)
240         cur.execute("""
241             UPDATE placex s SET wikipedia = d.wikipedia, importance = d.importance
242              FROM placex d
243              WHERE s.place_id = d.linked_place_id and d.wikipedia is not null
244                    and (s.wikipedia is null or s.importance < d.importance);
245             """)
246
247         cur.execute('ALTER TABLE placex ENABLE TRIGGER ALL')
248     conn.commit()
249
250
251 def setup_website(basedir, phplib_dir, config):
252     """ Create the website script stubs.
253     """
254     if not basedir.exists():
255         LOG.info('Creating website directory.')
256         basedir.mkdir()
257
258     template = dedent("""\
259                       <?php
260
261                       @define('CONST_Debug', $_GET['debug'] ?? false);
262                       @define('CONST_LibDir', '{0}');
263                       @define('CONST_NominatimVersion', '{1[0]}.{1[1]}.{1[2]}-{1[3]}');
264
265                       """.format(phplib_dir, NOMINATIM_VERSION))
266
267     for php_name, conf_name, var_type in PHP_CONST_DEFS:
268         if var_type == bool:
269             varout = 'true' if config.get_bool(conf_name) else 'false'
270         elif var_type == int:
271             varout = getattr(config, conf_name)
272         elif not getattr(config, conf_name):
273             varout = 'false'
274         else:
275             varout = "'{}'".format(getattr(config, conf_name).replace("'", "\\'"))
276
277         template += "@define('CONST_{}', {});\n".format(php_name, varout)
278
279     template += "\nrequire_once('{}/website/{{}}');\n".format(phplib_dir)
280
281     for script in WEBSITE_SCRIPTS:
282         (basedir / script).write_text(template.format(script), 'utf-8')