]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/refresh.py
77eecf0457119c5d338af71c160659beca9f9a44
[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 from textwrap import dedent
7
8 from psycopg2.extras import execute_values
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 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
80 def create_functions(conn, config, sqllib_dir,
81                      enable_diff_updates=True, enable_debug=False):
82     """ (Re)create the PL/pgSQL functions.
83     """
84     sql = SQLPreprocessor(conn, config, sqllib_dir)
85
86     sql.run_sql_file(conn, 'functions.sql',
87                      disable_diff_updates=not enable_diff_updates,
88                      debug=enable_debug)
89
90
91
92 WEBSITE_SCRIPTS = (
93     'deletable.php',
94     'details.php',
95     'lookup.php',
96     'polygons.php',
97     'reverse.php',
98     'search.php',
99     'status.php'
100 )
101
102 # constants needed by PHP scripts: PHP name, config name, type
103 PHP_CONST_DEFS = (
104     ('Database_DSN', 'DATABASE_DSN', str),
105     ('Default_Language', 'DEFAULT_LANGUAGE', str),
106     ('Log_DB', 'LOG_DB', bool),
107     ('Log_File', 'LOG_FILE', str),
108     ('Max_Word_Frequency', 'MAX_WORD_FREQUENCY', int),
109     ('NoAccessControl', 'CORS_NOACCESSCONTROL', bool),
110     ('Places_Max_ID_count', 'LOOKUP_MAX_COUNT', int),
111     ('PolygonOutput_MaximumTypes', 'POLYGON_OUTPUT_MAX_TYPES', int),
112     ('Search_BatchMode', 'SEARCH_BATCH_MODE', bool),
113     ('Search_NameOnlySearchFrequencyThreshold', 'SEARCH_NAME_ONLY_THRESHOLD', str),
114     ('Term_Normalization_Rules', 'TERM_NORMALIZATION', str),
115     ('Use_Aux_Location_data', 'USE_AUX_LOCATION_DATA', bool),
116     ('Use_US_Tiger_Data', 'USE_US_TIGER_DATA', bool),
117     ('MapIcon_URL', 'MAPICON_URL', str),
118 )
119
120
121 def import_wikipedia_articles(dsn, data_path, ignore_errors=False):
122     """ Replaces the wikipedia importance tables with new data.
123         The import is run in a single transaction so that the new data
124         is replace seemlessly.
125
126         Returns 0 if all was well and 1 if the importance file could not
127         be found. Throws an exception if there was an error reading the file.
128     """
129     datafile = data_path / 'wikimedia-importance.sql.gz'
130
131     if not datafile.exists():
132         return 1
133
134     pre_code = """BEGIN;
135                   DROP TABLE IF EXISTS "wikipedia_article";
136                   DROP TABLE IF EXISTS "wikipedia_redirect"
137                """
138     post_code = "COMMIT"
139     execute_file(dsn, datafile, ignore_errors=ignore_errors,
140                  pre_code=pre_code, post_code=post_code)
141
142     return 0
143
144
145 def recompute_importance(conn):
146     """ Recompute wikipedia links and importance for all entries in placex.
147         This is a long-running operations that must not be executed in
148         parallel with updates.
149     """
150     with conn.cursor() as cur:
151         cur.execute('ALTER TABLE placex DISABLE TRIGGER ALL')
152         cur.execute("""
153             UPDATE placex SET (wikipedia, importance) =
154                (SELECT wikipedia, importance
155                 FROM compute_importance(extratags, country_code, osm_type, osm_id))
156             """)
157         cur.execute("""
158             UPDATE placex s SET wikipedia = d.wikipedia, importance = d.importance
159              FROM placex d
160              WHERE s.place_id = d.linked_place_id and d.wikipedia is not null
161                    and (s.wikipedia is null or s.importance < d.importance);
162             """)
163
164         cur.execute('ALTER TABLE placex ENABLE TRIGGER ALL')
165     conn.commit()
166
167
168 def setup_website(basedir, phplib_dir, config):
169     """ Create the website script stubs.
170     """
171     if not basedir.exists():
172         LOG.info('Creating website directory.')
173         basedir.mkdir()
174
175     template = dedent("""\
176                       <?php
177
178                       @define('CONST_Debug', $_GET['debug'] ?? false);
179                       @define('CONST_LibDir', '{0}');
180                       @define('CONST_NominatimVersion', '{1[0]}.{1[1]}.{1[2]}-{1[3]}');
181
182                       """.format(phplib_dir, NOMINATIM_VERSION))
183
184     for php_name, conf_name, var_type in PHP_CONST_DEFS:
185         if var_type == bool:
186             varout = 'true' if config.get_bool(conf_name) else 'false'
187         elif var_type == int:
188             varout = getattr(config, conf_name)
189         elif not getattr(config, conf_name):
190             varout = 'false'
191         else:
192             varout = "'{}'".format(getattr(config, conf_name).replace("'", "\\'"))
193
194         template += "@define('CONST_{}', {});\n".format(php_name, varout)
195
196     template += "\nrequire_once('{}/website/{{}}');\n".format(phplib_dir)
197
198     for script in WEBSITE_SCRIPTS:
199         (basedir / script).write_text(template.format(script), 'utf-8')