]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/migration.py
Merge remote-tracking branch 'upstream/master'
[nominatim.git] / nominatim / tools / migration.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Functions for database migration to newer software versions.
9 """
10 from typing import List, Tuple, Callable, Any
11 import logging
12
13 from psycopg2 import sql as pysql
14
15 from nominatim.config import Configuration
16 from nominatim.db import properties
17 from nominatim.db.connection import connect, Connection
18 from nominatim.version import NominatimVersion, NOMINATIM_VERSION, parse_version
19 from nominatim.tools import refresh
20 from nominatim.tokenizer import factory as tokenizer_factory
21 from nominatim.errors import UsageError
22
23 LOG = logging.getLogger()
24
25 _MIGRATION_FUNCTIONS : List[Tuple[NominatimVersion, Callable[..., None]]] = []
26
27 def migrate(config: Configuration, paths: Any) -> int:
28     """ Check for the current database version and execute migrations,
29         if necesssary.
30     """
31     with connect(config.get_libpq_dsn()) as conn:
32         if conn.table_exists('nominatim_properties'):
33             db_version_str = properties.get_property(conn, 'database_version')
34         else:
35             db_version_str = None
36
37         if db_version_str is not None:
38             db_version = parse_version(db_version_str)
39
40             if db_version == NOMINATIM_VERSION:
41                 LOG.warning("Database already at latest version (%s)", db_version_str)
42                 return 0
43
44             LOG.info("Detected database version: %s", db_version_str)
45         else:
46             db_version = _guess_version(conn)
47
48
49         has_run_migration = False
50         for version, func in _MIGRATION_FUNCTIONS:
51             if db_version < version or \
52                (db_version == (3, 5, 0, 99) and version == (3, 5, 0, 99)):
53                 title = func.__doc__ or ''
54                 LOG.warning("Running: %s (%s)", title.split('\n', 1)[0], version)
55                 kwargs = dict(conn=conn, config=config, paths=paths)
56                 func(**kwargs)
57                 conn.commit()
58                 has_run_migration = True
59
60         if has_run_migration:
61             LOG.warning('Updating SQL functions.')
62             refresh.create_functions(conn, config)
63             tokenizer = tokenizer_factory.get_tokenizer_for_db(config)
64             tokenizer.update_sql_functions(config)
65
66         properties.set_property(conn, 'database_version', str(NOMINATIM_VERSION))
67
68         conn.commit()
69
70     return 0
71
72
73 def _guess_version(conn: Connection) -> NominatimVersion:
74     """ Guess a database version when there is no property table yet.
75         Only migrations for 3.6 and later are supported, so bail out
76         when the version seems older.
77     """
78     with conn.cursor() as cur:
79         # In version 3.6, the country_name table was updated. Check for that.
80         cnt = cur.scalar("""SELECT count(*) FROM
81                             (SELECT svals(name) FROM  country_name
82                              WHERE country_code = 'gb')x;
83                          """)
84         if cnt < 100:
85             LOG.fatal('It looks like your database was imported with a version '
86                       'prior to 3.6.0. Automatic migration not possible.')
87             raise UsageError('Migration not possible.')
88
89     return NominatimVersion(3, 5, 0, 99)
90
91
92
93 def _migration(major: int, minor: int, patch: int = 0,
94                dbpatch: int = 0) -> Callable[[Callable[..., None]], Callable[..., None]]:
95     """ Decorator for a single migration step. The parameters describe the
96         version after which the migration is applicable, i.e before changing
97         from the given version to the next, the migration is required.
98
99         All migrations are run in the order in which they are defined in this
100         file. Do not run global SQL scripts for migrations as you cannot be sure
101         that these scripts do the same in later versions.
102
103         Functions will always be reimported in full at the end of the migration
104         process, so the migration functions may leave a temporary state behind
105         there.
106     """
107     def decorator(func: Callable[..., None]) -> Callable[..., None]:
108         version = NominatimVersion(major, minor, patch, dbpatch)
109         _MIGRATION_FUNCTIONS.append((version, func))
110         return func
111
112     return decorator
113
114
115 @_migration(3, 5, 0, 99)
116 def import_status_timestamp_change(conn: Connection, **_: Any) -> None:
117     """ Add timezone to timestamp in status table.
118
119         The import_status table has been changed to include timezone information
120         with the time stamp.
121     """
122     with conn.cursor() as cur:
123         cur.execute("""ALTER TABLE import_status ALTER COLUMN lastimportdate
124                        TYPE timestamp with time zone;""")
125
126
127 @_migration(3, 5, 0, 99)
128 def add_nominatim_property_table(conn: Connection, config: Configuration, **_: Any) -> None:
129     """ Add nominatim_property table.
130     """
131     if not conn.table_exists('nominatim_properties'):
132         with conn.cursor() as cur:
133             cur.execute(pysql.SQL("""CREATE TABLE nominatim_properties (
134                                         property TEXT,
135                                         value TEXT);
136                                      GRANT SELECT ON TABLE nominatim_properties TO {};
137                                   """).format(pysql.Identifier(config.DATABASE_WEBUSER)))
138
139 @_migration(3, 6, 0, 0)
140 def change_housenumber_transliteration(conn: Connection, **_: Any) -> None:
141     """ Transliterate housenumbers.
142
143         The database schema switched from saving raw housenumbers in
144         placex.housenumber to saving transliterated ones.
145
146         Note: the function create_housenumber_id() has been dropped in later
147               versions.
148     """
149     with conn.cursor() as cur:
150         cur.execute("""CREATE OR REPLACE FUNCTION create_housenumber_id(housenumber TEXT)
151                        RETURNS TEXT AS $$
152                        DECLARE
153                          normtext TEXT;
154                        BEGIN
155                          SELECT array_to_string(array_agg(trans), ';')
156                            INTO normtext
157                            FROM (SELECT lookup_word as trans,
158                                         getorcreate_housenumber_id(lookup_word)
159                                  FROM (SELECT make_standard_name(h) as lookup_word
160                                        FROM regexp_split_to_table(housenumber, '[,;]') h) x) y;
161                          return normtext;
162                        END;
163                        $$ LANGUAGE plpgsql STABLE STRICT;""")
164         cur.execute("DELETE FROM word WHERE class = 'place' and type = 'house'")
165         cur.execute("""UPDATE placex
166                        SET housenumber = create_housenumber_id(housenumber)
167                        WHERE housenumber is not null""")
168
169
170 @_migration(3, 7, 0, 0)
171 def switch_placenode_geometry_index(conn: Connection, **_: Any) -> None:
172     """ Replace idx_placex_geometry_reverse_placeNode index.
173
174         Make the index slightly more permissive, so that it can also be used
175         when matching up boundaries and place nodes. It makes the index
176         idx_placex_adminname index unnecessary.
177     """
178     with conn.cursor() as cur:
179         cur.execute(""" CREATE INDEX IF NOT EXISTS idx_placex_geometry_placenode ON placex
180                         USING GIST (geometry)
181                         WHERE osm_type = 'N' and rank_search < 26
182                               and class = 'place' and type != 'postcode'
183                               and linked_place_id is null""")
184         cur.execute(""" DROP INDEX IF EXISTS idx_placex_adminname """)
185
186
187 @_migration(3, 7, 0, 1)
188 def install_legacy_tokenizer(conn: Connection, config: Configuration, **_: Any) -> None:
189     """ Setup legacy tokenizer.
190
191         If no other tokenizer has been configured yet, then create the
192         configuration for the backwards-compatible legacy tokenizer
193     """
194     if properties.get_property(conn, 'tokenizer') is None:
195         with conn.cursor() as cur:
196             for table in ('placex', 'location_property_osmline'):
197                 has_column = cur.scalar("""SELECT count(*) FROM information_schema.columns
198                                            WHERE table_name = %s
199                                            and column_name = 'token_info'""",
200                                         (table, ))
201                 if has_column == 0:
202                     cur.execute(pysql.SQL('ALTER TABLE {} ADD COLUMN token_info JSONB')
203                                 .format(pysql.Identifier(table)))
204         tokenizer = tokenizer_factory.create_tokenizer(config, init_db=False,
205                                                        module_name='legacy')
206
207         tokenizer.migrate_database(config) # type: ignore[attr-defined]
208
209
210 @_migration(4, 0, 99, 0)
211 def create_tiger_housenumber_index(conn: Connection, **_: Any) -> None:
212     """ Create idx_location_property_tiger_parent_place_id with included
213         house number.
214
215         The inclusion is needed for efficient lookup of housenumbers in
216         full address searches.
217     """
218     if conn.server_version_tuple() >= (11, 0, 0):
219         with conn.cursor() as cur:
220             cur.execute(""" CREATE INDEX IF NOT EXISTS
221                                 idx_location_property_tiger_housenumber_migrated
222                             ON location_property_tiger
223                             USING btree(parent_place_id)
224                             INCLUDE (startnumber, endnumber) """)
225
226
227 @_migration(4, 0, 99, 1)
228 def create_interpolation_index_on_place(conn: Connection, **_: Any) -> None:
229     """ Create idx_place_interpolations for lookup of interpolation lines
230         on updates.
231     """
232     with conn.cursor() as cur:
233         cur.execute("""CREATE INDEX IF NOT EXISTS idx_place_interpolations
234                        ON place USING gist(geometry)
235                        WHERE osm_type = 'W' and address ? 'interpolation'""")
236
237
238 @_migration(4, 0, 99, 2)
239 def add_step_column_for_interpolation(conn: Connection, **_: Any) -> None:
240     """ Add a new column 'step' to the interpolations table.
241
242         Also converts the data into the stricter format which requires that
243         startnumbers comply with the odd/even requirements.
244     """
245     if conn.table_has_column('location_property_osmline', 'step'):
246         return
247
248     with conn.cursor() as cur:
249         # Mark invalid all interpolations with no intermediate numbers.
250         cur.execute("""UPDATE location_property_osmline SET startnumber = null
251                        WHERE endnumber - startnumber <= 1 """)
252         # Align the start numbers where odd/even does not match.
253         cur.execute("""UPDATE location_property_osmline
254                        SET startnumber = startnumber + 1,
255                            linegeo = ST_LineSubString(linegeo,
256                                                       1.0 / (endnumber - startnumber)::float,
257                                                       1)
258                        WHERE (interpolationtype = 'odd' and startnumber % 2 = 0)
259                               or (interpolationtype = 'even' and startnumber % 2 = 1)
260                     """)
261         # Mark invalid odd/even interpolations with no intermediate numbers.
262         cur.execute("""UPDATE location_property_osmline SET startnumber = null
263                        WHERE interpolationtype in ('odd', 'even')
264                              and endnumber - startnumber = 2""")
265         # Finally add the new column and populate it.
266         cur.execute("ALTER TABLE location_property_osmline ADD COLUMN step SMALLINT")
267         cur.execute("""UPDATE location_property_osmline
268                          SET step = CASE WHEN interpolationtype = 'all'
269                                          THEN 1 ELSE 2 END
270                     """)
271
272
273 @_migration(4, 0, 99, 3)
274 def add_step_column_for_tiger(conn: Connection, **_: Any) -> None:
275     """ Add a new column 'step' to the tiger data table.
276     """
277     if conn.table_has_column('location_property_tiger', 'step'):
278         return
279
280     with conn.cursor() as cur:
281         cur.execute("ALTER TABLE location_property_tiger ADD COLUMN step SMALLINT")
282         cur.execute("""UPDATE location_property_tiger
283                          SET step = CASE WHEN interpolationtype = 'all'
284                                          THEN 1 ELSE 2 END
285                     """)
286
287
288 @_migration(4, 0, 99, 4)
289 def add_derived_name_column_for_country_names(conn: Connection, **_: Any) -> None:
290     """ Add a new column 'derived_name' which in the future takes the
291         country names as imported from OSM data.
292     """
293     if not conn.table_has_column('country_name', 'derived_name'):
294         with conn.cursor() as cur:
295             cur.execute("ALTER TABLE country_name ADD COLUMN derived_name public.HSTORE")
296
297
298 @_migration(4, 0, 99, 5)
299 def mark_internal_country_names(conn: Connection, config: Configuration, **_: Any) -> None:
300     """ Names from the country table should be marked as internal to prevent
301         them from being deleted. Only necessary for ICU tokenizer.
302     """
303     import psycopg2.extras # pylint: disable=import-outside-toplevel
304
305     tokenizer = tokenizer_factory.get_tokenizer_for_db(config)
306     with tokenizer.name_analyzer() as analyzer:
307         with conn.cursor() as cur:
308             psycopg2.extras.register_hstore(cur)
309             cur.execute("SELECT country_code, name FROM country_name")
310
311             for country_code, names in cur:
312                 if not names:
313                     names = {}
314                 names['countrycode'] = country_code
315                 analyzer.add_country_names(country_code, names)
316
317
318 @_migration(4, 1, 99, 0)
319 def add_place_deletion_todo_table(conn: Connection, **_: Any) -> None:
320     """ Add helper table for deleting data on updates.
321
322         The table is only necessary when updates are possible, i.e.
323         the database is not in freeze mode.
324     """
325     if conn.table_exists('place'):
326         with conn.cursor() as cur:
327             cur.execute("""CREATE TABLE IF NOT EXISTS place_to_be_deleted (
328                              osm_type CHAR(1),
329                              osm_id BIGINT,
330                              class TEXT,
331                              type TEXT,
332                              deferred BOOLEAN)""")
333
334
335 @_migration(4, 1, 99, 1)
336 def split_pending_index(conn: Connection, **_: Any) -> None:
337     """ Reorganise indexes for pending updates.
338     """
339     if conn.table_exists('place'):
340         with conn.cursor() as cur:
341             cur.execute("""CREATE INDEX IF NOT EXISTS idx_placex_rank_address_sector
342                            ON placex USING BTREE (rank_address, geometry_sector)
343                            WHERE indexed_status > 0""")
344             cur.execute("""CREATE INDEX IF NOT EXISTS idx_placex_rank_boundaries_sector
345                            ON placex USING BTREE (rank_search, geometry_sector)
346                            WHERE class = 'boundary' and type = 'administrative'
347                                  and indexed_status > 0""")
348             cur.execute("DROP INDEX IF EXISTS idx_placex_pendingsector")
349
350
351 @_migration(4, 2, 99, 0)
352 def enable_forward_dependencies(conn: Connection, **_: Any) -> None:
353     """ Create indexes for updates with forward dependency tracking (long-running).
354     """
355     if conn.table_exists('planet_osm_ways'):
356         with conn.cursor() as cur:
357             cur.execute("""SELECT * FROM pg_indexes
358                            WHERE tablename = 'planet_osm_ways'
359                                  and indexdef LIKE '%nodes%'""")
360             if cur.rowcount == 0:
361                 cur.execute("""CREATE OR REPLACE FUNCTION public.planet_osm_index_bucket(bigint[])
362                                RETURNS bigint[]
363                                LANGUAGE sql IMMUTABLE
364                                 AS $function$
365                                   SELECT ARRAY(SELECT DISTINCT unnest($1) >> 5)
366                                 $function$""")
367                 cur.execute("""CREATE INDEX planet_osm_ways_nodes_bucket_idx
368                                  ON planet_osm_ways
369                                  USING gin (planet_osm_index_bucket(nodes))
370                                  WITH (fastupdate=off)""")
371                 cur.execute("""CREATE INDEX planet_osm_rels_parts_idx
372                                  ON planet_osm_rels USING gin (parts)
373                                  WITH (fastupdate=off)""")
374                 cur.execute("ANALYZE planet_osm_ways")
375
376
377 @_migration(4, 2, 99, 1)
378 def add_improved_geometry_reverse_placenode_index(conn: Connection, **_: Any) -> None:
379     """ Create improved index for reverse lookup of place nodes.
380     """
381     with conn.cursor() as cur:
382         cur.execute("""CREATE INDEX IF NOT EXISTS idx_placex_geometry_reverse_lookupPlaceNode
383                        ON placex
384                        USING gist (ST_Buffer(geometry, reverse_place_diameter(rank_search)))
385                        WHERE rank_address between 4 and 25 AND type != 'postcode'
386                          AND name is not null AND linked_place_id is null AND osm_type = 'N'
387                     """)