]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/db/connection.py
improve deadlock detection for various versions of psycopg2
[nominatim.git] / nominatim / db / connection.py
1 """
2 Specialised connection and cursor functions.
3 """
4 import logging
5
6 import psycopg2
7 import psycopg2.extensions
8 import psycopg2.extras
9
10 from ..errors import UsageError
11
12 class _Cursor(psycopg2.extras.DictCursor):
13     """ A cursor returning dict-like objects and providing specialised
14         execution functions.
15     """
16
17     def execute(self, query, args=None): # pylint: disable=W0221
18         """ Query execution that logs the SQL query when debugging is enabled.
19         """
20         logger = logging.getLogger()
21         logger.debug(self.mogrify(query, args).decode('utf-8'))
22
23         super().execute(query, args)
24
25     def scalar(self, sql, args=None):
26         """ Execute query that returns a single value. The value is returned.
27             If the query yields more than one row, a ValueError is raised.
28         """
29         self.execute(sql, args)
30
31         if self.rowcount != 1:
32             raise RuntimeError("Query did not return a single row.")
33
34         return self.fetchone()[0]
35
36
37 class _Connection(psycopg2.extensions.connection):
38     """ A connection that provides the specialised cursor by default and
39         adds convenience functions for administrating the database.
40     """
41
42     def cursor(self, cursor_factory=_Cursor, **kwargs):
43         """ Return a new cursor. By default the specialised cursor is returned.
44         """
45         return super().cursor(cursor_factory=cursor_factory, **kwargs)
46
47
48     def table_exists(self, table):
49         """ Check that a table with the given name exists in the database.
50         """
51         with self.cursor() as cur:
52             num = cur.scalar("""SELECT count(*) FROM pg_tables
53                                 WHERE tablename = %s and schemaname = 'public'""", (table, ))
54             return num == 1
55
56
57     def index_exists(self, index, table=None):
58         """ Check that an index with the given name exists in the database.
59             If table is not None then the index must relate to the given
60             table.
61         """
62         with self.cursor() as cur:
63             cur.execute("""SELECT tablename FROM pg_indexes
64                            WHERE indexname = %s and schemaname = 'public'""", (index, ))
65             if cur.rowcount == 0:
66                 return False
67
68             if table is not None:
69                 row = cur.fetchone()
70                 return row[0] == table
71
72         return True
73
74
75     def server_version_tuple(self):
76         """ Return the server version as a tuple of (major, minor).
77             Converts correctly for pre-10 and post-10 PostgreSQL versions.
78         """
79         version = self.server_version
80         if version < 100000:
81             return (version / 10000, (version % 10000) / 100)
82
83         return (version / 10000, version % 10000)
84
85 def connect(dsn):
86     """ Open a connection to the database using the specialised connection
87         factory.
88     """
89     try:
90         return psycopg2.connect(dsn, connection_factory=_Connection)
91     except psycopg2.OperationalError as err:
92         raise UsageError("Cannot connect to database: {}".format(err)) from err