f2c51bfd24dd70d7cc023a4f233fc154c375afa4
[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 psycopg2
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)
12
13 import pgdb
14 from types import StringTypes, NoneType
15 import traceback
16 import commands
17 import re
18 from pprint import pformat
19
20 from sfa.util.faults import *
21 from sfa.util.sfalogging import sfa_logger
22
23 if not psycopg2:
24     is8bit = re.compile("[\x80-\xff]").search
25
26     def unicast(typecast):
27         """
28         pgdb returns raw UTF-8 strings. This function casts strings that
29         apppear to contain non-ASCII characters to unicode objects.
30         """
31     
32         def wrapper(*args, **kwds):
33             value = typecast(*args, **kwds)
34
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")
40
41             return value
42
43         return wrapper
44
45     pgdb.pgdbTypeCache.typecast = unicast(pgdb.pgdbTypeCache.typecast)
46
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))
52     return wrapper
53
54 class PostgreSQL:
55     def __init__(self, config):
56         self.config = config
57         self.debug = False
58 #        self.debug = True
59         self.connection = None
60
61     @handle_exception
62     def cursor(self):
63         if self.connection is None:
64             # (Re)initialize database connection
65             if psycopg2:
66                 try:
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:
72                     # Fall back on TCP
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")
79             else:
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)
84
85         (self.rowcount, self.description, self.lastrowid) = \
86                         (None, None, None)
87
88         return self.connection.cursor()
89
90     def close(self):
91         if self.connection is not None:
92             self.connection.close()
93             self.connection = None
94
95     def quote(self, value):
96         """
97         Returns quoted version of the specified value.
98         """
99
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)
104         else:
105             return pgdb._quote(value)
106
107     quote = classmethod(quote)
108
109     def param(self, name, value):
110         # None is converted to the unquoted string NULL
111         if isinstance(value, NoneType):
112             conversion = "s"
113         # True and False are also converted to unquoted strings
114         elif isinstance(value, bool):
115             conversion = "s"
116         elif isinstance(value, float):
117             conversion = "f"
118         elif not isinstance(value, StringTypes):
119             conversion = "d"
120         else:
121             conversion = "s"
122
123         return '%(' + name + ')' + conversion
124
125     param = classmethod(param)
126
127     def begin_work(self):
128         # Implicit in pgdb.connect()
129         pass
130
131     def commit(self):
132         self.connection.commit()
133
134     def rollback(self):
135         self.connection.rollback()
136
137     def do(self, query, params = None):
138         cursor = self.execute(query, params)
139         cursor.close()
140         return self.rowcount
141
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)
146         if rows: 
147             return rows[0][0]
148         return None 
149
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)
155             if rows:
156                 return rows[0][0]
157
158         return None
159
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):
166
167         cursor = self.cursor()
168         try:
169
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%'
175             if psycopg2:
176                 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
177             # rewrite wildcards set by Filter.py as '***' into '%'
178             query = query.replace ('***','%')
179
180             if not params:
181                 if self.debug:
182                     sfa_logger().debug('execute0 %r'%query)
183                 cursor.execute(query)
184             elif isinstance(params,dict):
185                 if self.debug:
186                     sfa_logger().debug('execute-dict: params=[%r] query=[%r]'%(params,query%params))
187                 cursor.execute(query,params)
188             elif isinstance(params,tuple) and len(params)==1:
189                 if self.debug:
190                     sfa_logger().debug('execute-tuple %r'%(query%params[0]))
191                 cursor.execute(query,params[0])
192             else:
193                 param_seq=(params,)
194                 if self.debug:
195                     for params in param_seq:
196                         sfa_logger().debug('executemany %r'%(query%params))
197                 cursor.executemany(query, param_seq)
198             (self.rowcount, self.description, self.lastrowid) = \
199                             (cursor.rowcount, cursor.description, cursor.lastrowid)
200         except Exception, e:
201             try:
202                 self.rollback()
203             except:
204                 pass
205             uuid = commands.getoutput("uuidgen")
206             sfa_logger().error("Database error %s:" % uuid)
207             sfa_logger().error("Exception=%r"%e)
208             sfa_logger().error("Query=%r"%query)
209             sfa_logger().error("Params=%r"%pformat(params))
210             sfa_logger().log_exc("PostgreSQL.execute caught exception")
211             raise SfaDBError("Please contact support: %s" % str(e))
212
213         return cursor
214
215     def selectall(self, query, params = None, hashref = True, key_field = None):
216         """
217         Return each row as a dictionary keyed on field name (like DBI
218         selectrow_hashref()). If key_field is specified, return rows
219         as a dictionary keyed on the specified field (like DBI
220         selectall_hashref()).
221
222         If params is specified, the specified parameters will be bound
223         to the query.
224         """
225
226         cursor = self.execute(query, params)
227         rows = cursor.fetchall()
228         cursor.close()
229         self.commit()
230         if hashref or key_field is not None:
231             # Return each row as a dictionary keyed on field name
232             # (like DBI selectrow_hashref()).
233             labels = [column[0] for column in self.description]
234             rows = [dict(zip(labels, row)) for row in rows]
235
236         if key_field is not None and key_field in labels:
237             # Return rows as a dictionary keyed on the specified field
238             # (like DBI selectall_hashref()).
239             return dict([(row[key_field], row) for row in rows])
240         else:
241             return rows
242
243     def fields(self, table, notnull = None, hasdef = None):
244         """
245         Return the names of the fields of the specified table.
246         """
247
248         if hasattr(self, 'fields_cache'):
249             if self.fields_cache.has_key((table, notnull, hasdef)):
250                 return self.fields_cache[(table, notnull, hasdef)]
251         else:
252             self.fields_cache = {}
253
254         sql = "SELECT attname FROM pg_attribute, pg_class" \
255               " WHERE pg_class.oid = attrelid" \
256               " AND attnum > 0 AND relname = %(table)s"
257
258         if notnull is not None:
259             sql += " AND attnotnull is %(notnull)s"
260
261         if hasdef is not None:
262             sql += " AND atthasdef is %(hasdef)s"
263
264         rows = self.selectall(sql, locals(), hashref = False)
265
266         self.fields_cache[(table, notnull, hasdef)] = [row[0] for row in rows]
267
268         return self.fields_cache[(table, notnull, hasdef)]