removed another bunch of references to geni
[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 class PostgreSQL:
48     def __init__(self, config):
49         self.config = config
50         self.debug = False
51 #        self.debug = True
52         self.connection = None
53
54     def cursor(self):
55         if self.connection is None:
56             # (Re)initialize database connection
57             if psycopg2:
58                 try:
59                     # Try UNIX socket first
60                     self.connection = psycopg2.connect(user = self.config.SFA_PLC_DB_USER,
61                                                        password = self.config.SFA_PLC_DB_PASSWORD,
62                                                        database = self.config.SFA_PLC_DB_NAME)
63                 except psycopg2.OperationalError:
64                     # Fall back on TCP
65                     self.connection = psycopg2.connect(user = self.config.SFA_PLC_DB_USER,
66                                                        password = self.config.SFA_PLC_DB_PASSWORD,
67                                                        database = self.config.SFA_PLC_DB_NAME,
68                                                        host = self.config.SFA_PLC_DB_HOST,
69                                                        port = self.config.SFA_PLC_DB_PORT)
70                 self.connection.set_client_encoding("UNICODE")
71             else:
72                 self.connection = pgdb.connect(user = self.config.SFA_PLC_DB_USER,
73                                                password = self.config.SFA_PLC_DB_PASSWORD,
74                                                host = "%s:%d" % (self.config.SFA_PLC_DB_HOST, self.config.SFA_PLC_DB_PORT),
75                                                database = self.config.SFA_PLC_DB_NAME)
76
77         (self.rowcount, self.description, self.lastrowid) = \
78                         (None, None, None)
79
80         return self.connection.cursor()
81
82     def close(self):
83         if self.connection is not None:
84             self.connection.close()
85             self.connection = None
86
87     def quote(self, value):
88         """
89         Returns quoted version of the specified value.
90         """
91
92         # The pgdb._quote function is good enough for general SQL
93         # quoting, except for array types.
94         if isinstance(value, (list, tuple, set)):
95             return "ARRAY[%s]" % ", ".join(map, self.quote, value)
96         else:
97             return pgdb._quote(value)
98
99     quote = classmethod(quote)
100
101     def param(self, name, value):
102         # None is converted to the unquoted string NULL
103         if isinstance(value, NoneType):
104             conversion = "s"
105         # True and False are also converted to unquoted strings
106         elif isinstance(value, bool):
107             conversion = "s"
108         elif isinstance(value, float):
109             conversion = "f"
110         elif not isinstance(value, StringTypes):
111             conversion = "d"
112         else:
113             conversion = "s"
114
115         return '%(' + name + ')' + conversion
116
117     param = classmethod(param)
118
119     def begin_work(self):
120         # Implicit in pgdb.connect()
121         pass
122
123     def commit(self):
124         self.connection.commit()
125
126     def rollback(self):
127         self.connection.rollback()
128
129     def do(self, query, params = None):
130         cursor = self.execute(query, params)
131         cursor.close()
132         return self.rowcount
133
134     def next_id(self, table_name, primary_key):
135         sequence = "%(table_name)s_%(primary_key)s_seq" % locals()      
136         sql = "SELECT nextval('%(sequence)s')" % locals()
137         rows = self.selectall(sql, hashref = False)
138         if rows: 
139             return rows[0][0]
140                 
141         return None 
142
143     def last_insert_id(self, table_name, primary_key):
144         if isinstance(self.lastrowid, int):
145             sql = "SELECT %s FROM %s WHERE oid = %d" % \
146                   (primary_key, table_name, self.lastrowid)
147             rows = self.selectall(sql, hashref = False)
148             if rows:
149                 return rows[0][0]
150
151         return None
152
153     # modified for psycopg2-2.0.7 
154     # executemany is undefined for SELECT's
155     # see http://www.python.org/dev/peps/pep-0249/
156     # accepts either None, a single dict, a tuple of single dict - in which case it execute's
157     # or a tuple of several dicts, in which case it executemany's
158     def execute(self, query, params = None):
159
160         cursor = self.cursor()
161         try:
162
163             # psycopg2 requires %()s format for all parameters,
164             # regardless of type.
165             # this needs to be done carefully though as with pattern-based filters
166             # we might have percents embedded in the query
167             # so e.g. GetPersons({'email':'*fake*'}) was resulting in .. LIKE '%sake%'
168             if psycopg2:
169                 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
170             # rewrite wildcards set by Filter.py as '***' into '%'
171             query = query.replace ('***','%')
172
173             if not params:
174                 if self.debug:
175                     print >> log,'execute0',query
176                 cursor.execute(query)
177             elif isinstance(params,dict):
178                 if self.debug:
179                     print >> log,'execute-dict: params',params,'query',query%params
180                 cursor.execute(query,params)
181             elif isinstance(params,tuple) and len(params)==1:
182                 if self.debug:
183                     print >> log,'execute-tuple',query%params[0]
184                 cursor.execute(query,params[0])
185             else:
186                 param_seq=(params,)
187                 if self.debug:
188                     for params in param_seq:
189                         print >> log,'executemany',query%params
190                 cursor.executemany(query, param_seq)
191             (self.rowcount, self.description, self.lastrowid) = \
192                             (cursor.rowcount, cursor.description, cursor.lastrowid)
193         except Exception, e:
194             try:
195                 self.rollback()
196             except:
197                 pass
198             uuid = commands.getoutput("uuidgen")
199             print >> log, "Database error %s:" % uuid
200             print >> log, e
201             print >> log, "Query:"
202             print >> log, query
203             print >> log, "Params:"
204             print >> log, pformat(params)
205             raise SfaDBError("Please contact support")
206
207         return cursor
208
209     def selectall(self, query, params = None, hashref = True, key_field = None):
210         """
211         Return each row as a dictionary keyed on field name (like DBI
212         selectrow_hashref()). If key_field is specified, return rows
213         as a dictionary keyed on the specified field (like DBI
214         selectall_hashref()).
215
216         If params is specified, the specified parameters will be bound
217         to the query.
218         """
219
220         cursor = self.execute(query, params)
221         rows = cursor.fetchall()
222         cursor.close()
223         self.commit()
224         if hashref or key_field is not None:
225             # Return each row as a dictionary keyed on field name
226             # (like DBI selectrow_hashref()).
227             labels = [column[0] for column in self.description]
228             rows = [dict(zip(labels, row)) for row in rows]
229
230         if key_field is not None and key_field in labels:
231             # Return rows as a dictionary keyed on the specified field
232             # (like DBI selectall_hashref()).
233             return dict([(row[key_field], row) for row in rows])
234         else:
235             return rows
236
237     def fields(self, table, notnull = None, hasdef = None):
238         """
239         Return the names of the fields of the specified table.
240         """
241
242         if hasattr(self, 'fields_cache'):
243             if self.fields_cache.has_key((table, notnull, hasdef)):
244                 return self.fields_cache[(table, notnull, hasdef)]
245         else:
246             self.fields_cache = {}
247
248         sql = "SELECT attname FROM pg_attribute, pg_class" \
249               " WHERE pg_class.oid = attrelid" \
250               " AND attnum > 0 AND relname = %(table)s"
251
252         if notnull is not None:
253             sql += " AND attnotnull is %(notnull)s"
254
255         if hasdef is not None:
256             sql += " AND atthasdef is %(hasdef)s"
257
258         rows = self.selectall(sql, locals(), hashref = False)
259
260         self.fields_cache[(table, notnull, hasdef)] = [row[0] for row in rows]
261
262         return self.fields_cache[(table, notnull, hasdef)]