1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2024 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Functions for database migration to newer software versions.
10 from typing import List, Tuple, Callable, Any
13 from ..errors import UsageError
14 from ..config import Configuration
15 from ..db import properties
16 from ..db.connection import connect, Connection, \
17 table_exists, register_hstore
18 from ..version import NominatimVersion, NOMINATIM_VERSION, parse_version
19 from ..tokenizer import factory as tokenizer_factory
22 LOG = logging.getLogger()
24 _MIGRATION_FUNCTIONS: List[Tuple[NominatimVersion, Callable[..., None]]] = []
27 def migrate(config: Configuration, paths: Any) -> int:
28 """ Check for the current database version and execute migrations,
31 with connect(config.get_libpq_dsn()) as conn:
33 if table_exists(conn, 'nominatim_properties'):
34 db_version_str = properties.get_property(conn, 'database_version')
38 if db_version_str is not None:
39 db_version = parse_version(db_version_str)
43 if db_version is None or db_version < (4, 3, 0, 0):
44 LOG.fatal('Your database version is older than 4.3. '
45 'Direct migration is not possible.\n'
46 'You should strongly consider a reimport. If that is not possible\n'
47 'please upgrade to 4.3 first and then to the newest version.')
48 raise UsageError('Migration not possible.')
50 if db_version == NOMINATIM_VERSION:
51 LOG.warning("Database already at latest version (%s)", db_version_str)
54 LOG.info("Detected database version: %s", db_version_str)
56 for version, func in _MIGRATION_FUNCTIONS:
57 if db_version < version:
58 title = func.__doc__ or ''
59 LOG.warning("Running: %s (%s)", title.split('\n', 1)[0], version)
60 kwargs = dict(conn=conn, config=config, paths=paths)
64 LOG.warning('Updating SQL functions.')
65 refresh.create_functions(conn, config)
66 tokenizer = tokenizer_factory.get_tokenizer_for_db(config)
67 tokenizer.update_sql_functions(config)
69 properties.set_property(conn, 'database_version', str(NOMINATIM_VERSION))
76 def _migration(major: int, minor: int, patch: int = 0,
77 dbpatch: int = 0) -> Callable[[Callable[..., None]], Callable[..., None]]:
78 """ Decorator for a single migration step. The parameters describe the
79 version after which the migration is applicable, i.e before changing
80 from the given version to the next, the migration is required.
82 All migrations are run in the order in which they are defined in this
83 file. Do not run global SQL scripts for migrations as you cannot be sure
84 that these scripts do the same in later versions.
86 Functions will always be reimported in full at the end of the migration
87 process, so the migration functions may leave a temporary state behind
90 def decorator(func: Callable[..., None]) -> Callable[..., None]:
91 version = NominatimVersion(major, minor, patch, dbpatch)
92 _MIGRATION_FUNCTIONS.append((version, func))
98 @_migration(4, 4, 99, 0)
99 def create_postcode_area_lookup_index(conn: Connection, **_: Any) -> None:
100 """ Create index needed for looking up postcode areas from postocde points.
102 with conn.cursor() as cur:
103 cur.execute("""CREATE INDEX IF NOT EXISTS idx_placex_postcode_areas
104 ON placex USING BTREE (country_code, postcode)
105 WHERE osm_type = 'R' AND class = 'boundary' AND type = 'postal_code'
109 @_migration(4, 4, 99, 1)
110 def create_postcode_parent_index(conn: Connection, **_: Any) -> None:
111 """ Create index needed for updating postcodes when a parent changes.
113 if table_exists(conn, 'planet_osm_ways'):
114 with conn.cursor() as cur:
115 cur.execute("""CREATE INDEX IF NOT EXISTS
116 idx_location_postcode_parent_place_id
117 ON location_postcode USING BTREE (parent_place_id)""")