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 SfaDBError
25 from sfa.util.sfalogging import logger
26 from sfa.storage.filter import Filter
29 is8bit = re.compile("[\x80-\xff]").search
31 def unicast(typecast):
33 pgdb returns raw UTF-8 strings. This function casts strings that
34 apppear to contain non-ASCII characters to unicode objects.
37 def wrapper(*args, **kwds):
38 value = typecast(*args, **kwds)
40 # pgdb always encodes unicode objects as UTF-8 regardless of
41 # the DB encoding (and gives you no option for overriding
42 # the encoding), so always decode 8-bit objects as UTF-8.
43 if isinstance(value, str) and is8bit(value):
44 value = unicode(value, "utf-8")
50 pgdb.pgdbTypeCache.typecast = unicast(pgdb.pgdbTypeCache.typecast)
52 def handle_exception(f):
53 def wrapper(*args, **kwds):
54 try: return f(*args, **kwds)
55 except Exception, fault:
56 raise SfaDBError(str(fault))
60 def __init__(self, config):
64 self.connection = None
68 if self.connection is None:
69 # (Re)initialize database connection
72 # Try UNIX socket first
73 self.connection = psycopg2.connect(user = self.config.SFA_DB_USER,
74 password = self.config.SFA_DB_PASSWORD,
75 database = self.config.SFA_DB_NAME)
76 except psycopg2.OperationalError:
78 self.connection = psycopg2.connect(user = self.config.SFA_DB_USER,
79 password = self.config.SFA_DB_PASSWORD,
80 database = self.config.SFA_DB_NAME,
81 host = self.config.SFA_DB_HOST,
82 port = self.config.SFA_DB_PORT)
83 self.connection.set_client_encoding("UNICODE")
85 self.connection = pgdb.connect(user = self.config.SFA_DB_USER,
86 password = self.config.SFA_DB_PASSWORD,
87 host = "%s:%d" % (self.config.SFA_DB_HOST, self.config.SFA_DB_PORT),
88 database = self.config.SFA_DB_NAME)
90 (self.rowcount, self.description, self.lastrowid) = \
93 return self.connection.cursor()
96 if self.connection is not None:
97 self.connection.close()
98 self.connection = None
100 def quote(self, value):
102 Returns quoted version of the specified value.
105 # The pgdb._quote function is good enough for general SQL
106 # quoting, except for array types.
107 if isinstance(value, (list, tuple, set)):
108 return "ARRAY[%s]" % ", ".join(map, self.quote, value)
110 return Filter._quote(value)
112 quote = classmethod(quote)
114 def param(self, name, value):
115 # None is converted to the unquoted string NULL
116 if isinstance(value, NoneType):
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, StringTypes):
128 return '%(' + name + ')' + conversion
130 param = classmethod(param)
132 def begin_work(self):
133 # Implicit in pgdb.connect()
137 self.connection.commit()
140 self.connection.rollback()
142 def do(self, query, params = None):
143 cursor = self.execute(query, params)
147 def next_id(self, table_name, primary_key):
148 sequence = "%(table_name)s_%(primary_key)s_seq" % locals()
149 sql = "SELECT nextval('%(sequence)s')" % locals()
150 rows = self.selectall(sql, hashref = False)
155 def last_insert_id(self, table_name, primary_key):
156 if isinstance(self.lastrowid, int):
157 sql = "SELECT %s FROM %s WHERE oid = %d" % \
158 (primary_key, table_name, self.lastrowid)
159 rows = self.selectall(sql, hashref = False)
165 # modified for psycopg2-2.0.7
166 # executemany is undefined for SELECT's
167 # see http://www.python.org/dev/peps/pep-0249/
168 # accepts either None, a single dict, a tuple of single dict - in which case it execute's
169 # or a tuple of several dicts, in which case it executemany's
170 def execute(self, query, params = None):
172 cursor = self.cursor()
175 # psycopg2 requires %()s format for all parameters,
176 # regardless of type.
177 # this needs to be done carefully though as with pattern-based filters
178 # we might have percents embedded in the query
179 # so e.g. GetPersons({'email':'*fake*'}) was resulting in .. LIKE '%sake%'
181 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
182 # rewrite wildcards set by Filter.py as '***' into '%'
183 query = query.replace ('***','%')
187 logger.debug('execute0 %r'%query)
188 cursor.execute(query)
189 elif isinstance(params,dict):
191 logger.debug('execute-dict: params=[%r] query=[%r]'%(params,query%params))
192 cursor.execute(query,params)
193 elif isinstance(params,tuple) and len(params)==1:
195 logger.debug('execute-tuple %r'%(query%params[0]))
196 cursor.execute(query,params[0])
200 for params in param_seq:
201 logger.debug('executemany %r'%(query%params))
202 cursor.executemany(query, param_seq)
203 (self.rowcount, self.description, self.lastrowid) = \
204 (cursor.rowcount, cursor.description, cursor.lastrowid)
210 uuid = commands.getoutput("uuidgen")
211 logger.error("Database error %s:" % uuid)
212 logger.error("Exception=%r"%e)
213 logger.error("Query=%r"%query)
214 logger.error("Params=%r"%pformat(params))
215 logger.log_exc("PostgreSQL.execute caught exception")
216 raise SfaDBError("Please contact support: %s" % str(e))
220 def selectall(self, query, params = None, hashref = True, key_field = None):
222 Return each row as a dictionary keyed on field name (like DBI
223 selectrow_hashref()). If key_field is specified, return rows
224 as a dictionary keyed on the specified field (like DBI
225 selectall_hashref()).
227 If params is specified, the specified parameters will be bound
231 cursor = self.execute(query, params)
232 rows = cursor.fetchall()
235 if hashref or key_field is not None:
236 # Return each row as a dictionary keyed on field name
237 # (like DBI selectrow_hashref()).
238 labels = [column[0] for column in self.description]
239 rows = [dict(zip(labels, row)) for row in rows]
241 if key_field is not None and key_field in labels:
242 # Return rows as a dictionary keyed on the specified field
243 # (like DBI selectall_hashref()).
244 return dict([(row[key_field], row) for row in rows])
248 def fields(self, table, notnull = None, hasdef = None):
250 Return the names of the fields of the specified table.
253 if hasattr(self, 'fields_cache'):
254 if self.fields_cache.has_key((table, notnull, hasdef)):
255 return self.fields_cache[(table, notnull, hasdef)]
257 self.fields_cache = {}
259 sql = "SELECT attname FROM pg_attribute, pg_class" \
260 " WHERE pg_class.oid = attrelid" \
261 " AND attnum > 0 AND relname = %(table)s"
263 if notnull is not None:
264 sql += " AND attnotnull is %(notnull)s"
266 if hasdef is not None:
267 sql += " AND atthasdef is %(hasdef)s"
269 rows = self.selectall(sql, locals(), hashref = False)
271 self.fields_cache[(table, notnull, hasdef)] = [row[0] for row in rows]
273 return self.fields_cache[(table, notnull, hasdef)]