fix bug in get_aggregate_nodes()
[sfa.git] / sfa / storage / 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 SfaDBError
25 from sfa.util.sfalogging import logger
26 from sfa.storage.filter import Filter
27
28 if not psycopg2:
29     is8bit = re.compile("[\x80-\xff]").search
30
31     def unicast(typecast):
32         """
33         pgdb returns raw UTF-8 strings. This function casts strings that
34         apppear to contain non-ASCII characters to unicode objects.
35         """
36     
37         def wrapper(*args, **kwds):
38             value = typecast(*args, **kwds)
39
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")
45
46             return value
47
48         return wrapper
49
50     pgdb.pgdbTypeCache.typecast = unicast(pgdb.pgdbTypeCache.typecast)
51
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))
57     return wrapper
58
59 class PostgreSQL:
60     def __init__(self, config):
61         self.config = config
62         self.debug = False
63 #        self.debug = True
64         self.connection = None
65
66     @handle_exception
67     def cursor(self):
68         if self.connection is None:
69             # (Re)initialize database connection
70             if psycopg2:
71                 try:
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:
77                     # Fall back on TCP
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")
84             else:
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)
89
90         (self.rowcount, self.description, self.lastrowid) = \
91                         (None, None, None)
92
93         return self.connection.cursor()
94
95     def close(self):
96         if self.connection is not None:
97             self.connection.close()
98             self.connection = None
99
100     def quote(self, value):
101         """
102         Returns quoted version of the specified value.
103         """
104
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)
109         else:
110             return Filter._quote(value)
111
112     quote = classmethod(quote)
113
114     def param(self, name, value):
115         # None is converted to the unquoted string NULL
116         if isinstance(value, NoneType):
117             conversion = "s"
118         # True and False are also converted to unquoted strings
119         elif isinstance(value, bool):
120             conversion = "s"
121         elif isinstance(value, float):
122             conversion = "f"
123         elif not isinstance(value, StringTypes):
124             conversion = "d"
125         else:
126             conversion = "s"
127
128         return '%(' + name + ')' + conversion
129
130     param = classmethod(param)
131
132     def begin_work(self):
133         # Implicit in pgdb.connect()
134         pass
135
136     def commit(self):
137         self.connection.commit()
138
139     def rollback(self):
140         self.connection.rollback()
141
142     def do(self, query, params = None):
143         cursor = self.execute(query, params)
144         cursor.close()
145         return self.rowcount
146
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)
151         if rows: 
152             return rows[0][0]
153         return None 
154
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)
160             if rows:
161                 return rows[0][0]
162
163         return None
164
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):
171
172         cursor = self.cursor()
173         try:
174
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%'
180             if psycopg2:
181                 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
182             # rewrite wildcards set by Filter.py as '***' into '%'
183             query = query.replace ('***','%')
184
185             if not params:
186                 if self.debug:
187                     logger.debug('execute0 %r'%query)
188                 cursor.execute(query)
189             elif isinstance(params,dict):
190                 if self.debug:
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:
194                 if self.debug:
195                     logger.debug('execute-tuple %r'%(query%params[0]))
196                 cursor.execute(query,params[0])
197             else:
198                 param_seq=(params,)
199                 if self.debug:
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)
205         except Exception, e:
206             try:
207                 self.rollback()
208             except:
209                 pass
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))
217
218         return cursor
219
220     def selectall(self, query, params = None, hashref = True, key_field = None):
221         """
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()).
226
227         If params is specified, the specified parameters will be bound
228         to the query.
229         """
230
231         cursor = self.execute(query, params)
232         rows = cursor.fetchall()
233         cursor.close()
234         self.commit()
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]
240
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])
245         else:
246             return rows
247
248     def fields(self, table, notnull = None, hasdef = None):
249         """
250         Return the names of the fields of the specified table.
251         """
252
253         if hasattr(self, 'fields_cache'):
254             if self.fields_cache.has_key((table, notnull, hasdef)):
255                 return self.fields_cache[(table, notnull, hasdef)]
256         else:
257             self.fields_cache = {}
258
259         sql = "SELECT attname FROM pg_attribute, pg_class" \
260               " WHERE pg_class.oid = attrelid" \
261               " AND attnum > 0 AND relname = %(table)s"
262
263         if notnull is not None:
264             sql += " AND attnotnull is %(notnull)s"
265
266         if hasdef is not None:
267             sql += " AND atthasdef is %(hasdef)s"
268
269         rows = self.selectall(sql, locals(), hashref = False)
270
271         self.fields_cache[(table, notnull, hasdef)] = [row[0] for row in rows]
272
273         return self.fields_cache[(table, notnull, hasdef)]