2 # PostgreSQL database interface. Sort of like DBI(3) (Database
3 # independent interface for Perl).
10 from pprint import pformat
11 from types import StringTypes, NoneType
14 import psycopg2.extensions
15 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
16 # UNICODEARRAY not exported yet
17 psycopg2.extensions.register_type(psycopg2._psycopg.UNICODEARRAY)
19 # allow to run sfa2wsdl if this is missing (for mac)
22 except: print >> sys.stderr, "WARNING, could not import pgdb"
24 from sfa.util.faults import *
25 from sfa.util.sfalogging import sfa_logger
28 is8bit = re.compile("[\x80-\xff]").search
30 def unicast(typecast):
32 pgdb returns raw UTF-8 strings. This function casts strings that
33 apppear to contain non-ASCII characters to unicode objects.
36 def wrapper(*args, **kwds):
37 value = typecast(*args, **kwds)
39 # pgdb always encodes unicode objects as UTF-8 regardless of
40 # the DB encoding (and gives you no option for overriding
41 # the encoding), so always decode 8-bit objects as UTF-8.
42 if isinstance(value, str) and is8bit(value):
43 value = unicode(value, "utf-8")
49 pgdb.pgdbTypeCache.typecast = unicast(pgdb.pgdbTypeCache.typecast)
51 def handle_exception(f):
52 def wrapper(*args, **kwds):
53 try: return f(*args, **kwds)
54 except Exception, fault:
55 raise SfaDBError(str(fault))
59 def __init__(self, config):
63 self.connection = None
67 if self.connection is None:
68 # (Re)initialize database connection
71 # Try UNIX socket first
72 self.connection = psycopg2.connect(user = self.config.SFA_PLC_DB_USER,
73 password = self.config.SFA_PLC_DB_PASSWORD,
74 database = self.config.SFA_PLC_DB_NAME)
75 except psycopg2.OperationalError:
77 self.connection = psycopg2.connect(user = self.config.SFA_PLC_DB_USER,
78 password = self.config.SFA_PLC_DB_PASSWORD,
79 database = self.config.SFA_PLC_DB_NAME,
80 host = self.config.SFA_PLC_DB_HOST,
81 port = self.config.SFA_PLC_DB_PORT)
82 self.connection.set_client_encoding("UNICODE")
84 self.connection = pgdb.connect(user = self.config.SFA_PLC_DB_USER,
85 password = self.config.SFA_PLC_DB_PASSWORD,
86 host = "%s:%d" % (self.config.SFA_PLC_DB_HOST, self.config.SFA_PLC_DB_PORT),
87 database = self.config.SFA_PLC_DB_NAME)
89 (self.rowcount, self.description, self.lastrowid) = \
92 return self.connection.cursor()
95 if self.connection is not None:
96 self.connection.close()
97 self.connection = None
99 def quote(self, value):
101 Returns quoted version of the specified value.
104 # The pgdb._quote function is good enough for general SQL
105 # quoting, except for array types.
106 if isinstance(value, (list, tuple, set)):
107 return "ARRAY[%s]" % ", ".join(map, self.quote, value)
109 return pgdb._quote(value)
111 quote = classmethod(quote)
113 def param(self, name, value):
114 # None is converted to the unquoted string NULL
115 if isinstance(value, NoneType):
117 # True and False are also converted to unquoted strings
118 elif isinstance(value, bool):
120 elif isinstance(value, float):
122 elif not isinstance(value, StringTypes):
127 return '%(' + name + ')' + conversion
129 param = classmethod(param)
131 def begin_work(self):
132 # Implicit in pgdb.connect()
136 self.connection.commit()
139 self.connection.rollback()
141 def do(self, query, params = None):
142 cursor = self.execute(query, params)
146 def next_id(self, table_name, primary_key):
147 sequence = "%(table_name)s_%(primary_key)s_seq" % locals()
148 sql = "SELECT nextval('%(sequence)s')" % locals()
149 rows = self.selectall(sql, hashref = False)
154 def last_insert_id(self, table_name, primary_key):
155 if isinstance(self.lastrowid, int):
156 sql = "SELECT %s FROM %s WHERE oid = %d" % \
157 (primary_key, table_name, self.lastrowid)
158 rows = self.selectall(sql, hashref = False)
164 # modified for psycopg2-2.0.7
165 # executemany is undefined for SELECT's
166 # see http://www.python.org/dev/peps/pep-0249/
167 # accepts either None, a single dict, a tuple of single dict - in which case it execute's
168 # or a tuple of several dicts, in which case it executemany's
169 def execute(self, query, params = None):
171 cursor = self.cursor()
174 # psycopg2 requires %()s format for all parameters,
175 # regardless of type.
176 # this needs to be done carefully though as with pattern-based filters
177 # we might have percents embedded in the query
178 # so e.g. GetPersons({'email':'*fake*'}) was resulting in .. LIKE '%sake%'
180 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
181 # rewrite wildcards set by Filter.py as '***' into '%'
182 query = query.replace ('***','%')
186 sfa_logger().debug('execute0 %r'%query)
187 cursor.execute(query)
188 elif isinstance(params,dict):
190 sfa_logger().debug('execute-dict: params=[%r] query=[%r]'%(params,query%params))
191 cursor.execute(query,params)
192 elif isinstance(params,tuple) and len(params)==1:
194 sfa_logger().debug('execute-tuple %r'%(query%params[0]))
195 cursor.execute(query,params[0])
199 for params in param_seq:
200 sfa_logger().debug('executemany %r'%(query%params))
201 cursor.executemany(query, param_seq)
202 (self.rowcount, self.description, self.lastrowid) = \
203 (cursor.rowcount, cursor.description, cursor.lastrowid)
209 uuid = commands.getoutput("uuidgen")
210 sfa_logger().error("Database error %s:" % uuid)
211 sfa_logger().error("Exception=%r"%e)
212 sfa_logger().error("Query=%r"%query)
213 sfa_logger().error("Params=%r"%pformat(params))
214 sfa_logger().log_exc("PostgreSQL.execute caught exception")
215 raise SfaDBError("Please contact support: %s" % str(e))
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(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 dict([(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 self.fields_cache.has_key((table, notnull, hasdef)):
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)]