]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/admin.py
Merge remote-tracking branch 'upstream/master'
[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 from psycopg2 import DataError
15
16 from nominatim.config import Configuration
17 from nominatim.db.connection import connect, Cursor
18 from nominatim.tokenizer import factory as tokenizer_factory
19 from nominatim.errors import UsageError
20 from nominatim.data.place_info import PlaceInfo
21 from nominatim.typing import DictCursorResult
22
23 LOG = logging.getLogger()
24
25 def _get_place_info(cursor: Cursor, osm_id: Optional[str],
26                     place_id: Optional[int]) -> DictCursorResult:
27     sql = """SELECT place_id, extra.*
28              FROM placex, LATERAL placex_indexing_prepare(placex) as extra
29           """
30
31     values: Tuple[Any, ...]
32     if osm_id:
33         osm_type = osm_id[0].upper()
34         if osm_type not in 'NWR' or not osm_id[1:].isdigit():
35             LOG.fatal('OSM ID must be of form <N|W|R><id>. Got: %s', osm_id)
36             raise UsageError("OSM ID parameter badly formatted")
37
38         sql += ' WHERE placex.osm_type = %s AND placex.osm_id = %s'
39         values = (osm_type, int(osm_id[1:]))
40     elif place_id is not None:
41         sql += ' WHERE placex.place_id = %s'
42         values = (place_id, )
43     else:
44         LOG.fatal("No OSM object given to index.")
45         raise UsageError("OSM object not found")
46
47     cursor.execute(sql + ' LIMIT 1', values)
48
49     if cursor.rowcount < 1:
50         LOG.fatal("OSM object %s not found in database.", osm_id)
51         raise UsageError("OSM object not found")
52
53     return cast(DictCursorResult, cursor.fetchone())
54
55
56 def analyse_indexing(config: Configuration, osm_id: Optional[str] = None,
57                      place_id: Optional[int] = None) -> None:
58     """ Analyse indexing of a single Nominatim object.
59     """
60     with connect(config.get_libpq_dsn()) as conn:
61         register_hstore(conn)
62         with conn.cursor() as cur:
63             place = _get_place_info(cur, osm_id, place_id)
64
65             cur.execute("update placex set indexed_status = 2 where place_id = %s",
66                         (place['place_id'], ))
67
68             cur.execute("""SET auto_explain.log_min_duration = '0';
69                            SET auto_explain.log_analyze = 'true';
70                            SET auto_explain.log_nested_statements = 'true';
71                            LOAD 'auto_explain';
72                            SET client_min_messages = LOG;
73                            SET log_min_messages = FATAL""")
74
75             tokenizer = tokenizer_factory.get_tokenizer_for_db(config)
76
77             with tokenizer.name_analyzer() as analyzer:
78                 cur.execute("""UPDATE placex
79                                SET indexed_status = 0, address = %s, token_info = %s,
80                                name = %s, linked_place_id = %s
81                                WHERE place_id = %s""",
82                             (place['address'],
83                              Json(analyzer.process_place(PlaceInfo(place))),
84                              place['name'], place['linked_place_id'], place['place_id']))
85
86         # we do not want to keep the results
87         conn.rollback()
88
89         for msg in conn.notices:
90             print(msg)
91
92
93 def clean_deleted_relations(config: Configuration, age: str) -> None:
94     """ Clean deleted relations older than a given age
95     """
96     with connect(config.get_libpq_dsn()) as conn:
97         with conn.cursor() as cur:
98             try:
99                 cur.execute("""SELECT place_force_delete(p.place_id)
100                             FROM import_polygon_delete d, placex p
101                             WHERE p.osm_type = d.osm_type AND p.osm_id = d.osm_id
102                             AND age(p.indexed_date) > %s::interval""",
103                             (age, ))
104             except DataError as exc:
105                 raise UsageError('Invalid PostgreSQL time interval format') from exc
106         conn.commit()