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
64 if isinstance(x, DateTimeType):
66 elif isinstance(x, str):
69 if isinstance(x, bytes):
70 x = "'%s'" % str(x).replace("\\", "\\\\").replace("'", "''")
71 elif isinstance(x, (int, float)):
75 elif isinstance(x, (list, tuple, set)):
76 x = 'ARRAY[%s]' % ', '.join([str(PostgreSQL._quote(x)) for x in x])
77 elif hasattr(x, '__pg_repr__'):
80 raise PLCDBError('Cannot quote type %s' % type(x))
84 def quote(self, value):
86 Returns quoted version of the specified value.
88 return PostgreSQL._quote(value)
90 # following is an unsuccessful attempt to re-use lib code as much as possible
91 # def quote(self, value):
92 # # The pgdb._quote function is good enough for general SQL
93 # # quoting, except for array types.
94 # if isinstance (value, (types.ListType, types.TupleType, set)):
95 # 'ARRAY[%s]' % ', '.join( [ str(self.quote(x)) for x in value ] )
98 # # up to PyGreSQL-3.x, function was pgdb._quote
100 # return pgdb._quote(value)
102 # # with PyGreSQL-4.x, use psycopg2's adapt
103 # from psycopg2.extensions import adapt
104 # return adapt (value)
107 def param(cls, name, value):
108 # None is converted to the unquoted string NULL
109 if isinstance(value, type(None)):
111 # True and False are also converted to unquoted strings
112 elif isinstance(value, bool):
114 elif isinstance(value, float):
116 elif not isinstance(value, str):
121 return '%(' + name + ')' + conversion
123 def begin_work(self):
124 # Implicit in pgdb.connect()
128 self.connection.commit()
131 self.connection.rollback()
133 def do(self, query, params=None):
134 cursor = self.execute(query, params)
138 def next_id(self, table_name, primary_key):
139 sequence = "{}_{}_seq".format(table_name, primary_key)
140 sql = "SELECT nextval('{}')".format(sequence)
141 rows = self.selectall(sql, hashref=False)
146 def last_insert_id(self, table_name, primary_key):
147 if isinstance(self.lastrowid, int):
148 sql = "SELECT %s FROM %s WHERE oid = %d" % \
149 (primary_key, table_name, self.lastrowid)
150 rows = self.selectall(sql, hashref=False)
156 # modified for psycopg2-2.0.7
157 # executemany is undefined for SELECT's
158 # see http://www.python.org/dev/peps/pep-0249/
159 # accepts either None, a single dict, a tuple of single dict - in which case it execute's
160 # or a tuple of several dicts, in which case it executemany's
161 def execute(self, query, params=None):
163 cursor = self.cursor()
166 # psycopg2 requires %()s format for all parameters,
167 # regardless of type.
168 # this needs to be done carefully though as with pattern-based filters
169 # we might have percents embedded in the query
170 # so e.g. GetPersons({'email':'*fake*'}) was resulting in .. LIKE '%sake%'
172 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
173 # rewrite wildcards set by Filter.py as '***' into '%'
174 query = query.replace('***', '%')
178 logger.debug('execute0: {}'.format(query))
179 cursor.execute(query)
180 elif isinstance(params, dict):
182 logger.debug('execute-dict: params {} query {}'
183 .format(params, query%params))
184 cursor.execute(query, params)
185 elif isinstance(params, tuple) and len(params) == 1:
187 logger.debug('execute-tuple {}'.format(query%params[0]))
188 cursor.execute(query, params[0])
190 param_seq = (params,)
192 for params in param_seq:
193 logger.debug('executemany {}'.format(query%params))
194 cursor.executemany(query, param_seq)
195 (self.rowcount, self.description, self.lastrowid) = \
196 (cursor.rowcount, cursor.description, cursor.lastrowid)
197 except Exception as e:
202 uuid = subprocess.getoutput("uuidgen")
203 message = "Database error {}: - Query {} - Params {}".format(uuid, query, pformat(params))
204 logger.exception(message)
205 raise PLCDBError("Please contact " + \
206 self.api.config.PLC_NAME + " Support " + \
207 "<" + self.api.config.PLC_MAIL_SUPPORT_ADDRESS + ">" + \
208 " and reference " + uuid)
212 def selectall(self, query, params=None, hashref=True, key_field=None):
214 Return each row as a dictionary keyed on field name (like DBI
215 selectrow_hashref()). If key_field is specified, return rows
216 as a dictionary keyed on the specified field (like DBI
217 selectall_hashref()).
219 If params is specified, the specified parameters will be bound
223 cursor = self.execute(query, params)
224 rows = cursor.fetchall()
227 if hashref or key_field is not None:
228 # Return each row as a dictionary keyed on field name
229 # (like DBI selectrow_hashref()).
230 labels = [column[0] for column in self.description]
231 rows = [dict(list(zip(labels, row))) for row in rows]
233 if key_field is not None and key_field in labels:
234 # Return rows as a dictionary keyed on the specified field
235 # (like DBI selectall_hashref()).
236 return {row[key_field]: row for row in rows}
240 def fields(self, table, notnull=None, hasdef=None):
242 Return the names of the fields of the specified table.
245 if hasattr(self, 'fields_cache'):
246 if (table, notnull, hasdef) in self.fields_cache:
247 return self.fields_cache[(table, notnull, hasdef)]
249 self.fields_cache = {}
251 sql = "SELECT attname FROM pg_attribute, pg_class" \
252 " WHERE pg_class.oid = attrelid" \
253 " AND attnum > 0 AND relname = %(table)s"
255 if notnull is not None:
256 sql += " AND attnotnull is %(notnull)s"
258 if hasdef is not None:
259 sql += " AND atthasdef is %(hasdef)s"
261 rows = self.selectall(sql, locals(), hashref=False)
263 self.fields_cache[(table, notnull, hasdef)] = [row[0] for row in rows]
265 return self.fields_cache[(table, notnull, hasdef)]