2 Functions for bringing auxiliary data in the database up-to-date.
6 from textwrap import dedent
8 from psycopg2 import sql as pysql
10 from nominatim.db.utils import execute_file
11 from nominatim.db.sql_preprocessor import SQLPreprocessor
12 from nominatim.version import NOMINATIM_VERSION
14 LOG = logging.getLogger()
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`.
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
28 rank_search = rank_address = ranks
31 for country in countries:
32 rows.append((country, key, value, rank_search, rank_address))
34 def load_address_levels(conn, table, levels):
35 """ Replace the `address_levels` table with the contents of `levels'.
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
43 _add_address_level_rows_from_entry(rows, entry)
45 with conn.cursor() as cur:
48 cur.execute("""CREATE TABLE {} (country_code varchar(2),
52 rank_address SMALLINT)""".format(table))
54 cur.execute_values(pysql.SQL("INSERT INTO {} VALUES %s")
55 .format(pysql.Identifier(table)), rows)
57 cur.execute('CREATE UNIQUE INDEX ON {} (country_code, class, type)'.format(table))
61 def load_address_levels_from_file(conn, config_file):
62 """ Replace the `address_levels` table with the contents of the config
65 with config_file.open('r') as fdesc:
66 load_address_levels(conn, 'address_levels', json.load(fdesc))
69 def create_functions(conn, config, enable_diff_updates=True, enable_debug=False):
70 """ (Re)create the PL/pgSQL functions.
72 sql = SQLPreprocessor(conn, config)
74 sql.run_sql_file(conn, 'functions.sql',
75 disable_diff_updates=not enable_diff_updates,
90 # constants needed by PHP scripts: PHP name, config name, type
92 ('Database_DSN', 'DATABASE_DSN', str),
93 ('Default_Language', 'DEFAULT_LANGUAGE', str),
94 ('Log_DB', 'LOG_DB', bool),
95 ('Log_File', 'LOG_FILE', str),
96 ('NoAccessControl', 'CORS_NOACCESSCONTROL', bool),
97 ('Places_Max_ID_count', 'LOOKUP_MAX_COUNT', int),
98 ('PolygonOutput_MaximumTypes', 'POLYGON_OUTPUT_MAX_TYPES', int),
99 ('Search_BatchMode', 'SEARCH_BATCH_MODE', bool),
100 ('Search_NameOnlySearchFrequencyThreshold', 'SEARCH_NAME_ONLY_THRESHOLD', str),
101 ('Use_US_Tiger_Data', 'USE_US_TIGER_DATA', bool),
102 ('MapIcon_URL', 'MAPICON_URL', str),
106 def import_wikipedia_articles(dsn, data_path, ignore_errors=False):
107 """ Replaces the wikipedia importance tables with new data.
108 The import is run in a single transaction so that the new data
109 is replace seemlessly.
111 Returns 0 if all was well and 1 if the importance file could not
112 be found. Throws an exception if there was an error reading the file.
114 datafile = data_path / 'wikimedia-importance.sql.gz'
116 if not datafile.exists():
120 DROP TABLE IF EXISTS "wikipedia_article";
121 DROP TABLE IF EXISTS "wikipedia_redirect"
124 execute_file(dsn, datafile, ignore_errors=ignore_errors,
125 pre_code=pre_code, post_code=post_code)
130 def recompute_importance(conn):
131 """ Recompute wikipedia links and importance for all entries in placex.
132 This is a long-running operations that must not be executed in
133 parallel with updates.
135 with conn.cursor() as cur:
136 cur.execute('ALTER TABLE placex DISABLE TRIGGER ALL')
138 UPDATE placex SET (wikipedia, importance) =
139 (SELECT wikipedia, importance
140 FROM compute_importance(extratags, country_code, osm_type, osm_id))
143 UPDATE placex s SET wikipedia = d.wikipedia, importance = d.importance
145 WHERE s.place_id = d.linked_place_id and d.wikipedia is not null
146 and (s.wikipedia is null or s.importance < d.importance);
149 cur.execute('ALTER TABLE placex ENABLE TRIGGER ALL')
153 def _quote_php_variable(var_type, config, conf_name):
155 return 'true' if config.get_bool(conf_name) else 'false'
158 return getattr(config, conf_name)
160 if not getattr(config, conf_name):
163 quoted = getattr(config, conf_name).replace("'", "\\'")
167 def setup_website(basedir, config, conn):
168 """ Create the website script stubs.
170 if not basedir.exists():
171 LOG.info('Creating website directory.')
174 template = dedent("""\
177 @define('CONST_Debug', $_GET['debug'] ?? false);
178 @define('CONST_LibDir', '{0}');
179 @define('CONST_TokenizerDir', '{2}');
180 @define('CONST_NominatimVersion', '{1[0]}.{1[1]}.{1[2]}-{1[3]}');
182 """.format(config.lib_dir.php, NOMINATIM_VERSION,
183 config.project_dir / 'tokenizer'))
185 for php_name, conf_name, var_type in PHP_CONST_DEFS:
186 varout = _quote_php_variable(var_type, config, conf_name)
188 template += f"@define('CONST_{php_name}', {varout});\n"
190 template += f"\nrequire_once('{config.lib_dir.php}/website/{{}}');\n"
192 search_name_table_exists = bool(conn and conn.table_exists('search_name'))
194 for script in WEBSITE_SCRIPTS:
195 if not search_name_table_exists and script == 'search.php':
196 (basedir / script).write_text(template.format('reverse-only-search.php'), 'utf-8')
198 (basedir / script).write_text(template.format(script), 'utf-8')