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 Implementation of the 'import' subcommand.
10 from typing import Optional
13 from pathlib import Path
18 from ..errors import UsageError
19 from ..config import Configuration
20 from ..db.connection import connect
21 from ..db import status, properties
22 from ..tokenizer.base import AbstractTokenizer
23 from ..version import NOMINATIM_VERSION
24 from .args import NominatimArgs
26 # Do not repeat documentation of subcommand classes.
27 # pylint: disable=C0111
28 # Using non-top-level imports to avoid eventually unused imports.
29 # pylint: disable=C0415
31 LOG = logging.getLogger()
35 Create a new Nominatim database from an OSM file.
37 This sub-command sets up a new Nominatim database from scratch starting
38 with creating a new database in Postgresql. The user running this command
39 needs superuser rights on the database.
42 def add_args(self, parser: argparse.ArgumentParser) -> None:
43 group1 = parser.add_argument_group('Required arguments')
44 group1.add_argument('--osm-file', metavar='FILE', action='append',
45 help='OSM file to be imported'
46 ' (repeat for importing multiple files)',
48 group1.add_argument('--continue', dest='continue_at',
49 choices=['import-from-file', 'load-data', 'indexing', 'db-postprocess'],
50 help='Continue an import that was interrupted',
52 group2 = parser.add_argument_group('Optional arguments')
53 group2.add_argument('--osm2pgsql-cache', metavar='SIZE', type=int,
54 help='Size of cache to be used by osm2pgsql (in MB)')
55 group2.add_argument('--reverse-only', action='store_true',
56 help='Do not create tables and indexes for searching')
57 group2.add_argument('--no-partitions', action='store_true',
58 help=("Do not partition search indices "
59 "(speeds up import of single country extracts)"))
60 group2.add_argument('--no-updates', action='store_true',
61 help="Do not keep tables that are only needed for "
62 "updating the database later")
63 group2.add_argument('--offline', action='store_true',
64 help="Do not attempt to load any additional data from the internet")
65 group3 = parser.add_argument_group('Expert options')
66 group3.add_argument('--ignore-errors', action='store_true',
67 help='Continue import even when errors in SQL are present')
68 group3.add_argument('--index-noanalyse', action='store_true',
69 help='Do not perform analyse operations during index (expert only)')
70 group3.add_argument('--prepare-database', action='store_true',
71 help='Create the database but do not import any data')
74 def run(self, args: NominatimArgs) -> int: # pylint: disable=too-many-statements, too-many-branches
75 if args.osm_file is None and args.continue_at is None and not args.prepare_database:
76 raise UsageError("No input files (use --osm-file).")
78 if args.osm_file is not None and args.continue_at not in ('import-from-file', None):
79 raise UsageError(f"Cannot use --continue {args.continue_at} and --osm-file together.")
81 if args.continue_at is not None and args.prepare_database:
83 "Cannot use --continue and --prepare-database together."
86 return asyncio.run(self.async_run(args))
89 async def async_run(self, args: NominatimArgs) -> int:
90 from ..data import country_info
91 from ..tools import database_import, postcodes, freeze
92 from ..indexer.indexer import Indexer
94 num_threads = args.threads or psutil.cpu_count() or 1
95 country_info.setup_country_config(args.config)
97 if args.prepare_database or args.continue_at is None:
98 LOG.warning('Creating database')
99 database_import.setup_database_skeleton(args.config.get_libpq_dsn(),
100 rouser=args.config.DATABASE_WEBUSER)
101 if args.prepare_database:
104 if args.continue_at in (None, 'import-from-file'):
105 self._base_import(args)
107 if args.continue_at in ('import-from-file', 'load-data', None):
108 LOG.warning('Initialise tables')
109 with connect(args.config.get_libpq_dsn()) as conn:
110 database_import.truncate_data_tables(conn)
112 LOG.warning('Load data into placex table')
113 await database_import.load_data(args.config.get_libpq_dsn(), num_threads)
115 LOG.warning("Setting up tokenizer")
116 tokenizer = self._get_tokenizer(args.continue_at, args.config)
118 if args.continue_at in ('import-from-file', 'load-data', None):
119 LOG.warning('Calculate postcodes')
120 postcodes.update_postcodes(args.config.get_libpq_dsn(),
121 args.project_dir, tokenizer)
123 if args.continue_at in \
124 ('import-from-file', 'load-data', 'indexing', None):
125 LOG.warning('Indexing places')
126 indexer = Indexer(args.config.get_libpq_dsn(), tokenizer, num_threads)
127 await indexer.index_full(analyse=not args.index_noanalyse)
129 LOG.warning('Post-process tables')
130 with connect(args.config.get_libpq_dsn()) as conn:
131 await database_import.create_search_indices(conn, args.config,
132 drop=args.no_updates,
134 LOG.warning('Create search index for default country names.')
135 country_info.create_country_names(conn, tokenizer,
136 args.config.get_str_list('LANGUAGES'))
138 freeze.drop_update_tables(conn)
139 tokenizer.finalize_import(args.config)
141 LOG.warning('Recompute word counts')
142 tokenizer.update_statistics(args.config, threads=num_threads)
144 self._finalize_database(args.config.get_libpq_dsn(), args.offline)
149 def _base_import(self, args: NominatimArgs) -> None:
150 from ..tools import database_import, refresh
151 from ..data import country_info
153 files = args.get_osm_file_list()
155 raise UsageError("No input files (use --osm-file).")
157 if args.continue_at in ('import-from-file', None):
158 # Check if the correct plugins are installed
159 database_import.check_existing_database_plugins(args.config.get_libpq_dsn())
160 LOG.warning('Setting up country tables')
161 country_info.setup_country_tables(args.config.get_libpq_dsn(),
162 args.config.lib_dir.data,
165 LOG.warning('Importing OSM data file')
166 database_import.import_osm_data(files,
167 args.osm2pgsql_options(0, 1),
168 drop=args.no_updates,
169 ignore_errors=args.ignore_errors)
171 LOG.warning('Importing wikipedia importance data')
172 data_path = Path(args.config.WIKIPEDIA_DATA_PATH or args.project_dir)
173 if refresh.import_wikipedia_articles(args.config.get_libpq_dsn(),
175 LOG.error('Wikipedia importance dump file not found. '
176 'Calculating importance values of locations will not '
177 'use Wikipedia importance data.')
179 LOG.warning('Importing secondary importance raster data')
180 if refresh.import_secondary_importance(args.config.get_libpq_dsn(),
181 args.project_dir) != 0:
182 LOG.error('Secondary importance file not imported. '
183 'Falling back to default ranking.')
185 self._setup_tables(args.config, args.reverse_only)
188 def _setup_tables(self, config: Configuration, reverse_only: bool) -> None:
189 """ Set up the basic database layout: tables, indexes and functions.
191 from ..tools import database_import, refresh
193 with connect(config.get_libpq_dsn()) as conn:
194 LOG.warning('Create functions (1st pass)')
195 refresh.create_functions(conn, config, False, False)
196 LOG.warning('Create tables')
197 database_import.create_tables(conn, config, reverse_only=reverse_only)
198 refresh.load_address_levels_from_config(conn, config)
199 LOG.warning('Create functions (2nd pass)')
200 refresh.create_functions(conn, config, False, False)
201 LOG.warning('Create table triggers')
202 database_import.create_table_triggers(conn, config)
203 LOG.warning('Create partition tables')
204 database_import.create_partition_tables(conn, config)
205 LOG.warning('Create functions (3rd pass)')
206 refresh.create_functions(conn, config, False, False)
209 def _get_tokenizer(self, continue_at: Optional[str],
210 config: Configuration) -> AbstractTokenizer:
211 """ Set up a new tokenizer or load an already initialised one.
213 from ..tokenizer import factory as tokenizer_factory
215 if continue_at in ('import-from-file', 'load-data', None):
216 # (re)initialise the tokenizer data
217 return tokenizer_factory.create_tokenizer(config)
219 # just load the tokenizer
220 return tokenizer_factory.get_tokenizer_for_db(config)
223 def _finalize_database(self, dsn: str, offline: bool) -> None:
224 """ Determine the database date and set the status accordingly.
226 with connect(dsn) as conn:
227 properties.set_property(conn, 'database_version', str(NOMINATIM_VERSION))
230 dbdate = status.compute_database_date(conn, offline)
231 status.set_status(conn, dbdate)
232 LOG.info('Database is at %s.', dbdate)
233 except Exception as exc: # pylint: disable=broad-except
234 LOG.error('Cannot determine date of database: %s', exc)