]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/refresh.py
add consistent SPDX copyright headers
[nominatim.git] / nominatim / tools / refresh.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Functions for bringing auxiliary data in the database up-to-date.
9 """
10 import logging
11 from textwrap import dedent
12 from pathlib import Path
13
14 from psycopg2 import sql as pysql
15
16 from nominatim.db.utils import execute_file
17 from nominatim.db.sql_preprocessor import SQLPreprocessor
18 from nominatim.version import NOMINATIM_VERSION
19
20 LOG = logging.getLogger()
21
22
23 def _add_address_level_rows_from_entry(rows, entry):
24     """ Converts a single entry from the JSON format for address rank
25         descriptions into a flat format suitable for inserting into a
26         PostgreSQL table and adds these lines to `rows`.
27     """
28     countries = entry.get('countries') or (None, )
29     for key, values in entry['tags'].items():
30         for value, ranks in values.items():
31             if isinstance(ranks, list):
32                 rank_search, rank_address = ranks
33             else:
34                 rank_search = rank_address = ranks
35             if not value:
36                 value = None
37             for country in countries:
38                 rows.append((country, key, value, rank_search, rank_address))
39
40 def load_address_levels(conn, table, levels):
41     """ Replace the `address_levels` table with the contents of `levels'.
42
43         A new table is created any previously existing table is dropped.
44         The table has the following columns:
45             country, class, type, rank_search, rank_address
46     """
47     rows = []
48     for entry in levels:
49         _add_address_level_rows_from_entry(rows, entry)
50
51     with conn.cursor() as cur:
52         cur.drop_table(table)
53
54         cur.execute("""CREATE TABLE {} (country_code varchar(2),
55                                         class TEXT,
56                                         type TEXT,
57                                         rank_search SMALLINT,
58                                         rank_address SMALLINT)""".format(table))
59
60         cur.execute_values(pysql.SQL("INSERT INTO {} VALUES %s")
61                            .format(pysql.Identifier(table)), rows)
62
63         cur.execute('CREATE UNIQUE INDEX ON {} (country_code, class, type)'.format(table))
64
65     conn.commit()
66
67
68 def load_address_levels_from_config(conn, config):
69     """ Replace the `address_levels` table with the content as
70         defined in the given configuration. Uses the parameter
71         NOMINATIM_ADDRESS_LEVEL_CONFIG to determine the location of the
72         configuration file.
73     """
74     cfg = config.load_sub_configuration('', config='ADDRESS_LEVEL_CONFIG')
75     load_address_levels(conn, 'address_levels', cfg)
76
77
78 def create_functions(conn, config, enable_diff_updates=True, enable_debug=False):
79     """ (Re)create the PL/pgSQL functions.
80     """
81     sql = SQLPreprocessor(conn, config)
82
83     sql.run_sql_file(conn, 'functions.sql',
84                      disable_diff_updates=not enable_diff_updates,
85                      debug=enable_debug)
86
87
88
89 WEBSITE_SCRIPTS = (
90     'deletable.php',
91     'details.php',
92     'lookup.php',
93     'polygons.php',
94     'reverse.php',
95     'search.php',
96     'status.php'
97 )
98
99 # constants needed by PHP scripts: PHP name, config name, type
100 PHP_CONST_DEFS = (
101     ('Database_DSN', 'DATABASE_DSN', str),
102     ('Default_Language', 'DEFAULT_LANGUAGE', str),
103     ('Log_DB', 'LOG_DB', bool),
104     ('Log_File', 'LOG_FILE', Path),
105     ('NoAccessControl', 'CORS_NOACCESSCONTROL', bool),
106     ('Places_Max_ID_count', 'LOOKUP_MAX_COUNT', int),
107     ('PolygonOutput_MaximumTypes', 'POLYGON_OUTPUT_MAX_TYPES', int),
108     ('Search_BatchMode', 'SEARCH_BATCH_MODE', bool),
109     ('Search_NameOnlySearchFrequencyThreshold', 'SEARCH_NAME_ONLY_THRESHOLD', str),
110     ('Use_US_Tiger_Data', 'USE_US_TIGER_DATA', bool),
111     ('MapIcon_URL', 'MAPICON_URL', str),
112 )
113
114
115 def import_wikipedia_articles(dsn, data_path, ignore_errors=False):
116     """ Replaces the wikipedia importance tables with new data.
117         The import is run in a single transaction so that the new data
118         is replace seemlessly.
119
120         Returns 0 if all was well and 1 if the importance file could not
121         be found. Throws an exception if there was an error reading the file.
122     """
123     datafile = data_path / 'wikimedia-importance.sql.gz'
124
125     if not datafile.exists():
126         return 1
127
128     pre_code = """BEGIN;
129                   DROP TABLE IF EXISTS "wikipedia_article";
130                   DROP TABLE IF EXISTS "wikipedia_redirect"
131                """
132     post_code = "COMMIT"
133     execute_file(dsn, datafile, ignore_errors=ignore_errors,
134                  pre_code=pre_code, post_code=post_code)
135
136     return 0
137
138
139 def recompute_importance(conn):
140     """ Recompute wikipedia links and importance for all entries in placex.
141         This is a long-running operations that must not be executed in
142         parallel with updates.
143     """
144     with conn.cursor() as cur:
145         cur.execute('ALTER TABLE placex DISABLE TRIGGER ALL')
146         cur.execute("""
147             UPDATE placex SET (wikipedia, importance) =
148                (SELECT wikipedia, importance
149                 FROM compute_importance(extratags, country_code, osm_type, osm_id))
150             """)
151         cur.execute("""
152             UPDATE placex s SET wikipedia = d.wikipedia, importance = d.importance
153              FROM placex d
154              WHERE s.place_id = d.linked_place_id and d.wikipedia is not null
155                    and (s.wikipedia is null or s.importance < d.importance);
156             """)
157
158         cur.execute('ALTER TABLE placex ENABLE TRIGGER ALL')
159     conn.commit()
160
161
162 def _quote_php_variable(var_type, config, conf_name):
163     if var_type == bool:
164         return 'true' if config.get_bool(conf_name) else 'false'
165
166     if var_type == int:
167         return getattr(config, conf_name)
168
169     if not getattr(config, conf_name):
170         return 'false'
171
172     if var_type == Path:
173         value = str(config.get_path(conf_name))
174     else:
175         value = getattr(config, conf_name)
176
177     quoted = value.replace("'", "\\'")
178     return f"'{quoted}'"
179
180
181 def setup_website(basedir, config, conn):
182     """ Create the website script stubs.
183     """
184     if not basedir.exists():
185         LOG.info('Creating website directory.')
186         basedir.mkdir()
187
188     template = dedent("""\
189                       <?php
190
191                       @define('CONST_Debug', $_GET['debug'] ?? false);
192                       @define('CONST_LibDir', '{0}');
193                       @define('CONST_TokenizerDir', '{2}');
194                       @define('CONST_NominatimVersion', '{1[0]}.{1[1]}.{1[2]}-{1[3]}');
195
196                       """.format(config.lib_dir.php, NOMINATIM_VERSION,
197                                  config.project_dir / 'tokenizer'))
198
199     for php_name, conf_name, var_type in PHP_CONST_DEFS:
200         varout = _quote_php_variable(var_type, config, conf_name)
201
202         template += f"@define('CONST_{php_name}', {varout});\n"
203
204     template += f"\nrequire_once('{config.lib_dir.php}/website/{{}}');\n"
205
206     search_name_table_exists = bool(conn and conn.table_exists('search_name'))
207
208     for script in WEBSITE_SCRIPTS:
209         if not search_name_table_exists and script == 'search.php':
210             (basedir / script).write_text(template.format('reverse-only-search.php'), 'utf-8')
211         else:
212             (basedir / script).write_text(template.format(script), 'utf-8')