2 Specialised psycopg2 cursor with shortcut functions useful for testing.
6 class CursorForTesting(psycopg2.extras.DictCursor):
7 """ Extension to the DictCursor class that provides execution
8 short-cuts that simplify writing assertions.
11 def scalar(self, sql, params=None):
12 """ Execute a query with a single return value and return this value.
13 Raises an assertion when not exactly one row is returned.
15 self.execute(sql, params)
16 assert self.rowcount == 1
17 return self.fetchone()[0]
20 def row_set(self, sql, params=None):
21 """ Execute a query and return the result as a set of tuples.
22 Fails when the SQL command returns duplicate rows.
24 self.execute(sql, params)
26 result = set((tuple(row) for row in self))
27 assert len(result) == self.rowcount
32 def table_exists(self, table):
33 """ Check that a table with the given name exists in the database.
35 num = self.scalar("""SELECT count(*) FROM pg_tables
36 WHERE tablename = %s""", (table, ))
40 def index_exists(self, table, index):
41 """ Check that an indexwith the given name exists on the given table.
43 num = self.scalar("""SELECT count(*) FROM pg_indexes
44 WHERE tablename = %s and indexname = %s""",
49 def table_rows(self, table, where=None):
50 """ Return the number of rows in the given table.
53 return self.scalar('SELECT count(*) FROM ' + table)
55 return self.scalar('SELECT count(*) FROM {} WHERE {}'.format(table, where))
58 def execute_values(self, *args, **kwargs):
59 """ Execute the execute_values() function on the cursor.
61 psycopg2.extras.execute_values(self, *args, **kwargs)