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