reviewed imports, tolerant on some that are hard to get on a mac
[sfa.git] / sfa / util / PostgreSQL.py
1 #
2 # PostgreSQL database interface. Sort of like DBI(3) (Database
3 # independent interface for Perl).
4 #
5 #
6
7 import re
8 import traceback
9 import commands
10 from pprint import pformat
11 from types import StringTypes, NoneType
12
13 import psycopg2
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)
18
19 # allow to run sfa2wsdl if this is missing (for mac)
20 import sys
21 try: import pgdb
22 except: print >> sys.stderr, "WARNING, could not import pgdb"
23
24 from sfa.util.faults import *
25 from sfa.util.sfalogging import sfa_logger
26
27 if not psycopg2:
28     is8bit = re.compile("[\x80-\xff]").search
29
30     def unicast(typecast):
31         """
32         pgdb returns raw UTF-8 strings. This function casts strings that
33         apppear to contain non-ASCII characters to unicode objects.
34         """
35     
36         def wrapper(*args, **kwds):
37             value = typecast(*args, **kwds)
38
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")
44
45             return value
46
47         return wrapper
48
49     pgdb.pgdbTypeCache.typecast = unicast(pgdb.pgdbTypeCache.typecast)
50
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))
56     return wrapper
57
58 class PostgreSQL:
59     def __init__(self, config):
60         self.config = config
61         self.debug = False
62 #        self.debug = True
63         self.connection = None
64
65     @handle_exception
66     def cursor(self):
67         if self.connection is None:
68             # (Re)initialize database connection
69             if psycopg2:
70                 try:
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:
76                     # Fall back on TCP
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")
83             else:
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)
88
89         (self.rowcount, self.description, self.lastrowid) = \
90                         (None, None, None)
91
92         return self.connection.cursor()
93
94     def close(self):
95         if self.connection is not None:
96             self.connection.close()
97             self.connection = None
98
99     def quote(self, value):
100         """
101         Returns quoted version of the specified value.
102         """
103
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)
108         else:
109             return pgdb._quote(value)
110
111     quote = classmethod(quote)
112
113     def param(self, name, value):
114         # None is converted to the unquoted string NULL
115         if isinstance(value, NoneType):
116             conversion = "s"
117         # True and False are also converted to unquoted strings
118         elif isinstance(value, bool):
119             conversion = "s"
120         elif isinstance(value, float):
121             conversion = "f"
122         elif not isinstance(value, StringTypes):
123             conversion = "d"
124         else:
125             conversion = "s"
126
127         return '%(' + name + ')' + conversion
128
129     param = classmethod(param)
130
131     def begin_work(self):
132         # Implicit in pgdb.connect()
133         pass
134
135     def commit(self):
136         self.connection.commit()
137
138     def rollback(self):
139         self.connection.rollback()
140
141     def do(self, query, params = None):
142         cursor = self.execute(query, params)
143         cursor.close()
144         return self.rowcount
145
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)
150         if rows: 
151             return rows[0][0]
152         return None 
153
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)
159             if rows:
160                 return rows[0][0]
161
162         return None
163
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):
170
171         cursor = self.cursor()
172         try:
173
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%'
179             if psycopg2:
180                 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
181             # rewrite wildcards set by Filter.py as '***' into '%'
182             query = query.replace ('***','%')
183
184             if not params:
185                 if self.debug:
186                     sfa_logger().debug('execute0 %r'%query)
187                 cursor.execute(query)
188             elif isinstance(params,dict):
189                 if self.debug:
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:
193                 if self.debug:
194                     sfa_logger().debug('execute-tuple %r'%(query%params[0]))
195                 cursor.execute(query,params[0])
196             else:
197                 param_seq=(params,)
198                 if self.debug:
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)
204         except Exception, e:
205             try:
206                 self.rollback()
207             except:
208                 pass
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))
216
217         return cursor
218
219     def selectall(self, query, params = None, hashref = True, key_field = None):
220         """
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()).
225
226         If params is specified, the specified parameters will be bound
227         to the query.
228         """
229
230         cursor = self.execute(query, params)
231         rows = cursor.fetchall()
232         cursor.close()
233         self.commit()
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]
239
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])
244         else:
245             return rows
246
247     def fields(self, table, notnull = None, hasdef = None):
248         """
249         Return the names of the fields of the specified table.
250         """
251
252         if hasattr(self, 'fields_cache'):
253             if self.fields_cache.has_key((table, notnull, hasdef)):
254                 return self.fields_cache[(table, notnull, hasdef)]
255         else:
256             self.fields_cache = {}
257
258         sql = "SELECT attname FROM pg_attribute, pg_class" \
259               " WHERE pg_class.oid = attrelid" \
260               " AND attnum > 0 AND relname = %(table)s"
261
262         if notnull is not None:
263             sql += " AND attnotnull is %(notnull)s"
264
265         if hasdef is not None:
266             sql += " AND atthasdef is %(hasdef)s"
267
268         rows = self.selectall(sql, locals(), hashref = False)
269
270         self.fields_cache[(table, notnull, hasdef)] = [row[0] for row in rows]
271
272         return self.fields_cache[(table, notnull, hasdef)]