Debian Codegraph @

powa_collector/customconn.py

raw
1 import psycopg2
2 from psycopg2.extensions import connection as _connection, cursor as _cursor
3 from psycopg2.extras import DictCursor
4 import time
5
6 from powa_collector.utils import get_powa_version
7
8 class CustomConnection(_connection):
9 """
10 Custom psycopg2 connection class that takes care of expanding extension
11 schema and optionally logs various information at debug level, both on
12 successful execution and in case of error.
13
14 Supports either plain cursor (through CustomCursor) or DictCursor
15 (through CustomDictCursor).
16
17 Before execution, and if a _nsps object is found cached in the connection,
18 the query will be formatted using its _nsps dict, which contains a list of
19 extension_name -> escaped_schema_name mapping.
20 All you need to do is pass query strings of the form
21 SELECT ... FROM {extension_name}.some_relation ...
22 """
23 def initialize(self, logger, debug):
24 self._logger = logger
25 self._debug = debug
26
27 def cursor(self, *args, **kwargs):
28 factory = kwargs.get('cursor_factory')
29
30 if factory is None:
31 kwargs['cursor_factory'] = CustomCursor
32 elif factory == DictCursor:
33 kwargs['cursor_factory'] = CustomDictCursor
34 else:
35 msg = "Unsupported cursor_factory: %s" % factory.__name__
36 self._logger.error(msg)
37 raise Exception(msg)
38
39 return _connection.cursor(self, *args, **kwargs)
40
41
42 class CustomDictCursor(DictCursor):
43 def execute(self, query, params=None):
44 query = resolve_nsps(query, self.connection)
45
46 self.timestamp = time.time()
47 try:
48 return super(CustomDictCursor, self).execute(query, params)
49 except Exception as e:
50 log_query(self, query, params, e)
51 raise e
52 finally:
53 log_query(self, query, params)
54
55
56 class CustomCursor(_cursor):
57 def execute(self, query, params=None):
58 query = resolve_nsps(query, self.connection)
59
60 self.timestamp = time.time()
61 try:
62 return super(CustomCursor, self).execute(query, params)
63 except Exception as e:
64 log_query(self, query, params, e)
65 raise e
66 finally:
67 log_query(self, query, params)
68
69
70 def resolve_nsps(query, connection):
71 if hasattr(connection, '_nsps'):
72 return query.format(**connection._nsps)
73
74 return query
75
76
77 def log_query(cls, query, params=None, exception=None):
78 t = round((time.time() - cls.timestamp) * 1000, 2)
79
80 fmt = ''
81 if exception is not None:
82 fmt = "Error during query execution:\n{}\n".format(exception)
83
84 fmt += "query on {dsn}: {ms} ms\n{query}"
85 if params is not None:
86 fmt += "\n{params}"
87
88 cls.connection._logger.debug(fmt.format(ms=t, dsn=cls.connection.dsn,
89 query=query, params=params))
90
91
92 def get_connection(logger, debug, *args, **kwargs):
93 """
94 Create a new connection using the CustomConnection factory.
95
96 For handling connections on a specific database rather than the dedicated
97 powa database (for the per-database snapshot feature) caller can specify an
98 "override_dbname" named argument that will replace the "dbname" named
99 argument. Note that in that case the extension schema expansion feature is
100 not available.
101 """
102 new_dbname = kwargs.pop("override_dbname", None)
103
104 if (new_dbname is not None):
105 # If caller provided an override_dbname it better also provided a
106 # dbname argument (which should be the case for remote server standard
107 # connection kwargs, but not the repository server).
108 if ('dbname' not in kwargs):
109 msg = "Tried to specify an override_dbname without providing " \
110 "a dbname. kwargs:\n%r" % kwargs
111 self._logger.error(msg)
112 raise Exception(msg)
113 kwargs['dbname'] = new_dbname
114
115 kwargs['connection_factory'] = CustomConnection
116
117 conn = psycopg2.connect(*args, **kwargs)
118 conn.initialize(logger, debug)
119
120 cur = conn.cursor()
121
122 # The automatic extension schema qualification is only available for
123 # standard global and module connections, not per-database module
124 # connections.
125 if (new_dbname is None):
126 # retrieve and cache the quoted schema for all installed extensions
127 logger.debug("Retrieving extension schemas...")
128 cur.execute("""SELECT extname, quote_ident(nspname) AS nsp
129 FROM pg_catalog.pg_extension e
130 JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace""")
131 ext_nsps = {row[0]: row[1] for row in cur.fetchall()}
132 logger.debug("extension schemas: %r" % ext_nsps)
133 conn._nsps = ext_nsps
134
135 # If using powa 5+ (or connecting to a non-powa database) make sure
136 # everything has to be fully qualified.
137 powa_ver = get_powa_version(conn)
138 if (powa_ver is None or int(powa_ver[0][0]) >= 5):
139 logger.debug("Setting secure search_path")
140 cur.execute("SET search_path TO 'pg_catalog'");
141
142 cur.close()
143 conn.commit()
144
145 return conn