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 # don't double quote backslahes, this causes failure
72 # with e.g. the SFA code when it tries to spot slices
73 # created from fed4fire, which to my knowledge is the only
74 # place where a backslash is useful
75 # x = x.replace("\\", "\\\\")
76 x = x.replace("'", "''")
78 elif isinstance(x, (int, float)):
82 elif isinstance(x, (list, tuple, set)):
83 x = 'ARRAY[%s]' % ', '.join([str(PostgreSQL._quote(x)) for x in x])
84 elif hasattr(x, '__pg_repr__'):
87 raise PLCDBError('Cannot quote type %s' % type(x))
91 def quote(self, value):
93 Returns quoted version of the specified value.
95 return PostgreSQL._quote(value)
97 # following is an unsuccessful attempt to re-use lib code as much as possible
98 # def quote(self, value):
99 # # The pgdb._quote function is good enough for general SQL
100 # # quoting, except for array types.
101 # if isinstance (value, (types.ListType, types.TupleType, set)):
102 # 'ARRAY[%s]' % ', '.join( [ str(self.quote(x)) for x in value ] )
105 # # up to PyGreSQL-3.x, function was pgdb._quote
107 # return pgdb._quote(value)
109 # # with PyGreSQL-4.x, use psycopg2's adapt
110 # from psycopg2.extensions import adapt
111 # return adapt (value)
114 def param(cls, name, value):
115 # None is converted to the unquoted string NULL
116 if isinstance(value, type(None)):
118 # True and False are also converted to unquoted strings
119 elif isinstance(value, bool):
121 elif isinstance(value, float):
123 elif not isinstance(value, str):
128 return '%(' + name + ')' + conversion
130 def begin_work(self):
131 # Implicit in pgdb.connect()
135 self.connection.commit()
138 self.connection.rollback()
140 def do(self, query, params=None):
141 cursor = self.execute(query, params)
145 def next_id(self, table_name, primary_key):
146 sequence = "{}_{}_seq".format(table_name, primary_key)
147 sql = "SELECT nextval('{}')".format(sequence)
148 rows = self.selectall(sql, hashref=False)
153 def last_insert_id(self, table_name, primary_key):
154 if isinstance(self.lastrowid, int):
155 sql = "SELECT %s FROM %s WHERE oid = %d" % \
156 (primary_key, table_name, self.lastrowid)
157 rows = self.selectall(sql, hashref=False)
163 # modified for psycopg2-2.0.7
164 # executemany is undefined for SELECT's
165 # see http://www.python.org/dev/peps/pep-0249/
166 # accepts either None, a single dict, a tuple of single dict - in which case it execute's
167 # or a tuple of several dicts, in which case it executemany's
168 def execute(self, query, params=None):
170 cursor = self.cursor()
173 # psycopg2 requires %()s format for all parameters,
174 # regardless of type.
175 # this needs to be done carefully though as with pattern-based filters
176 # we might have percents embedded in the query
177 # so e.g. GetPersons({'email':'*fake*'}) was resulting in .. LIKE '%sake%'
179 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
180 # rewrite wildcards set by Filter.py as '***' into '%'
181 query = query.replace('***', '%')
185 logger.debug('execute0: {}'.format(query))
186 cursor.execute(query)
187 elif isinstance(params, dict):
189 logger.debug('execute-dict: params {} query {}'
190 .format(params, query%params))
191 cursor.execute(query, params)
192 elif isinstance(params, tuple) and len(params) == 1:
194 logger.debug('execute-tuple {}'.format(query%params[0]))
195 cursor.execute(query, params[0])
197 param_seq = (params,)
199 for params in param_seq:
200 logger.debug('executemany {}'.format(query%params))
201 cursor.executemany(query, param_seq)
202 (self.rowcount, self.description, self.lastrowid) = \
203 (cursor.rowcount, cursor.description, cursor.lastrowid)
204 except Exception as e:
209 uuid = subprocess.getoutput("uuidgen")
210 message = "Database error {}: - Query {} - Params {}".format(uuid, query, pformat(params))
211 logger.exception(message)
212 raise PLCDBError("Please contact " + \
213 self.api.config.PLC_NAME + " Support " + \
214 "<" + self.api.config.PLC_MAIL_SUPPORT_ADDRESS + ">" + \
215 " and reference " + uuid)
219 def selectall(self, query, params=None, hashref=True, key_field=None):
221 Return each row as a dictionary keyed on field name (like DBI
222 selectrow_hashref()). If key_field is specified, return rows
223 as a dictionary keyed on the specified field (like DBI
224 selectall_hashref()).
226 If params is specified, the specified parameters will be bound
230 cursor = self.execute(query, params)
231 rows = cursor.fetchall()
234 if hashref or key_field is not None:
235 # Return each row as a dictionary keyed on field name
236 # (like DBI selectrow_hashref()).
237 labels = [column[0] for column in self.description]
238 rows = [dict(list(zip(labels, row))) for row in rows]
240 if key_field is not None and key_field in labels:
241 # Return rows as a dictionary keyed on the specified field
242 # (like DBI selectall_hashref()).
243 return {row[key_field]: row for row in rows}
247 def fields(self, table, notnull=None, hasdef=None):
249 Return the names of the fields of the specified table.
252 if hasattr(self, 'fields_cache'):
253 if (table, notnull, hasdef) in self.fields_cache:
254 return self.fields_cache[(table, notnull, hasdef)]
256 self.fields_cache = {}
258 sql = "SELECT attname FROM pg_attribute, pg_class" \
259 " WHERE pg_class.oid = attrelid" \
260 " AND attnum > 0 AND relname = %(table)s"
262 if notnull is not None:
263 sql += " AND attnotnull is %(notnull)s"
265 if hasdef is not None:
266 sql += " AND atthasdef is %(hasdef)s"
268 rows = self.selectall(sql, locals(), hashref=False)
270 self.fields_cache[(table, notnull, hasdef)] = [row[0] for row in rows]
272 return self.fields_cache[(table, notnull, hasdef)]