]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/migration.py
Merge remote-tracking branch 'upstream/master'
[nominatim.git] / nominatim / tools / migration.py
1 """
2 Functions for database migration to newer software versions.
3 """
4 import logging
5
6 from ..db import properties
7 from ..db.connection import connect
8 from ..version import NOMINATIM_VERSION
9 from . import refresh, database_import
10 from ..errors import UsageError
11
12 LOG = logging.getLogger()
13
14 _MIGRATION_FUNCTIONS = []
15
16 def migrate(config, paths):
17     """ Check for the current database version and execute migrations,
18         if necesssary.
19     """
20     with connect(config.get_libpq_dsn()) as conn:
21         if conn.table_exists('nominatim_properties'):
22             db_version_str = properties.get_property(conn, 'database_version')
23         else:
24             db_version_str = None
25
26         if db_version_str is not None:
27             parts = db_version_str.split('.')
28             db_version = tuple([int(x) for x in parts[:2] + parts[2].split('-')])
29
30             if db_version == NOMINATIM_VERSION:
31                 LOG.warning("Database already at latest version (%s)", db_version_str)
32                 return 0
33
34             LOG.info("Detected database version: %s", db_version_str)
35         else:
36             db_version = _guess_version(conn)
37
38
39         has_run_migration = False
40         for version, func in _MIGRATION_FUNCTIONS:
41             if db_version <= version:
42                 LOG.warning("Runnning: %s (%s)", func.__doc__.split('\n', 1)[0],
43                             '{0[0]}.{0[1]}.{0[2]}-{0[3]}'.format(version))
44                 kwargs = dict(conn=conn, config=config, paths=paths)
45                 func(**kwargs)
46                 has_run_migration = True
47
48         if has_run_migration:
49             LOG.warning('Updating SQL functions.')
50             refresh.create_functions(conn, config, paths.sqllib_dir)
51
52         properties.set_property(conn, 'database_version',
53                                 '{0[0]}.{0[1]}.{0[2]}-{0[3]}'.format(NOMINATIM_VERSION))
54
55         conn.commit()
56
57     return 0
58
59
60 def _guess_version(conn):
61     """ Guess a database version when there is no property table yet.
62         Only migrations for 3.6 and later are supported, so bail out
63         when the version seems older.
64     """
65     with conn.cursor() as cur:
66         # In version 3.6, the country_name table was updated. Check for that.
67         cnt = cur.scalar("""SELECT count(*) FROM
68                             (SELECT svals(name) FROM  country_name
69                              WHERE country_code = 'gb')x;
70                          """)
71         if cnt < 100:
72             LOG.fatal('It looks like your database was imported with a version '
73                       'prior to 3.6.0. Automatic migration not possible.')
74             raise UsageError('Migration not possible.')
75
76     return (3, 5, 0, 99)
77
78
79
80 def _migration(major, minor, patch=0, dbpatch=0):
81     """ Decorator for a single migration step. The parameters describe the
82         version after which the migration is applicable, i.e before changing
83         from the given version to the next, the migration is required.
84
85         All migrations are run in the order in which they are defined in this
86         file. Do not run global SQL scripts for migrations as you cannot be sure
87         that these scripts do the same in later versions.
88
89         Functions will always be reimported in full at the end of the migration
90         process, so the migration functions may leave a temporary state behind
91         there.
92     """
93     def decorator(func):
94         _MIGRATION_FUNCTIONS.append(((major, minor, patch, dbpatch), func))
95
96     return decorator
97
98
99 @_migration(3, 5, 0, 99)
100 def import_status_timestamp_change(conn, **_):
101     """ Add timezone to timestamp in status table.
102
103         The import_status table has been changed to include timezone information
104         with the time stamp.
105     """
106     with conn.cursor() as cur:
107         cur.execute("""ALTER TABLE import_status ALTER COLUMN lastimportdate
108                        TYPE timestamp with time zone;""")
109
110
111 @_migration(3, 5, 0, 99)
112 def install_database_module_in_project_directory(conn, config, paths, **_):
113     """ Install database module in project directory.
114
115         The database module needs to be present in the project directory
116         since those were introduced.
117     """
118     database_import.install_module(paths.module_dir, paths.project_dir,
119                                    config.DATABASE_MODULE_PATH, conn=conn)
120
121
122 @_migration(3, 5, 0, 99)
123 def add_nominatim_property_table(conn, config, **_):
124     """ Add nominatim_property table.
125     """
126     if not conn.table_exists('nominatim_properties'):
127         with conn.cursor() as cur:
128             cur.execute("""CREATE TABLE nominatim_properties (
129                                property TEXT,
130                                value TEXT);
131                            GRANT SELECT ON TABLE nominatim_properties TO "{}";
132                         """.format(config.DATABASE_WEBUSER))
133
134 @_migration(3, 6, 0, 0)
135 def change_housenumber_transliteration(conn, **_):
136     """ Transliterate housenumbers.
137
138         The database schema switched from saving raw housenumbers in
139         placex.housenumber to saving transliterated ones.
140     """
141     with conn.cursor() as cur:
142         cur.execute("""CREATE OR REPLACE FUNCTION create_housenumber_id(housenumber TEXT)
143                        RETURNS TEXT AS $$
144                        DECLARE
145                          normtext TEXT;
146                        BEGIN
147                          SELECT array_to_string(array_agg(trans), ';')
148                            INTO normtext
149                            FROM (SELECT lookup_word as trans, getorcreate_housenumber_id(lookup_word)
150                                  FROM (SELECT make_standard_name(h) as lookup_word
151                                        FROM regexp_split_to_table(housenumber, '[,;]') h) x) y;
152                          return normtext;
153                        END;
154                        $$ LANGUAGE plpgsql STABLE STRICT;""")
155         cur.execute("DELETE FROM word WHERE class = 'place' and type = 'house'")
156         cur.execute("""UPDATE placex
157                        SET housenumber = create_housenumber_id(housenumber)
158                        WHERE housenumber is not null""")
159
160
161 @_migration(3, 7, 0, 0)
162 def switch_placenode_geometry_index(conn, **_):
163     """ Replace idx_placex_geometry_reverse_placeNode index.
164
165         Make the index slightly more permissive, so that it can also be used
166         when matching up boundaries and place nodes. It makes the index
167         idx_placex_adminname index unnecessary.
168     """
169     with conn.cursor() as cur:
170         cur.execute(""" CREATE INDEX IF NOT EXISTS idx_placex_geometry_placenode ON placex
171                         USING GIST (geometry)
172                         WHERE osm_type = 'N' and rank_search < 26
173                               and class = 'place' and type != 'postcode'
174                               and linked_place_id is null""")
175         cur.execute(""" DROP INDEX IF EXISTS idx_placex_adminname """)