2 # PostgreSQL database interface.
3 # Sort of like DBI(3) (Database independent interface for Perl).
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 # Copyright (C) 2006 The Trustees of Princeton University
8 # pylint: disable=c0103, c0111
12 from pprint import pformat
13 from datetime import datetime as DateTimeType
16 import psycopg2.extensions
17 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
18 # UNICODEARRAY not exported yet
19 psycopg2.extensions.register_type(psycopg2._psycopg.UNICODEARRAY)
21 from PLC.Logger import logger
22 #from PLC.Debug import profile
23 from PLC.Faults import *
26 def __init__(self, api):
30 self.connection = None
33 if self.connection is None:
34 # (Re)initialize database connection
36 # Try UNIX socket first
37 self.connection = psycopg2.connect(
38 user=self.api.config.PLC_DB_USER,
39 password=self.api.config.PLC_DB_PASSWORD,
40 database=self.api.config.PLC_DB_NAME)
41 except psycopg2.OperationalError:
43 self.connection = psycopg2.connect(
44 user=self.api.config.PLC_DB_USER,
45 password=self.api.config.PLC_DB_PASSWORD,
46 database=self.api.config.PLC_DB_NAME,
47 host=self.api.config.PLC_DB_HOST,
48 port=self.api.config.PLC_DB_PORT)
49 self.connection.set_client_encoding("UNICODE")
51 (self.rowcount, self.description, self.lastrowid) = \
54 return self.connection.cursor()
57 if self.connection is not None:
58 self.connection.close()
59 self.connection = None
62 # From pgdb, and simplify code
63 # this is **very different** from the python2 code !
65 if isinstance(x, DateTimeType):
67 elif isinstance(x, bytes):
70 if isinstance(x, str):
71 x = x.replace("\\", "\\\\").replace("'", "''")
73 elif isinstance(x, (int, float)):
77 elif isinstance(x, (list, tuple, set)):
78 x = 'ARRAY[%s]' % ', '.join([str(PostgreSQL._quote(x)) for x in x])
79 elif hasattr(x, '__pg_repr__'):
82 raise PLCDBError('Cannot quote type %s' % type(x))
86 def quote(self, value):
88 Returns quoted version of the specified value.
90 return PostgreSQL._quote(value)
92 # following is an unsuccessful attempt to re-use lib code as much as possible
93 # def quote(self, value):
94 # # The pgdb._quote function is good enough for general SQL
95 # # quoting, except for array types.
96 # if isinstance (value, (types.ListType, types.TupleType, set)):
97 # 'ARRAY[%s]' % ', '.join( [ str(self.quote(x)) for x in value ] )
100 # # up to PyGreSQL-3.x, function was pgdb._quote
102 # return pgdb._quote(value)
104 # # with PyGreSQL-4.x, use psycopg2's adapt
105 # from psycopg2.extensions import adapt
106 # return adapt (value)
109 def param(cls, name, value):
110 # None is converted to the unquoted string NULL
111 if isinstance(value, type(None)):
113 # True and False are also converted to unquoted strings
114 elif isinstance(value, bool):
116 elif isinstance(value, float):
118 elif not isinstance(value, str):
123 return '%(' + name + ')' + conversion
125 def begin_work(self):
126 # Implicit in pgdb.connect()
130 self.connection.commit()
133 self.connection.rollback()
135 def do(self, query, params=None):
136 cursor = self.execute(query, params)
140 def next_id(self, table_name, primary_key):
141 sequence = "{}_{}_seq".format(table_name, primary_key)
142 sql = "SELECT nextval('{}')".format(sequence)
143 rows = self.selectall(sql, hashref=False)
148 def last_insert_id(self, table_name, primary_key):
149 if isinstance(self.lastrowid, int):
150 sql = "SELECT %s FROM %s WHERE oid = %d" % \
151 (primary_key, table_name, self.lastrowid)
152 rows = self.selectall(sql, hashref=False)
158 # modified for psycopg2-2.0.7
159 # executemany is undefined for SELECT's
160 # see http://www.python.org/dev/peps/pep-0249/
161 # accepts either None, a single dict, a tuple of single dict - in which case it execute's
162 # or a tuple of several dicts, in which case it executemany's
163 def execute(self, query, params=None):
165 cursor = self.cursor()
168 # psycopg2 requires %()s format for all parameters,
169 # regardless of type.
170 # this needs to be done carefully though as with pattern-based filters
171 # we might have percents embedded in the query
172 # so e.g. GetPersons({'email':'*fake*'}) was resulting in .. LIKE '%sake%'
174 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
175 # rewrite wildcards set by Filter.py as '***' into '%'
176 query = query.replace('***', '%')
180 logger.debug('execute0: {}'.format(query))
181 cursor.execute(query)
182 elif isinstance(params, dict):
184 logger.debug('execute-dict: params {} query {}'
185 .format(params, query%params))
186 cursor.execute(query, params)
187 elif isinstance(params, tuple) and len(params) == 1:
189 logger.debug('execute-tuple {}'.format(query%params[0]))
190 cursor.execute(query, params[0])
192 param_seq = (params,)
194 for params in param_seq:
195 logger.debug('executemany {}'.format(query%params))
196 cursor.executemany(query, param_seq)
197 (self.rowcount, self.description, self.lastrowid) = \
198 (cursor.rowcount, cursor.description, cursor.lastrowid)
199 except Exception as e:
204 uuid = subprocess.getoutput("uuidgen")
205 message = "Database error {}: - Query {} - Params {}".format(uuid, query, pformat(params))
206 logger.exception(message)
207 raise PLCDBError("Please contact " + \
208 self.api.config.PLC_NAME + " Support " + \
209 "<" + self.api.config.PLC_MAIL_SUPPORT_ADDRESS + ">" + \
210 " and reference " + uuid)
214 def selectall(self, query, params=None, hashref=True, key_field=None):
216 Return each row as a dictionary keyed on field name (like DBI
217 selectrow_hashref()). If key_field is specified, return rows
218 as a dictionary keyed on the specified field (like DBI
219 selectall_hashref()).
221 If params is specified, the specified parameters will be bound
225 cursor = self.execute(query, params)
226 rows = cursor.fetchall()
229 if hashref or key_field is not None:
230 # Return each row as a dictionary keyed on field name
231 # (like DBI selectrow_hashref()).
232 labels = [column[0] for column in self.description]
233 rows = [dict(list(zip(labels, row))) for row in rows]
235 if key_field is not None and key_field in labels:
236 # Return rows as a dictionary keyed on the specified field
237 # (like DBI selectall_hashref()).
238 return {row[key_field]: row for row in rows}
242 def fields(self, table, notnull=None, hasdef=None):
244 Return the names of the fields of the specified table.
247 if hasattr(self, 'fields_cache'):
248 if (table, notnull, hasdef) in self.fields_cache:
249 return self.fields_cache[(table, notnull, hasdef)]
251 self.fields_cache = {}
253 sql = "SELECT attname FROM pg_attribute, pg_class" \
254 " WHERE pg_class.oid = attrelid" \
255 " AND attnum > 0 AND relname = %(table)s"
257 if notnull is not None:
258 sql += " AND attnotnull is %(notnull)s"
260 if hasdef is not None:
261 sql += " AND atthasdef is %(hasdef)s"
263 rows = self.selectall(sql, locals(), hashref=False)
265 self.fields_cache[(table, notnull, hasdef)] = [row[0] for row in rows]
267 return self.fields_cache[(table, notnull, hasdef)]