2 # PostgreSQL database interface. Sort of like DBI(3) (Database
3 # independent interface for Perl).
8 import psycopg2.extensions
9 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
10 # UNICODEARRAY not exported yet
11 psycopg2.extensions.register_type(psycopg2._psycopg.UNICODEARRAY)
14 from types import StringTypes, NoneType
18 from pprint import pformat
20 from sfa.util.faults import *
21 from sfa.util.debug import *
24 is8bit = re.compile("[\x80-\xff]").search
26 def unicast(typecast):
28 pgdb returns raw UTF-8 strings. This function casts strings that
29 apppear to contain non-ASCII characters to unicode objects.
32 def wrapper(*args, **kwds):
33 value = typecast(*args, **kwds)
35 # pgdb always encodes unicode objects as UTF-8 regardless of
36 # the DB encoding (and gives you no option for overriding
37 # the encoding), so always decode 8-bit objects as UTF-8.
38 if isinstance(value, str) and is8bit(value):
39 value = unicode(value, "utf-8")
45 pgdb.pgdbTypeCache.typecast = unicast(pgdb.pgdbTypeCache.typecast)
47 def handle_exception(f):
48 def wrapper(*args, **kwds):
49 try: return f(*args, **kwds)
50 except Exception, fault:
51 raise SfaDBError(str(fault))
55 def __init__(self, config):
59 self.connection = None
63 if self.connection is None:
64 # (Re)initialize database connection
67 # Try UNIX socket first
68 self.connection = psycopg2.connect(user = self.config.SFA_PLC_DB_USER,
69 password = self.config.SFA_PLC_DB_PASSWORD,
70 database = self.config.SFA_PLC_DB_NAME)
71 except psycopg2.OperationalError:
73 self.connection = psycopg2.connect(user = self.config.SFA_PLC_DB_USER,
74 password = self.config.SFA_PLC_DB_PASSWORD,
75 database = self.config.SFA_PLC_DB_NAME,
76 host = self.config.SFA_PLC_DB_HOST,
77 port = self.config.SFA_PLC_DB_PORT)
78 self.connection.set_client_encoding("UNICODE")
80 self.connection = pgdb.connect(user = self.config.SFA_PLC_DB_USER,
81 password = self.config.SFA_PLC_DB_PASSWORD,
82 host = "%s:%d" % (self.config.SFA_PLC_DB_HOST, self.config.SFA_PLC_DB_PORT),
83 database = self.config.SFA_PLC_DB_NAME)
85 (self.rowcount, self.description, self.lastrowid) = \
88 return self.connection.cursor()
91 if self.connection is not None:
92 self.connection.close()
93 self.connection = None
95 def quote(self, value):
97 Returns quoted version of the specified value.
100 # The pgdb._quote function is good enough for general SQL
101 # quoting, except for array types.
102 if isinstance(value, (list, tuple, set)):
103 return "ARRAY[%s]" % ", ".join(map, self.quote, value)
105 return pgdb._quote(value)
107 quote = classmethod(quote)
109 def param(self, name, value):
110 # None is converted to the unquoted string NULL
111 if isinstance(value, NoneType):
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, StringTypes):
123 return '%(' + name + ')' + conversion
125 param = classmethod(param)
127 def begin_work(self):
128 # Implicit in pgdb.connect()
132 self.connection.commit()
135 self.connection.rollback()
137 def do(self, query, params = None):
138 cursor = self.execute(query, params)
142 def next_id(self, table_name, primary_key):
143 sequence = "%(table_name)s_%(primary_key)s_seq" % locals()
144 sql = "SELECT nextval('%(sequence)s')" % locals()
145 rows = self.selectall(sql, hashref = False)
150 def last_insert_id(self, table_name, primary_key):
151 if isinstance(self.lastrowid, int):
152 sql = "SELECT %s FROM %s WHERE oid = %d" % \
153 (primary_key, table_name, self.lastrowid)
154 rows = self.selectall(sql, hashref = False)
160 # modified for psycopg2-2.0.7
161 # executemany is undefined for SELECT's
162 # see http://www.python.org/dev/peps/pep-0249/
163 # accepts either None, a single dict, a tuple of single dict - in which case it execute's
164 # or a tuple of several dicts, in which case it executemany's
165 def execute(self, query, params = None):
167 cursor = self.cursor()
170 # psycopg2 requires %()s format for all parameters,
171 # regardless of type.
172 # this needs to be done carefully though as with pattern-based filters
173 # we might have percents embedded in the query
174 # so e.g. GetPersons({'email':'*fake*'}) was resulting in .. LIKE '%sake%'
176 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
177 # rewrite wildcards set by Filter.py as '***' into '%'
178 query = query.replace ('***','%')
182 print >> log,'execute0',query
183 cursor.execute(query)
184 elif isinstance(params,dict):
186 print >> log,'execute-dict: params',params,'query',query%params
187 cursor.execute(query,params)
188 elif isinstance(params,tuple) and len(params)==1:
190 print >> log,'execute-tuple',query%params[0]
191 cursor.execute(query,params[0])
195 for params in param_seq:
196 print >> log,'executemany',query%params
197 cursor.executemany(query, param_seq)
198 (self.rowcount, self.description, self.lastrowid) = \
199 (cursor.rowcount, cursor.description, cursor.lastrowid)
205 uuid = commands.getoutput("uuidgen")
206 print >> log, "Database error %s:" % uuid
208 print >> log, "Query:"
210 print >> log, "Params:"
211 print >> log, pformat(params)
212 raise SfaDBError("Please contact support: %s" % str(e))
216 def selectall(self, query, params = None, hashref = True, key_field = None):
218 Return each row as a dictionary keyed on field name (like DBI
219 selectrow_hashref()). If key_field is specified, return rows
220 as a dictionary keyed on the specified field (like DBI
221 selectall_hashref()).
223 If params is specified, the specified parameters will be bound
227 cursor = self.execute(query, params)
228 rows = cursor.fetchall()
231 if hashref or key_field is not None:
232 # Return each row as a dictionary keyed on field name
233 # (like DBI selectrow_hashref()).
234 labels = [column[0] for column in self.description]
235 rows = [dict(zip(labels, row)) for row in rows]
237 if key_field is not None and key_field in labels:
238 # Return rows as a dictionary keyed on the specified field
239 # (like DBI selectall_hashref()).
240 return dict([(row[key_field], row) for row in rows])
244 def fields(self, table, notnull = None, hasdef = None):
246 Return the names of the fields of the specified table.
249 if hasattr(self, 'fields_cache'):
250 if self.fields_cache.has_key((table, notnull, hasdef)):
251 return self.fields_cache[(table, notnull, hasdef)]
253 self.fields_cache = {}
255 sql = "SELECT attname FROM pg_attribute, pg_class" \
256 " WHERE pg_class.oid = attrelid" \
257 " AND attnum > 0 AND relname = %(table)s"
259 if notnull is not None:
260 sql += " AND attnotnull is %(notnull)s"
262 if hasdef is not None:
263 sql += " AND atthasdef is %(hasdef)s"
265 rows = self.selectall(sql, locals(), hashref = False)
267 self.fields_cache[(table, notnull, hasdef)] = [row[0] for row in rows]
269 return self.fields_cache[(table, notnull, hasdef)]