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