]> git.openstreetmap.org Git - nominatim.git/blob - src/nominatim_db/tools/database_import.py
prepare release 5.3.2-post1
[nominatim.git] / src / nominatim_db / tools / database_import.py
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2026 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Functions for setting up and importing a new Nominatim database.
9 """
10 from typing import Tuple, Optional, Union, Sequence, MutableMapping, Any
11 import logging
12 import os
13 import subprocess
14 import asyncio
15 from pathlib import Path
16
17 import psutil
18 import psycopg
19 from psycopg import sql as pysql
20
21 from ..errors import UsageError
22 from ..config import Configuration
23 from ..db.connection import connect, get_pg_env, Connection, server_version_tuple, \
24                             postgis_version_tuple, drop_tables, table_exists, execute_scalar
25 from ..db.sql_preprocessor import SQLPreprocessor
26 from ..db.query_pool import QueryPool
27 from .exec_utils import run_osm2pgsql
28 from ..version import POSTGRESQL_REQUIRED_VERSION, POSTGIS_REQUIRED_VERSION
29
30 LOG = logging.getLogger()
31
32
33 def _require_version(module: str, actual: Tuple[int, int], expected: Tuple[int, int]) -> None:
34     """ Compares the version for the given module and raises an exception
35         if the actual version is too old.
36     """
37     if actual < expected:
38         LOG.fatal('Minimum supported version of %s is %d.%d. '
39                   'Found version %d.%d.',
40                   module, expected[0], expected[1], actual[0], actual[1])
41         raise UsageError(f'{module} is too old.')
42
43
44 def _require_loaded(extension_name: str, conn: Connection) -> None:
45     """ Check that the given extension is loaded. """
46     with conn.cursor() as cur:
47         cur.execute('SELECT * FROM pg_extension WHERE extname = %s', (extension_name, ))
48         if cur.rowcount <= 0:
49             LOG.fatal('Required module %s is not loaded.', extension_name)
50             raise UsageError(f'{extension_name} is not loaded.')
51
52
53 def check_existing_database_plugins(dsn: str) -> None:
54     """ Check that the database has the required plugins installed."""
55     with connect(dsn) as conn:
56         _require_version('PostgreSQL server',
57                          server_version_tuple(conn),
58                          POSTGRESQL_REQUIRED_VERSION)
59         _require_version('PostGIS',
60                          postgis_version_tuple(conn),
61                          POSTGIS_REQUIRED_VERSION)
62         _require_loaded('hstore', conn)
63
64
65 def setup_database_skeleton(dsn: str, rouser: Optional[str] = None) -> None:
66     """ Create a new database for Nominatim and populate it with the
67         essential extensions.
68
69         The function fails when the database already exists or Postgresql or
70         PostGIS versions are too old.
71
72         Uses `createdb` to create the database.
73
74         If 'rouser' is given, then the function also checks that the user
75         with that given name exists.
76
77         Requires superuser rights by the caller.
78     """
79     proc = subprocess.run(['createdb'], env=get_pg_env(dsn), check=False)
80
81     if proc.returncode != 0:
82         raise UsageError('Creating new database failed.')
83
84     with connect(dsn) as conn:
85         _require_version('PostgreSQL server',
86                          server_version_tuple(conn),
87                          POSTGRESQL_REQUIRED_VERSION)
88
89         if rouser is not None:
90             cnt = execute_scalar(conn, 'SELECT count(*) FROM pg_user where usename = %s',
91                                  (rouser, ))
92             if cnt == 0:
93                 LOG.fatal("Web user '%s' does not exist. Create it with:\n"
94                           "\n      createuser %s", rouser, rouser)
95                 raise UsageError('Missing read-only user.')
96
97         # Create extensions.
98         with conn.cursor() as cur:
99             cur.execute('CREATE EXTENSION IF NOT EXISTS hstore')
100             cur.execute('CREATE EXTENSION IF NOT EXISTS postgis')
101             cur.execute('CREATE EXTENSION IF NOT EXISTS postgis_raster')
102
103         conn.commit()
104
105         _require_version('PostGIS',
106                          postgis_version_tuple(conn),
107                          POSTGIS_REQUIRED_VERSION)
108
109
110 def import_osm_data(osm_files: Union[Path, Sequence[Path]],
111                     options: MutableMapping[str, Any],
112                     drop: bool = False, ignore_errors: bool = False) -> None:
113     """ Import the given OSM files. 'options' contains the list of
114         default settings for osm2pgsql.
115     """
116     options['import_file'] = osm_files
117     options['append'] = False
118     options['threads'] = 1
119
120     if not options['flatnode_file'] and options['osm2pgsql_cache'] == 0:
121         # Make some educated guesses about cache size based on the size
122         # of the import file and the available memory.
123         mem = psutil.virtual_memory()
124         fsize = 0
125         if isinstance(osm_files, list):
126             for fname in osm_files:
127                 fsize += os.stat(str(fname)).st_size
128         else:
129             fsize = os.stat(str(osm_files)).st_size
130         options['osm2pgsql_cache'] = int(min((mem.available + getattr(mem, 'cached', 0)) * 0.75,
131                                              fsize * 2) / 1024 / 1024) + 1
132
133     run_osm2pgsql(options)
134
135     with connect(options['dsn']) as conn:
136         if not ignore_errors:
137             with conn.cursor() as cur:
138                 cur.execute('SELECT true FROM place LIMIT 1')
139                 if cur.rowcount == 0:
140                     raise UsageError('No data imported by osm2pgsql.')
141
142         if drop:
143             drop_tables(conn, 'planet_osm_nodes')
144             conn.commit()
145
146     if drop and options['flatnode_file']:
147         Path(options['flatnode_file']).unlink()
148
149
150 def create_tables(conn: Connection, config: Configuration, reverse_only: bool = False) -> None:
151     """ Create the set of basic tables.
152         When `reverse_only` is True, then the main table for searching will
153         be skipped and only reverse search is possible.
154     """
155     SQLPreprocessor(conn, config).run_sql_file(conn, 'tables.sql',
156                                                create_reverse_only=reverse_only)
157
158     # reinitiate the preprocessor to get all the newly created tables
159     SQLPreprocessor(conn, config).run_sql_file(conn, 'grants.sql')
160
161
162 def create_table_triggers(conn: Connection, config: Configuration) -> None:
163     """ Create the triggers for the tables. The trigger functions must already
164         have been imported with refresh.create_functions().
165     """
166     sql = SQLPreprocessor(conn, config)
167     sql.run_sql_file(conn, 'table-triggers.sql')
168
169
170 def create_partition_tables(conn: Connection, config: Configuration) -> None:
171     """ Create tables that have explicit partitioning.
172     """
173     sql = SQLPreprocessor(conn, config)
174     sql.run_sql_file(conn, 'partition-tables.src.sql')
175
176
177 def truncate_data_tables(conn: Connection) -> None:
178     """ Truncate all data tables to prepare for a fresh load.
179     """
180     with conn.cursor() as cur:
181         cur.execute('TRUNCATE placex')
182         cur.execute('TRUNCATE place_addressline')
183         cur.execute('TRUNCATE location_area')
184         cur.execute('TRUNCATE location_area_country')
185         cur.execute('TRUNCATE location_property_tiger')
186         cur.execute('TRUNCATE location_property_osmline')
187         cur.execute('TRUNCATE location_postcodes')
188         if table_exists(conn, 'search_name'):
189             cur.execute('TRUNCATE search_name')
190         cur.execute('DROP SEQUENCE IF EXISTS seq_place')
191         cur.execute('CREATE SEQUENCE seq_place start 100000')
192
193         cur.execute("""SELECT tablename FROM pg_tables
194                        WHERE tablename LIKE 'location_road_%'""")
195
196         for table in [r[0] for r in list(cur)]:
197             cur.execute(pysql.SQL('TRUNCATE {}').format(pysql.Identifier(table)))
198
199     conn.commit()
200
201
202 _COPY_COLUMNS = pysql.SQL(',').join(map(pysql.Identifier,
203                                         ('osm_type', 'osm_id', 'class', 'type',
204                                          'name', 'admin_level', 'address',
205                                          'extratags', 'geometry')))
206
207
208 async def load_data(dsn: str, threads: int) -> None:
209     """ Copy data into the word and placex table.
210     """
211     placex_threads = max(1, threads - 1)
212
213     progress = asyncio.create_task(_progress_print())
214
215     async with QueryPool(dsn, placex_threads + 1) as pool:
216         # Copy data from place to placex in <threads - 1> chunks.
217         for imod in range(placex_threads):
218             await pool.put_query(
219                 pysql.SQL("""INSERT INTO placex ({columns})
220                                SELECT {columns} FROM place
221                                 WHERE osm_id % {total} = {mod}
222                           """).format(columns=_COPY_COLUMNS,
223                                       total=pysql.Literal(placex_threads),
224                                       mod=pysql.Literal(imod)), None)
225
226         # Interpolations need to be copied separately
227         await pool.put_query("""
228                 INSERT INTO location_property_osmline (osm_id, type, address, linegeo)
229                   SELECT osm_id, type, address, geometry
230                   FROM place_interpolation
231                 """, None)
232
233     progress.cancel()
234
235     async with await psycopg.AsyncConnection.connect(dsn) as aconn:
236         await aconn.execute('ANALYSE')
237
238
239 async def _progress_print() -> None:
240     while True:
241         try:
242             await asyncio.sleep(1)
243         except asyncio.CancelledError:
244             print('', flush=True)
245             break
246         print('.', end='', flush=True)
247
248
249 async def create_search_indices(conn: Connection, config: Configuration,
250                                 drop: bool = False, threads: int = 1) -> None:
251     """ Create tables that have explicit partitioning.
252     """
253
254     # If index creation failed and left an index invalid, they need to be
255     # cleaned out first, so that the script recreates them.
256     with conn.cursor() as cur:
257         cur.execute("""SELECT relname FROM pg_class, pg_index
258                        WHERE pg_index.indisvalid = false
259                              AND pg_index.indexrelid = pg_class.oid""")
260         bad_indices = [row[0] for row in list(cur)]
261         for idx in bad_indices:
262             LOG.info("Drop invalid index %s.", idx)
263             cur.execute(pysql.SQL('DROP INDEX {}').format(pysql.Identifier(idx)))
264     conn.commit()
265
266     sql = SQLPreprocessor(conn, config)
267
268     await sql.run_parallel_sql_file(config.get_libpq_dsn(),
269                                     'indices.sql', min(8, threads), drop=drop)