984e51494df8df8f557d46eb1af9e2d2422354b9
[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.debug import *
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                     print >> log,'execute0',query
183                 cursor.execute(query)
184             elif isinstance(params,dict):
185                 if self.debug:
186                     print >> log,'execute-dict: params',params,'query',query%params
187                 cursor.execute(query,params)
188             elif isinstance(params,tuple) and len(params)==1:
189                 if self.debug:
190                     print >> log,'execute-tuple',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                         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)
200         except Exception, e:
201             try:
202                 self.rollback()
203             except:
204                 pass
205             uuid = commands.getoutput("uuidgen")
206             print >> log, "Database error %s:" % uuid
207             print >> log, e
208             print >> log, "Query:"
209             print >> log, query
210             print >> log, "Params:"
211             print >> log, pformat(params)
212             raise SfaDBError("Please contact support: %s" % str(e))
213
214         return cursor
215
216     def selectall(self, query, params = None, hashref = True, key_field = None):
217         """
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()).
222
223         If params is specified, the specified parameters will be bound
224         to the query.
225         """
226
227         cursor = self.execute(query, params)
228         rows = cursor.fetchall()
229         cursor.close()
230         self.commit()
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]
236
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])
241         else:
242             return rows
243
244     def fields(self, table, notnull = None, hasdef = None):
245         """
246         Return the names of the fields of the specified table.
247         """
248
249         if hasattr(self, 'fields_cache'):
250             if self.fields_cache.has_key((table, notnull, hasdef)):
251                 return self.fields_cache[(table, notnull, hasdef)]
252         else:
253             self.fields_cache = {}
254
255         sql = "SELECT attname FROM pg_attribute, pg_class" \
256               " WHERE pg_class.oid = attrelid" \
257               " AND attnum > 0 AND relname = %(table)s"
258
259         if notnull is not None:
260             sql += " AND attnotnull is %(notnull)s"
261
262         if hasdef is not None:
263             sql += " AND atthasdef is %(hasdef)s"
264
265         rows = self.selectall(sql, locals(), hashref = False)
266
267         self.fields_cache[(table, notnull, hasdef)] = [row[0] for row in rows]
268
269         return self.fields_cache[(table, notnull, hasdef)]