2 Functions for database migration to newer software versions.
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
12 LOG = logging.getLogger()
14 _MIGRATION_FUNCTIONS = []
16 def migrate(config, paths):
17 """ Check for the current database version and execute migrations,
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')
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('-')])
30 if db_version == NOMINATIM_VERSION:
31 LOG.warning("Database already at latest version (%s)", db_version_str)
34 LOG.info("Detected database version: %s", db_version_str)
36 db_version = _guess_version(conn)
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)
46 has_run_migration = True
49 LOG.warning('Updating SQL functions.')
50 refresh.create_functions(conn, config, paths.sqllib_dir)
52 properties.set_property(conn, 'database_version',
53 '{0[0]}.{0[1]}.{0[2]}-{0[3]}'.format(NOMINATIM_VERSION))
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.
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;
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.')
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.
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.
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
94 _MIGRATION_FUNCTIONS.append(((major, minor, patch, dbpatch), func))
99 @_migration(3, 5, 0, 99)
100 def import_status_timestamp_change(conn, **_):
101 """ Add timezone to timestamp in status table.
103 The import_status table has been changed to include timezone information
106 with conn.cursor() as cur:
107 cur.execute("""ALTER TABLE import_status ALTER COLUMN lastimportdate
108 TYPE timestamp with time zone;""")
111 @_migration(3, 5, 0, 99)
112 def install_database_module_in_project_directory(conn, config, paths, **_):
113 """ Install database module in project directory.
115 The database module needs to be present in the project directory
116 since those were introduced.
118 database_import.install_module(paths.module_dir, paths.project_dir,
119 config.DATABASE_MODULE_PATH, conn=conn)
122 @_migration(3, 5, 0, 99)
123 def add_nominatim_property_table(conn, config, **_):
124 """ Add nominatim_property table.
126 if not conn.table_exists('nominatim_properties'):
127 with conn.cursor() as cur:
128 cur.execute("""CREATE TABLE nominatim_properties (
131 GRANT SELECT ON TABLE nominatim_properties TO "{}";
132 """.format(config.DATABASE_WEBUSER))
134 @_migration(3, 6, 0, 0)
135 def change_housenumber_transliteration(conn, **_):
136 """ Transliterate housenumbers.
138 The database schema switched from saving raw housenumbers in
139 placex.housenumber to saving transliterated ones.
141 with conn.cursor() as cur:
142 cur.execute("""CREATE OR REPLACE FUNCTION create_housenumber_id(housenumber TEXT)
147 SELECT array_to_string(array_agg(trans), ';')
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;
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""")