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