]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/admin.py
9fb944d3ada0b45e956396253ed2ebd3cdd2c856
[nominatim.git] / nominatim / tools / admin.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Functions for database analysis and maintenance.
9 """
10 from typing import Optional, Tuple, Any, cast
11 import logging
12
13 from psycopg2.extras import Json, register_hstore
14
15 from nominatim.config import Configuration
16 from nominatim.db.connection import connect, Cursor
17 from nominatim.tokenizer import factory as tokenizer_factory
18 from nominatim.errors import UsageError
19 from nominatim.data.place_info import PlaceInfo
20 from nominatim.typing import DictCursorResult
21
22 LOG = logging.getLogger()
23
24 def _get_place_info(cursor: Cursor, osm_id: Optional[str],
25                     place_id: Optional[int]) -> DictCursorResult:
26     sql = """SELECT place_id, extra.*
27              FROM placex, LATERAL placex_indexing_prepare(placex) as extra
28           """
29
30     values: Tuple[Any, ...]
31     if osm_id:
32         osm_type = osm_id[0].upper()
33         if osm_type not in 'NWR' or not osm_id[1:].isdigit():
34             LOG.fatal('OSM ID must be of form <N|W|R><id>. Got: %s', osm_id)
35             raise UsageError("OSM ID parameter badly formatted")
36
37         sql += ' WHERE placex.osm_type = %s AND placex.osm_id = %s'
38         values = (osm_type, int(osm_id[1:]))
39     elif place_id is not None:
40         sql += ' WHERE placex.place_id = %s'
41         values = (place_id, )
42     else:
43         LOG.fatal("No OSM object given to index.")
44         raise UsageError("OSM object not found")
45
46     cursor.execute(sql + ' LIMIT 1', values)
47
48     if cursor.rowcount < 1:
49         LOG.fatal("OSM object %s not found in database.", osm_id)
50         raise UsageError("OSM object not found")
51
52     return cast(DictCursorResult, cursor.fetchone()) # type: ignore[no-untyped-call]
53
54
55 def analyse_indexing(config: Configuration, osm_id: Optional[str] = None,
56                      place_id: Optional[int] = None) -> None:
57     """ Analyse indexing of a single Nominatim object.
58     """
59     with connect(config.get_libpq_dsn()) as conn:
60         register_hstore(conn)
61         with conn.cursor() as cur:
62             place = _get_place_info(cur, osm_id, place_id)
63
64             cur.execute("update placex set indexed_status = 2 where place_id = %s",
65                         (place['place_id'], ))
66
67             cur.execute("""SET auto_explain.log_min_duration = '0';
68                            SET auto_explain.log_analyze = 'true';
69                            SET auto_explain.log_nested_statements = 'true';
70                            LOAD 'auto_explain';
71                            SET client_min_messages = LOG;
72                            SET log_min_messages = FATAL""")
73
74             tokenizer = tokenizer_factory.get_tokenizer_for_db(config)
75
76             with tokenizer.name_analyzer() as analyzer:
77                 cur.execute("""UPDATE placex
78                                SET indexed_status = 0, address = %s, token_info = %s,
79                                name = %s, linked_place_id = %s
80                                WHERE place_id = %s""",
81                             (place['address'],
82                              Json(analyzer.process_place(PlaceInfo(place))),
83                              place['name'], place['linked_place_id'], place['place_id']))
84
85         # we do not want to keep the results
86         conn.rollback()
87
88         for msg in conn.notices:
89             print(msg)