2 Specialised connection and cursor functions.
7 import psycopg2.extensions
10 from ..errors import UsageError
12 class _Cursor(psycopg2.extras.DictCursor):
13 """ A cursor returning dict-like objects and providing specialised
17 def execute(self, query, args=None): # pylint: disable=W0221
18 """ Query execution that logs the SQL query when debugging is enabled.
20 logger = logging.getLogger()
21 logger.debug(self.mogrify(query, args).decode('utf-8'))
23 super().execute(query, args)
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.
29 self.execute(sql, args)
31 if self.rowcount != 1:
32 raise RuntimeError("Query did not return a single row.")
34 return self.fetchone()[0]
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.
42 def cursor(self, cursor_factory=_Cursor, **kwargs):
43 """ Return a new cursor. By default the specialised cursor is returned.
45 return super().cursor(cursor_factory=cursor_factory, **kwargs)
48 def table_exists(self, table):
49 """ Check that a table with the given name exists in the database.
51 with self.cursor() as cur:
52 num = cur.scalar("""SELECT count(*) FROM pg_tables
53 WHERE tablename = %s and schemaname = 'public'""", (table, ))
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
62 with self.cursor() as cur:
63 cur.execute("""SELECT tablename FROM pg_indexes
64 WHERE indexname = %s and schemaname = 'public'""", (index, ))
70 return row[0] == table
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.
79 version = self.server_version
81 return (version / 10000, (version % 10000) / 100)
83 return (version / 10000, version % 10000)
86 """ Open a connection to the database using the specialised connection
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