]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/db/status.py
add typing annotations for DB status module
[nominatim.git] / nominatim / db / status.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 Access and helper functions for the status and status log table.
9 """
10 from typing import Optional, Tuple, cast
11 import datetime as dt
12 import logging
13 import re
14
15 from typing_extensions import TypedDict
16
17 from nominatim.db.connection import Connection
18 from nominatim.tools.exec_utils import get_url
19 from nominatim.errors import UsageError
20
21 LOG = logging.getLogger()
22 ISODATE_FORMAT = '%Y-%m-%dT%H:%M:%S'
23
24
25 class StatusRow(TypedDict):
26     """ Dictionary of columns of the import_status table.
27     """
28     lastimportdate: dt.datetime
29     sequence_id: Optional[int]
30     indexed: Optional[bool]
31
32
33 def compute_database_date(conn: Connection) -> dt.datetime:
34     """ Determine the date of the database from the newest object in the
35         data base.
36     """
37     # First, find the node with the highest ID in the database
38     with conn.cursor() as cur:
39         if conn.table_exists('place'):
40             osmid = cur.scalar("SELECT max(osm_id) FROM place WHERE osm_type='N'")
41         else:
42             osmid = cur.scalar("SELECT max(osm_id) FROM placex WHERE osm_type='N'")
43
44         if osmid is None:
45             LOG.fatal("No data found in the database.")
46             raise UsageError("No data found in the database.")
47
48     LOG.info("Using node id %d for timestamp lookup", osmid)
49     # Get the node from the API to find the timestamp when it was created.
50     node_url = f'https://www.openstreetmap.org/api/0.6/node/{osmid}/1'
51     data = get_url(node_url)
52
53     match = re.search(r'timestamp="((\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}))Z"', data)
54
55     if match is None:
56         LOG.fatal("The node data downloaded from the API does not contain valid data.\n"
57                   "URL used: %s", node_url)
58         raise UsageError("Bad API data.")
59
60     LOG.debug("Found timestamp %s", match.group(1))
61
62     return dt.datetime.strptime(match.group(1), ISODATE_FORMAT).replace(tzinfo=dt.timezone.utc)
63
64
65 def set_status(conn: Connection, date: Optional[dt.datetime],
66                seq: Optional[int] = None, indexed: bool = True) -> None:
67     """ Replace the current status with the given status. If date is `None`
68         then only sequence and indexed will be updated as given. Otherwise
69         the whole status is replaced.
70         The change will be committed to the database.
71     """
72     assert date is None or date.tzinfo == dt.timezone.utc
73     with conn.cursor() as cur:
74         if date is None:
75             cur.execute("UPDATE import_status set sequence_id = %s, indexed = %s",
76                         (seq, indexed))
77         else:
78             cur.execute("TRUNCATE TABLE import_status")
79             cur.execute("""INSERT INTO import_status (lastimportdate, sequence_id, indexed)
80                            VALUES (%s, %s, %s)""", (date, seq, indexed))
81
82     conn.commit()
83
84
85 def get_status(conn: Connection) -> Tuple[Optional[dt.datetime], Optional[int], Optional[bool]]:
86     """ Return the current status as a triple of (date, sequence, indexed).
87         If status has not been set up yet, a triple of None is returned.
88     """
89     with conn.cursor() as cur:
90         cur.execute("SELECT * FROM import_status LIMIT 1")
91         if cur.rowcount < 1:
92             return None, None, None
93
94         row = cast(StatusRow, cur.fetchone()) # type: ignore[no-untyped-call]
95         return row['lastimportdate'], row['sequence_id'], row['indexed']
96
97
98 def set_indexed(conn: Connection, state: bool) -> None:
99     """ Set the indexed flag in the status table to the given state.
100     """
101     with conn.cursor() as cur:
102         cur.execute("UPDATE import_status SET indexed = %s", (state, ))
103     conn.commit()
104
105
106 def log_status(conn: Connection, start: dt.datetime,
107                event: str, batchsize: Optional[int] = None) -> None:
108     """ Write a new status line to the `import_osmosis_log` table.
109     """
110     with conn.cursor() as cur:
111         cur.execute("""INSERT INTO import_osmosis_log
112                        (batchend, batchseq, batchsize, starttime, endtime, event)
113                        SELECT lastimportdate, sequence_id, %s, %s, now(), %s FROM import_status""",
114                     (batchsize, start, event))
115     conn.commit()